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//   sphinx-build -b html _build/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 UsedDocs : Documentation {
61  let Category = DocCatFunction;
62  let Content = [{
63This attribute, when attached to a function or variable definition, indicates
64that there may be references to the entity which are not apparent in the source
65code.  For example, it may be referenced from inline ``asm``, or it may be
66found through a dynamic symbol or section lookup.
67
68The compiler must emit the definition even if it appears to be unused, and it
69must not apply optimizations which depend on fully understanding how the entity
70is used.
71
72Whether this attribute has any effect on the linker depends on the target and
73the linker. Most linkers support the feature of section garbage collection
74(``--gc-sections``), also known as "dead stripping" (``ld64 -dead_strip``) or
75discarding unreferenced sections (``link.exe /OPT:REF``). On COFF and Mach-O
76targets (Windows and Apple platforms), the `used` attribute prevents symbols
77from being removed by linker section GC. On ELF targets, it has no effect on its
78own, and the linker may remove the definition if it is not otherwise referenced.
79This linker GC can be avoided by also adding the ``retain`` attribute.  Note
80that ``retain`` requires special support from the linker; see that attribute's
81documentation for further information.
82  }];
83}
84
85def RetainDocs : Documentation {
86  let Category = DocCatFunction;
87  let Content = [{
88This attribute, when attached to a function or variable definition, prevents
89section garbage collection in the linker. It does not prevent other discard
90mechanisms, such as archive member selection, and COMDAT group resolution.
91
92If the compiler does not emit the definition, e.g. because it was not used in
93the translation unit or the compiler was able to eliminate all of the uses,
94this attribute has no effect.  This attribute is typically combined with the
95``used`` attribute to force the definition to be emitted and preserved into the
96final linked image.
97
98This attribute is only necessary on ELF targets; other targets prevent section
99garbage collection by the linker when using the ``used`` attribute alone.
100Using the attributes together should result in consistent behavior across
101targets.
102
103This attribute requires the linker to support the ``SHF_GNU_RETAIN`` extension.
104This support is available in GNU ``ld`` and ``gold`` as of binutils 2.36, as
105well as in ``ld.lld`` 13.
106  }];
107}
108
109def InitPriorityDocs : Documentation {
110  let Category = DocCatVariable;
111  let Content = [{
112In C++, the order in which global variables are initialized across translation
113units is unspecified, unlike the ordering within a single translation unit. The
114``init_priority`` attribute allows you to specify a relative ordering for the
115initialization of objects declared at namespace scope in C++. The priority is
116given as an integer constant expression between 101 and 65535 (inclusive).
117Priorities outside of that range are reserved for use by the implementation. A
118lower value indicates a higher priority of initialization. Note that only the
119relative ordering of values is important. For example:
120
121.. code-block:: c++
122
123  struct SomeType { SomeType(); };
124  __attribute__((init_priority(200))) SomeType Obj1;
125  __attribute__((init_priority(101))) SomeType Obj2;
126
127``Obj2`` will be initialized *before* ``Obj1`` despite the usual order of
128initialization being the opposite.
129
130This attribute is only supported for C++ and Objective-C++ and is ignored in
131other language modes. Currently, this attribute is not implemented on z/OS.
132  }];
133}
134
135def InitSegDocs : Documentation {
136  let Category = DocCatVariable;
137  let Content = [{
138The attribute applied by ``pragma init_seg()`` controls the section into
139which global initialization function pointers are emitted. It is only
140available with ``-fms-extensions``. Typically, this function pointer is
141emitted into ``.CRT$XCU`` on Windows. The user can change the order of
142initialization by using a different section name with the same
143``.CRT$XC`` prefix and a suffix that sorts lexicographically before or
144after the standard ``.CRT$XCU`` sections. See the init_seg_
145documentation on MSDN for more information.
146
147.. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx
148  }];
149}
150
151def TLSModelDocs : Documentation {
152  let Category = DocCatVariable;
153  let Content = [{
154The ``tls_model`` attribute allows you to specify which thread-local storage
155model to use. It accepts the following strings:
156
157* global-dynamic
158* local-dynamic
159* initial-exec
160* local-exec
161
162TLS models are mutually exclusive.
163  }];
164}
165
166def DLLExportDocs : Documentation {
167  let Category = DocCatVariable;
168  let Content = [{
169The ``__declspec(dllexport)`` attribute declares a variable, function, or
170Objective-C interface to be exported from the module. It is available under the
171``-fdeclspec`` flag for compatibility with various compilers. The primary use
172is for COFF object files which explicitly specify what interfaces are available
173for external use. See the dllexport_ documentation on MSDN for more
174information.
175
176.. _dllexport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx
177  }];
178}
179
180def DLLImportDocs : Documentation {
181  let Category = DocCatVariable;
182  let Content = [{
183The ``__declspec(dllimport)`` attribute declares a variable, function, or
184Objective-C interface to be imported from an external module. It is available
185under the ``-fdeclspec`` flag for compatibility with various compilers. The
186primary use is for COFF object files which explicitly specify what interfaces
187are imported from external modules. See the dllimport_ documentation on MSDN
188for more information.
189
190Note that a dllimport function may still be inlined, if its definition is
191available and it doesn't reference any non-dllimport functions or global
192variables.
193
194.. _dllimport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx
195  }];
196}
197
198def ThreadDocs : Documentation {
199  let Category = DocCatVariable;
200  let Content = [{
201The ``__declspec(thread)`` attribute declares a variable with thread local
202storage. It is available under the ``-fms-extensions`` flag for MSVC
203compatibility. See the documentation for `__declspec(thread)`_ on MSDN.
204
205.. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx
206
207In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the
208GNU ``__thread`` keyword. The variable must not have a destructor and must have
209a constant initializer, if any. The attribute only applies to variables
210declared with static storage duration, such as globals, class static data
211members, and static locals.
212  }];
213}
214
215def NoEscapeDocs : Documentation {
216  let Category = DocCatVariable;
217  let Content = [{
218``noescape`` placed on a function parameter of a pointer type is used to inform
219the compiler that the pointer cannot escape: that is, no reference to the object
220the pointer points to that is derived from the parameter value will survive
221after the function returns. Users are responsible for making sure parameters
222annotated with ``noescape`` do not actually escape. Calling ``free()`` on such
223a parameter does not constitute an escape.
224
225For example:
226
227.. code-block:: c
228
229  int *gp;
230
231  void nonescapingFunc(__attribute__((noescape)) int *p) {
232    *p += 100; // OK.
233  }
234
235  void escapingFunc(__attribute__((noescape)) int *p) {
236    gp = p; // Not OK.
237  }
238
239Additionally, when the parameter is a `block pointer
240<https://clang.llvm.org/docs/BlockLanguageSpec.html>`, the same restriction
241applies to copies of the block. For example:
242
243.. code-block:: c
244
245  typedef void (^BlockTy)();
246  BlockTy g0, g1;
247
248  void nonescapingFunc(__attribute__((noescape)) BlockTy block) {
249    block(); // OK.
250  }
251
252  void escapingFunc(__attribute__((noescape)) BlockTy block) {
253    g0 = block; // Not OK.
254    g1 = Block_copy(block); // Not OK either.
255  }
256
257  }];
258}
259
260def CarriesDependencyDocs : Documentation {
261  let Category = DocCatFunction;
262  let Content = [{
263The ``carries_dependency`` attribute specifies dependency propagation into and
264out of functions.
265
266When specified on a function or Objective-C method, the ``carries_dependency``
267attribute means that the return value carries a dependency out of the function,
268so that the implementation need not constrain ordering upon return from that
269function. Implementations of the function and its caller may choose to preserve
270dependencies instead of emitting memory ordering instructions such as fences.
271
272Note, this attribute does not change the meaning of the program, but may result
273in generation of more efficient code.
274  }];
275}
276
277def CPUSpecificCPUDispatchDocs : Documentation {
278  let Category = DocCatFunction;
279  let Content = [{
280The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and
281resolve multiversioned functions. This form of multiversioning provides a
282mechanism for declaring versions across translation units and manually
283specifying the resolved function list. A specified CPU defines a set of minimum
284features that are required for the function to be called. The result of this is
285that future processors execute the most restrictive version of the function the
286new processor can execute.
287
288In addition, unlike the ICC implementation of this feature, the selection of the
289version does not consider the manufacturer or microarchitecture of the processor.
290It tests solely the list of features that are both supported by the specified
291processor and present in the compiler-rt library. This can be surprising at times,
292as the runtime processor may be from a completely different manufacturer, as long
293as it supports the same feature set.
294
295This can additionally be surprising, as some processors are indistringuishable from
296others based on the list of testable features. When this happens, the variant
297is selected in an unspecified manner.
298
299Function versions are defined with ``cpu_specific``, which takes one or more CPU
300names as a parameter. For example:
301
302.. code-block:: c
303
304  // Declares and defines the ivybridge version of single_cpu.
305  __attribute__((cpu_specific(ivybridge)))
306  void single_cpu(void){}
307
308  // Declares and defines the atom version of single_cpu.
309  __attribute__((cpu_specific(atom)))
310  void single_cpu(void){}
311
312  // Declares and defines both the ivybridge and atom version of multi_cpu.
313  __attribute__((cpu_specific(ivybridge, atom)))
314  void multi_cpu(void){}
315
316A dispatching (or resolving) function can be declared anywhere in a project's
317source code with ``cpu_dispatch``. This attribute takes one or more CPU names
318as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch``
319are not expected to be defined, only declared. If such a marked function has a
320definition, any side effects of the function are ignored; trivial function
321bodies are permissible for ICC compatibility.
322
323.. code-block:: c
324
325  // Creates a resolver for single_cpu above.
326  __attribute__((cpu_dispatch(ivybridge, atom)))
327  void single_cpu(void){}
328
329  // Creates a resolver for multi_cpu, but adds a 3rd version defined in another
330  // translation unit.
331  __attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
332  void multi_cpu(void){}
333
334Note that it is possible to have a resolving function that dispatches based on
335more or fewer options than are present in the program. Specifying fewer will
336result in the omitted options not being considered during resolution. Specifying
337a version for resolution that isn't defined in the program will result in a
338linking failure.
339
340It is also possible to specify a CPU name of ``generic`` which will be resolved
341if the executing processor doesn't satisfy the features required in the CPU
342name. The behavior of a program executing on a processor that doesn't satisfy
343any option of a multiversioned function is undefined.
344  }];
345}
346
347def SYCLKernelDocs : Documentation {
348  let Category = DocCatFunction;
349  let Content = [{
350The ``sycl_kernel`` attribute specifies that a function template will be used
351to outline device code and to generate an OpenCL kernel.
352Here is a code example of the SYCL program, which demonstrates the compiler's
353outlining job:
354
355.. code-block:: c++
356
357  int foo(int x) { return ++x; }
358
359  using namespace cl::sycl;
360  queue Q;
361  buffer<int, 1> a(range<1>{1024});
362  Q.submit([&](handler& cgh) {
363    auto A = a.get_access<access::mode::write>(cgh);
364    cgh.parallel_for<init_a>(range<1>{1024}, [=](id<1> index) {
365      A[index] = index[0] + foo(42);
366    });
367  }
368
369A C++ function object passed to the ``parallel_for`` is called a "SYCL kernel".
370A SYCL kernel defines the entry point to the "device part" of the code. The
371compiler will emit all symbols accessible from a "kernel". In this code
372example, the compiler will emit "foo" function. More details about the
373compilation of functions for the device part can be found in the SYCL 1.2.1
374specification Section 6.4.
375To show to the compiler entry point to the "device part" of the code, the SYCL
376runtime can use the ``sycl_kernel`` attribute in the following way:
377
378.. code-block:: c++
379
380  namespace cl {
381  namespace sycl {
382  class handler {
383    template <typename KernelName, typename KernelType/*, ...*/>
384    __attribute__((sycl_kernel)) void sycl_kernel_function(KernelType KernelFuncObj) {
385      // ...
386      KernelFuncObj();
387    }
388
389    template <typename KernelName, typename KernelType, int Dims>
390    void parallel_for(range<Dims> NumWorkItems, KernelType KernelFunc) {
391  #ifdef __SYCL_DEVICE_ONLY__
392      sycl_kernel_function<KernelName, KernelType, Dims>(KernelFunc);
393  #else
394      // Host implementation
395  #endif
396    }
397  };
398  } // namespace sycl
399  } // namespace cl
400
401The compiler will also generate an OpenCL kernel using the function marked with
402the ``sycl_kernel`` attribute.
403Here is the list of SYCL device compiler expectations with regard to the
404function marked with the ``sycl_kernel`` attribute:
405
406- The function must be a template with at least two type template parameters.
407  The compiler generates an OpenCL kernel and uses the first template parameter
408  as a unique name for the generated OpenCL kernel. The host application uses
409  this unique name to invoke the OpenCL kernel generated for the SYCL kernel
410  specialized by this name and second template parameter ``KernelType`` (which
411  might be an unnamed function object type).
412- The function must have at least one parameter. The first parameter is
413  required to be a function object type (named or unnamed i.e. lambda). The
414  compiler uses function object type fields to generate OpenCL kernel
415  parameters.
416- The function must return void. The compiler reuses the body of marked functions to
417  generate the OpenCL kernel body, and the OpenCL kernel must return ``void``.
418
419The SYCL kernel in the previous code sample meets these expectations.
420  }];
421}
422
423def SYCLSpecialClassDocs : Documentation {
424  let Category = DocCatStmt;
425  let Content = [{
426SYCL defines some special classes (accessor, sampler, and stream) which require
427specific handling during the generation of the SPIR entry point.
428The ``__attribute__((sycl_special_class))`` attribute is used in SYCL
429headers to indicate that a class or a struct needs a specific handling when
430it is passed from host to device.
431Special classes will have a mandatory ``__init`` method and an optional
432``__finalize`` method (the ``__finalize`` method is used only with the
433``stream`` type). Kernel parameters types are extract from the ``__init`` method
434parameters. The kernel function arguments list is derived from the
435arguments of the ``__init`` method. The arguments of the ``__init`` method are
436copied into the kernel function argument list and the ``__init`` and
437``__finalize`` methods are called at the beginning and the end of the kernel,
438respectively.
439The ``__init`` and ``__finalize`` methods must be defined inside the
440special class.
441Please note that this is an attribute that is used as an internal
442implementation detail and not intended to be used by external users.
443
444The syntax of the attribute is as follows:
445
446.. code-block:: text
447
448  class __attribute__((sycl_special_class)) accessor {};
449  class [[clang::sycl_special_class]] accessor {};
450
451This is a code example that illustrates the use of the attribute:
452
453.. code-block:: c++
454
455  class __attribute__((sycl_special_class)) SpecialType {
456    int F1;
457    int F2;
458    void __init(int f1) {
459      F1 = f1;
460      F2 = f1;
461    }
462    void __finalize() {}
463  public:
464    SpecialType() = default;
465    int getF2() const { return F2; }
466  };
467
468  int main () {
469    SpecialType T;
470    cgh.single_task([=] {
471      T.getF2();
472    });
473  }
474
475This would trigger the following kernel entry point in the AST:
476
477.. code-block:: c++
478
479  void __sycl_kernel(int f1) {
480    SpecialType T;
481    T.__init(f1);
482    ...
483    T.__finalize()
484  }
485  }];
486}
487
488def C11NoReturnDocs : Documentation {
489  let Category = DocCatFunction;
490  let Content = [{
491A function declared as ``_Noreturn`` shall not return to its caller. The
492compiler will generate a diagnostic for a function declared as ``_Noreturn``
493that appears to be capable of returning to its caller. Despite being a type
494specifier, the ``_Noreturn`` attribute cannot be specified on a function
495pointer type.
496  }];
497}
498
499def CXX11NoReturnDocs : Documentation {
500  let Category = DocCatFunction;
501  let Heading = "noreturn, _Noreturn";
502  let Content = [{
503A function declared as ``[[noreturn]]`` shall not return to its caller. The
504compiler will generate a diagnostic for a function declared as ``[[noreturn]]``
505that appears to be capable of returning to its caller.
506
507The ``[[_Noreturn]]`` spelling is deprecated and only exists to ease code
508migration for code using ``[[noreturn]]`` after including ``<stdnoreturn.h>``.
509  }];
510}
511
512def NoMergeDocs : Documentation {
513  let Category = DocCatStmt;
514  let Content = [{
515If a statement is marked ``nomerge`` and contains call expressions, those call
516expressions inside the statement will not be merged during optimization. This
517attribute can be used to prevent the optimizer from obscuring the source
518location of certain calls. For example, it will prevent tail merging otherwise
519identical code sequences that raise an exception or terminate the program. Tail
520merging normally reduces the precision of source location information, making
521stack traces less useful for debugging. This attribute gives the user control
522over the tradeoff between code size and debug information precision.
523
524``nomerge`` attribute can also be used as function attribute to prevent all
525calls to the specified function from merging. It has no effect on indirect
526calls.
527  }];
528}
529
530def NoInlineDocs : Documentation {
531  let Category = DocCatFunction;
532  let Content = [{
533This function attribute suppresses the inlining of a function at the call sites
534of the function.
535
536``[[clang::noinline]]`` spelling can be used as a statement attribute; other
537spellings of the attribute are not supported on statements. If a statement is
538marked ``[[clang::noinline]]`` and contains calls, those calls inside the
539statement will not be inlined by the compiler.
540
541``__noinline__`` can be used as a keyword in CUDA/HIP languages. This is to
542avoid diagnostics due to usage of ``__attribute__((__noinline__))``
543with ``__noinline__`` defined as a macro as ``__attribute__((noinline))``.
544
545.. code-block:: c
546
547  int example(void) {
548    int r;
549    [[clang::noinline]] foo();
550    [[clang::noinline]] r = bar();
551    return r;
552  }
553
554  }];
555}
556
557def MustTailDocs : Documentation {
558  let Category = DocCatStmt;
559  let Content = [{
560If a ``return`` statement is marked ``musttail``, this indicates that the
561compiler must generate a tail call for the program to be correct, even when
562optimizations are disabled. This guarantees that the call will not cause
563unbounded stack growth if it is part of a recursive cycle in the call graph.
564
565If the callee is a virtual function that is implemented by a thunk, there is
566no guarantee in general that the thunk tail-calls the implementation of the
567virtual function, so such a call in a recursive cycle can still result in
568unbounded stack growth.
569
570``clang::musttail`` can only be applied to a ``return`` statement whose value
571is the result of a function call (even functions returning void must use
572``return``, although no value is returned). The target function must have the
573same number of arguments as the caller. The types of the return value and all
574arguments must be similar according to C++ rules (differing only in cv
575qualifiers or array size), including the implicit "this" argument, if any.
576Any variables in scope, including all arguments to the function and the
577return value must be trivially destructible. The calling convention of the
578caller and callee must match, and they must not be variadic functions or have
579old style K&R C function declarations.
580  }];
581}
582
583def AssertCapabilityDocs : Documentation {
584  let Category = DocCatFunction;
585  let Heading = "assert_capability, assert_shared_capability";
586  let Content = [{
587Marks a function that dynamically tests whether a capability is held, and halts
588the program if it is not held.
589  }];
590}
591
592def AcquireCapabilityDocs : Documentation {
593  let Category = DocCatFunction;
594  let Heading = "acquire_capability, acquire_shared_capability";
595  let Content = [{
596Marks a function as acquiring a capability.
597  }];
598}
599
600def TryAcquireCapabilityDocs : Documentation {
601  let Category = DocCatFunction;
602  let Heading = "try_acquire_capability, try_acquire_shared_capability";
603  let Content = [{
604Marks a function that attempts to acquire a capability. This function may fail to
605actually acquire the capability; they accept a Boolean value determining
606whether acquiring the capability means success (true), or failing to acquire
607the capability means success (false).
608  }];
609}
610
611def ReleaseCapabilityDocs : Documentation {
612  let Category = DocCatFunction;
613  let Heading = "release_capability, release_shared_capability";
614  let Content = [{
615Marks a function as releasing a capability.
616  }];
617}
618
619def AssumeAlignedDocs : Documentation {
620  let Category = DocCatFunction;
621  let Content = [{
622Use ``__attribute__((assume_aligned(<alignment>[,<offset>]))`` on a function
623declaration to specify that the return value of the function (which must be a
624pointer type) has the specified offset, in bytes, from an address with the
625specified alignment. The offset is taken to be zero if omitted.
626
627.. code-block:: c++
628
629  // The returned pointer value has 32-byte alignment.
630  void *a() __attribute__((assume_aligned (32)));
631
632  // The returned pointer value is 4 bytes greater than an address having
633  // 32-byte alignment.
634  void *b() __attribute__((assume_aligned (32, 4)));
635
636Note that this attribute provides information to the compiler regarding a
637condition that the code already ensures is true. It does not cause the compiler
638to enforce the provided alignment assumption.
639  }];
640}
641
642def AllocSizeDocs : Documentation {
643  let Category = DocCatFunction;
644  let Content = [{
645The ``alloc_size`` attribute can be placed on functions that return pointers in
646order to hint to the compiler how many bytes of memory will be available at the
647returned pointer. ``alloc_size`` takes one or two arguments.
648
649- ``alloc_size(N)`` implies that argument number N equals the number of
650  available bytes at the returned pointer.
651- ``alloc_size(N, M)`` implies that the product of argument number N and
652  argument number M equals the number of available bytes at the returned
653  pointer.
654
655Argument numbers are 1-based.
656
657An example of how to use ``alloc_size``
658
659.. code-block:: c
660
661  void *my_malloc(int a) __attribute__((alloc_size(1)));
662  void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2)));
663
664  int main() {
665    void *const p = my_malloc(100);
666    assert(__builtin_object_size(p, 0) == 100);
667    void *const a = my_calloc(20, 5);
668    assert(__builtin_object_size(a, 0) == 100);
669  }
670
671.. Note:: This attribute works differently in clang than it does in GCC.
672  Specifically, clang will only trace ``const`` pointers (as above); we give up
673  on pointers that are not marked as ``const``. In the vast majority of cases,
674  this is unimportant, because LLVM has support for the ``alloc_size``
675  attribute. However, this may cause mildly unintuitive behavior when used with
676  other attributes, such as ``enable_if``.
677  }];
678}
679
680def CodeSegDocs : Documentation {
681  let Category = DocCatFunction;
682  let Content = [{
683The ``__declspec(code_seg)`` attribute enables the placement of code into separate
684named segments that can be paged or locked in memory individually. This attribute
685is used to control the placement of instantiated templates and compiler-generated
686code. See the documentation for `__declspec(code_seg)`_ on MSDN.
687
688.. _`__declspec(code_seg)`: http://msdn.microsoft.com/en-us/library/dn636922.aspx
689  }];
690}
691
692def AllocAlignDocs : Documentation {
693  let Category = DocCatFunction;
694  let Content = [{
695Use ``__attribute__((alloc_align(<alignment>))`` on a function
696declaration to specify that the return value of the function (which must be a
697pointer type) is at least as aligned as the value of the indicated parameter. The
698parameter is given by its index in the list of formal parameters; the first
699parameter has index 1 unless the function is a C++ non-static member function,
700in which case the first parameter has index 2 to account for the implicit ``this``
701parameter.
702
703.. code-block:: c++
704
705  // The returned pointer has the alignment specified by the first parameter.
706  void *a(size_t align) __attribute__((alloc_align(1)));
707
708  // The returned pointer has the alignment specified by the second parameter.
709  void *b(void *v, size_t align) __attribute__((alloc_align(2)));
710
711  // The returned pointer has the alignment specified by the second visible
712  // parameter, however it must be adjusted for the implicit 'this' parameter.
713  void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3)));
714
715Note that this attribute merely informs the compiler that a function always
716returns a sufficiently aligned pointer. It does not cause the compiler to
717emit code to enforce that alignment. The behavior is undefined if the returned
718pointer is not sufficiently aligned.
719  }];
720}
721
722def EnableIfDocs : Documentation {
723  let Category = DocCatFunction;
724  let Content = [{
725.. Note:: Some features of this attribute are experimental. The meaning of
726  multiple enable_if attributes on a single declaration is subject to change in
727  a future version of clang. Also, the ABI is not standardized and the name
728  mangling may change in future versions. To avoid that, use asm labels.
729
730The ``enable_if`` attribute can be placed on function declarations to control
731which overload is selected based on the values of the function's arguments.
732When combined with the ``overloadable`` attribute, this feature is also
733available in C.
734
735.. code-block:: c++
736
737  int isdigit(int c);
738  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")));
739
740  void foo(char c) {
741    isdigit(c);
742    isdigit(10);
743    isdigit(-10);  // results in a compile-time error.
744  }
745
746The enable_if attribute takes two arguments, the first is an expression written
747in terms of the function parameters, the second is a string explaining why this
748overload candidate could not be selected to be displayed in diagnostics. The
749expression is part of the function signature for the purposes of determining
750whether it is a redeclaration (following the rules used when determining
751whether a C++ template specialization is ODR-equivalent), but is not part of
752the type.
753
754The enable_if expression is evaluated as if it were the body of a
755bool-returning constexpr function declared with the arguments of the function
756it is being applied to, then called with the parameters at the call site. If the
757result is false or could not be determined through constant expression
758evaluation, then this overload will not be chosen and the provided string may
759be used in a diagnostic if the compile fails as a result.
760
761Because the enable_if expression is an unevaluated context, there are no global
762state changes, nor the ability to pass information from the enable_if
763expression to the function body. For example, suppose we want calls to
764strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
765strbuf) only if the size of strbuf can be determined:
766
767.. code-block:: c++
768
769  __attribute__((always_inline))
770  static inline size_t strnlen(const char *s, size_t maxlen)
771    __attribute__((overloadable))
772    __attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
773                             "chosen when the buffer size is known but 'maxlen' is not")))
774  {
775    return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
776  }
777
778Multiple enable_if attributes may be applied to a single declaration. In this
779case, the enable_if expressions are evaluated from left to right in the
780following manner. First, the candidates whose enable_if expressions evaluate to
781false or cannot be evaluated are discarded. If the remaining candidates do not
782share ODR-equivalent enable_if expressions, the overload resolution is
783ambiguous. Otherwise, enable_if overload resolution continues with the next
784enable_if attribute on the candidates that have not been discarded and have
785remaining enable_if attributes. In this way, we pick the most specific
786overload out of a number of viable overloads using enable_if.
787
788.. code-block:: c++
789
790  void f() __attribute__((enable_if(true, "")));  // #1
791  void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, "")));  // #2
792
793  void g(int i, int j) __attribute__((enable_if(i, "")));  // #1
794  void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true)));  // #2
795
796In this example, a call to f() is always resolved to #2, as the first enable_if
797expression is ODR-equivalent for both declarations, but #1 does not have another
798enable_if expression to continue evaluating, so the next round of evaluation has
799only a single candidate. In a call to g(1, 1), the call is ambiguous even though
800#2 has more enable_if attributes, because the first enable_if expressions are
801not ODR-equivalent.
802
803Query for this feature with ``__has_attribute(enable_if)``.
804
805Note that functions with one or more ``enable_if`` attributes may not have
806their address taken, unless all of the conditions specified by said
807``enable_if`` are constants that evaluate to ``true``. For example:
808
809.. code-block:: c
810
811  const int TrueConstant = 1;
812  const int FalseConstant = 0;
813  int f(int a) __attribute__((enable_if(a > 0, "")));
814  int g(int a) __attribute__((enable_if(a == 0 || a != 0, "")));
815  int h(int a) __attribute__((enable_if(1, "")));
816  int i(int a) __attribute__((enable_if(TrueConstant, "")));
817  int j(int a) __attribute__((enable_if(FalseConstant, "")));
818
819  void fn() {
820    int (*ptr)(int);
821    ptr = &f; // error: 'a > 0' is not always true
822    ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant
823    ptr = &h; // OK: 1 is a truthy constant
824    ptr = &i; // OK: 'TrueConstant' is a truthy constant
825    ptr = &j; // error: 'FalseConstant' is a constant, but not truthy
826  }
827
828Because ``enable_if`` evaluation happens during overload resolution,
829``enable_if`` may give unintuitive results when used with templates, depending
830on when overloads are resolved. In the example below, clang will emit a
831diagnostic about no viable overloads for ``foo`` in ``bar``, but not in ``baz``:
832
833.. code-block:: c++
834
835  double foo(int i) __attribute__((enable_if(i > 0, "")));
836  void *foo(int i) __attribute__((enable_if(i <= 0, "")));
837  template <int I>
838  auto bar() { return foo(I); }
839
840  template <typename T>
841  auto baz() { return foo(T::number); }
842
843  struct WithNumber { constexpr static int number = 1; };
844  void callThem() {
845    bar<sizeof(WithNumber)>();
846    baz<WithNumber>();
847  }
848
849This is because, in ``bar``, ``foo`` is resolved prior to template
850instantiation, so the value for ``I`` isn't known (thus, both ``enable_if``
851conditions for ``foo`` fail). However, in ``baz``, ``foo`` is resolved during
852template instantiation, so the value for ``T::number`` is known.
853  }];
854}
855
856def DiagnoseIfDocs : Documentation {
857  let Category = DocCatFunction;
858  let Content = [{
859The ``diagnose_if`` attribute can be placed on function declarations to emit
860warnings or errors at compile-time if calls to the attributed function meet
861certain user-defined criteria. For example:
862
863.. code-block:: c
864
865  int abs(int a)
866    __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning")));
867  int must_abs(int a)
868    __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error")));
869
870  int val = abs(1); // warning: Redundant abs call
871  int val2 = must_abs(1); // error: Redundant abs call
872  int val3 = abs(val);
873  int val4 = must_abs(val); // Because run-time checks are not emitted for
874                            // diagnose_if attributes, this executes without
875                            // issue.
876
877
878``diagnose_if`` is closely related to ``enable_if``, with a few key differences:
879
880* Overload resolution is not aware of ``diagnose_if`` attributes: they're
881  considered only after we select the best candidate from a given candidate set.
882* Function declarations that differ only in their ``diagnose_if`` attributes are
883  considered to be redeclarations of the same function (not overloads).
884* If the condition provided to ``diagnose_if`` cannot be evaluated, no
885  diagnostic will be emitted.
886
887Otherwise, ``diagnose_if`` is essentially the logical negation of ``enable_if``.
888
889As a result of bullet number two, ``diagnose_if`` attributes will stack on the
890same function. For example:
891
892.. code-block:: c
893
894  int foo() __attribute__((diagnose_if(1, "diag1", "warning")));
895  int foo() __attribute__((diagnose_if(1, "diag2", "warning")));
896
897  int bar = foo(); // warning: diag1
898                   // warning: diag2
899  int (*fooptr)(void) = foo; // warning: diag1
900                             // warning: diag2
901
902  constexpr int supportsAPILevel(int N) { return N < 5; }
903  int baz(int a)
904    __attribute__((diagnose_if(!supportsAPILevel(10),
905                               "Upgrade to API level 10 to use baz", "error")));
906  int baz(int a)
907    __attribute__((diagnose_if(!a, "0 is not recommended.", "warning")));
908
909  int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz
910  int v = baz(0); // error: Upgrade to API level 10 to use baz
911
912Query for this feature with ``__has_attribute(diagnose_if)``.
913  }];
914}
915
916def PassObjectSizeDocs : Documentation {
917  let Category = DocCatVariable; // Technically it's a parameter doc, but eh.
918  let Heading = "pass_object_size, pass_dynamic_object_size";
919  let Content = [{
920.. Note:: The mangling of functions with parameters that are annotated with
921  ``pass_object_size`` is subject to change. You can get around this by
922  using ``__asm__("foo")`` to explicitly name your functions, thus preserving
923  your ABI; also, non-overloadable C functions with ``pass_object_size`` are
924  not mangled.
925
926The ``pass_object_size(Type)`` attribute can be placed on function parameters to
927instruct clang to call ``__builtin_object_size(param, Type)`` at each callsite
928of said function, and implicitly pass the result of this call in as an invisible
929argument of type ``size_t`` directly after the parameter annotated with
930``pass_object_size``. Clang will also replace any calls to
931``__builtin_object_size(param, Type)`` in the function by said implicit
932parameter.
933
934Example usage:
935
936.. code-block:: c
937
938  int bzero1(char *const p __attribute__((pass_object_size(0))))
939      __attribute__((noinline)) {
940    int i = 0;
941    for (/**/; i < (int)__builtin_object_size(p, 0); ++i) {
942      p[i] = 0;
943    }
944    return i;
945  }
946
947  int main() {
948    char chars[100];
949    int n = bzero1(&chars[0]);
950    assert(n == sizeof(chars));
951    return 0;
952  }
953
954If successfully evaluating ``__builtin_object_size(param, Type)`` at the
955callsite is not possible, then the "failed" value is passed in. So, using the
956definition of ``bzero1`` from above, the following code would exit cleanly:
957
958.. code-block:: c
959
960  int main2(int argc, char *argv[]) {
961    int n = bzero1(argv);
962    assert(n == -1);
963    return 0;
964  }
965
966``pass_object_size`` plays a part in overload resolution. If two overload
967candidates are otherwise equally good, then the overload with one or more
968parameters with ``pass_object_size`` is preferred. This implies that the choice
969between two identical overloads both with ``pass_object_size`` on one or more
970parameters will always be ambiguous; for this reason, having two such overloads
971is illegal. For example:
972
973.. code-block:: c++
974
975  #define PS(N) __attribute__((pass_object_size(N)))
976  // OK
977  void Foo(char *a, char *b); // Overload A
978  // OK -- overload A has no parameters with pass_object_size.
979  void Foo(char *a PS(0), char *b PS(0)); // Overload B
980  // Error -- Same signature (sans pass_object_size) as overload B, and both
981  // overloads have one or more parameters with the pass_object_size attribute.
982  void Foo(void *a PS(0), void *b);
983
984  // OK
985  void Bar(void *a PS(0)); // Overload C
986  // OK
987  void Bar(char *c PS(1)); // Overload D
988
989  void main() {
990    char known[10], *unknown;
991    Foo(unknown, unknown); // Calls overload B
992    Foo(known, unknown); // Calls overload B
993    Foo(unknown, known); // Calls overload B
994    Foo(known, known); // Calls overload B
995
996    Bar(known); // Calls overload D
997    Bar(unknown); // Calls overload D
998  }
999
1000Currently, ``pass_object_size`` is a bit restricted in terms of its usage:
1001
1002* Only one use of ``pass_object_size`` is allowed per parameter.
1003
1004* It is an error to take the address of a function with ``pass_object_size`` on
1005  any of its parameters. If you wish to do this, you can create an overload
1006  without ``pass_object_size`` on any parameters.
1007
1008* It is an error to apply the ``pass_object_size`` attribute to parameters that
1009  are not pointers. Additionally, any parameter that ``pass_object_size`` is
1010  applied to must be marked ``const`` at its function's definition.
1011
1012Clang also supports the ``pass_dynamic_object_size`` attribute, which behaves
1013identically to ``pass_object_size``, but evaluates a call to
1014``__builtin_dynamic_object_size`` at the callee instead of
1015``__builtin_object_size``. ``__builtin_dynamic_object_size`` provides some extra
1016runtime checks when the object size can't be determined at compile-time. You can
1017read more about ``__builtin_dynamic_object_size`` `here
1018<https://clang.llvm.org/docs/LanguageExtensions.html#evaluating-object-size-dynamically>`_.
1019
1020  }];
1021}
1022
1023def OverloadableDocs : Documentation {
1024  let Category = DocCatFunction;
1025  let Content = [{
1026Clang provides support for C++ function overloading in C. Function overloading
1027in C is introduced using the ``overloadable`` attribute. For example, one
1028might provide several overloaded versions of a ``tgsin`` function that invokes
1029the appropriate standard function computing the sine of a value with ``float``,
1030``double``, or ``long double`` precision:
1031
1032.. code-block:: c
1033
1034  #include <math.h>
1035  float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
1036  double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
1037  long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
1038
1039Given these declarations, one can call ``tgsin`` with a ``float`` value to
1040receive a ``float`` result, with a ``double`` to receive a ``double`` result,
1041etc. Function overloading in C follows the rules of C++ function overloading
1042to pick the best overload given the call arguments, with a few C-specific
1043semantics:
1044
1045* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
1046  floating-point promotion (per C99) rather than as a floating-point conversion
1047  (as in C++).
1048
1049* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
1050  considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
1051  compatible types.
1052
1053* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
1054  and ``U`` are compatible types. This conversion is given "conversion" rank.
1055
1056* If no viable candidates are otherwise available, we allow a conversion from a
1057  pointer of type ``T*`` to a pointer of type ``U*``, where ``T`` and ``U`` are
1058  incompatible. This conversion is ranked below all other types of conversions.
1059  Please note: ``U`` lacking qualifiers that are present on ``T`` is sufficient
1060  for ``T`` and ``U`` to be incompatible.
1061
1062The declaration of ``overloadable`` functions is restricted to function
1063declarations and definitions. If a function is marked with the ``overloadable``
1064attribute, then all declarations and definitions of functions with that name,
1065except for at most one (see the note below about unmarked overloads), must have
1066the ``overloadable`` attribute. In addition, redeclarations of a function with
1067the ``overloadable`` attribute must have the ``overloadable`` attribute, and
1068redeclarations of a function without the ``overloadable`` attribute must *not*
1069have the ``overloadable`` attribute. e.g.,
1070
1071.. code-block:: c
1072
1073  int f(int) __attribute__((overloadable));
1074  float f(float); // error: declaration of "f" must have the "overloadable" attribute
1075  int f(int); // error: redeclaration of "f" must have the "overloadable" attribute
1076
1077  int g(int) __attribute__((overloadable));
1078  int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
1079
1080  int h(int);
1081  int h(int) __attribute__((overloadable)); // error: declaration of "h" must not
1082                                            // have the "overloadable" attribute
1083
1084Functions marked ``overloadable`` must have prototypes. Therefore, the
1085following code is ill-formed:
1086
1087.. code-block:: c
1088
1089  int h() __attribute__((overloadable)); // error: h does not have a prototype
1090
1091However, ``overloadable`` functions are allowed to use a ellipsis even if there
1092are no named parameters (as is permitted in C++). This feature is particularly
1093useful when combined with the ``unavailable`` attribute:
1094
1095.. code-block:: c++
1096
1097  void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
1098
1099Functions declared with the ``overloadable`` attribute have their names mangled
1100according to the same rules as C++ function names. For example, the three
1101``tgsin`` functions in our motivating example get the mangled names
1102``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two
1103caveats to this use of name mangling:
1104
1105* Future versions of Clang may change the name mangling of functions overloaded
1106  in C, so you should not depend on an specific mangling. To be completely
1107  safe, we strongly urge the use of ``static inline`` with ``overloadable``
1108  functions.
1109
1110* The ``overloadable`` attribute has almost no meaning when used in C++,
1111  because names will already be mangled and functions are already overloadable.
1112  However, when an ``overloadable`` function occurs within an ``extern "C"``
1113  linkage specification, it's name *will* be mangled in the same way as it
1114  would in C.
1115
1116For the purpose of backwards compatibility, at most one function with the same
1117name as other ``overloadable`` functions may omit the ``overloadable``
1118attribute. In this case, the function without the ``overloadable`` attribute
1119will not have its name mangled.
1120
1121For example:
1122
1123.. code-block:: c
1124
1125  // Notes with mangled names assume Itanium mangling.
1126  int f(int);
1127  int f(double) __attribute__((overloadable));
1128  void foo() {
1129    f(5); // Emits a call to f (not _Z1fi, as it would with an overload that
1130          // was marked with overloadable).
1131    f(1.0); // Emits a call to _Z1fd.
1132  }
1133
1134Support for unmarked overloads is not present in some versions of clang. You may
1135query for it using ``__has_extension(overloadable_unmarked)``.
1136
1137Query for this attribute with ``__has_attribute(overloadable)``.
1138  }];
1139}
1140
1141def ObjCMethodFamilyDocs : Documentation {
1142  let Category = DocCatFunction;
1143  let Content = [{
1144Many methods in Objective-C have conventional meanings determined by their
1145selectors. It is sometimes useful to be able to mark a method as having a
1146particular conventional meaning despite not having the right selector, or as
1147not having the conventional meaning that its selector would suggest. For these
1148use cases, we provide an attribute to specifically describe the "method family"
1149that a method belongs to.
1150
1151**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
1152``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This
1153attribute can only be placed at the end of a method declaration:
1154
1155.. code-block:: objc
1156
1157  - (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
1158
1159Users who do not wish to change the conventional meaning of a method, and who
1160merely want to document its non-standard retain and release semantics, should
1161use the retaining behavior attributes (``ns_returns_retained``,
1162``ns_returns_not_retained``, etc).
1163
1164Query for this feature with ``__has_attribute(objc_method_family)``.
1165  }];
1166}
1167
1168def RetainBehaviorDocs : Documentation {
1169  let Category = DocCatFunction;
1170  let Content = [{
1171The behavior of a function with respect to reference counting for Foundation
1172(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1173convention (e.g. functions starting with "get" are assumed to return at
1174``+0``).
1175
1176It can be overridden using a family of the following attributes. In
1177Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
1178a function communicates that the object is returned at ``+1``, and the caller
1179is responsible for freeing it.
1180Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
1181specifies that the object is returned at ``+0`` and the ownership remains with
1182the callee.
1183The annotation ``__attribute__((ns_consumes_self))`` specifies that
1184the Objective-C method call consumes the reference to ``self``, e.g. by
1185attaching it to a supplied parameter.
1186Additionally, parameters can have an annotation
1187``__attribute__((ns_consumed))``, which specifies that passing an owned object
1188as that parameter effectively transfers the ownership, and the caller is no
1189longer responsible for it.
1190These attributes affect code generation when interacting with ARC code, and
1191they are used by the Clang Static Analyzer.
1192
1193In C programs using CoreFoundation, a similar set of attributes:
1194``__attribute__((cf_returns_not_retained))``,
1195``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
1196have the same respective semantics when applied to CoreFoundation objects.
1197These attributes affect code generation when interacting with ARC code, and
1198they are used by the Clang Static Analyzer.
1199
1200Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1201the same attribute family is present:
1202``__attribute__((os_returns_not_retained))``,
1203``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
1204with the same respective semantics.
1205Similar to ``__attribute__((ns_consumes_self))``,
1206``__attribute__((os_consumes_this))`` specifies that the method call consumes
1207the reference to "this" (e.g., when attaching it to a different object supplied
1208as a parameter).
1209Out parameters (parameters the function is meant to write into,
1210either via pointers-to-pointers or references-to-pointers)
1211may be annotated with ``__attribute__((os_returns_retained))``
1212or ``__attribute__((os_returns_not_retained))`` which specifies that the object
1213written into the out parameter should (or respectively should not) be released
1214after use.
1215Since often out parameters may or may not be written depending on the exit
1216code of the function,
1217annotations ``__attribute__((os_returns_retained_on_zero))``
1218and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
1219an out parameter at ``+1`` is written if and only if the function returns a zero
1220(respectively non-zero) error code.
1221Observe that return-code-dependent out parameter annotations are only
1222available for retained out parameters, as non-retained object do not have to be
1223released by the callee.
1224These attributes are only used by the Clang Static Analyzer.
1225
1226The family of attributes ``X_returns_X_retained`` can be added to functions,
1227C++ methods, and Objective-C methods and properties.
1228Attributes ``X_consumed`` can be added to parameters of methods, functions,
1229and Objective-C methods.
1230  }];
1231}
1232
1233def NoDebugDocs : Documentation {
1234  let Category = DocCatVariable;
1235  let Content = [{
1236The ``nodebug`` attribute allows you to suppress debugging information for a
1237function or method, for a variable that is not a parameter or a non-static
1238data member, or for a typedef or using declaration.
1239  }];
1240}
1241
1242def StandaloneDebugDocs : Documentation {
1243  let Category = DocCatVariable;
1244  let Content = [{
1245The ``standalone_debug`` attribute causes debug info to be emitted for a record
1246type regardless of the debug info optimizations that are enabled with
1247-fno-standalone-debug. This attribute only has an effect when debug info
1248optimizations are enabled (e.g. with -fno-standalone-debug), and is C++-only.
1249  }];
1250}
1251
1252def NoDuplicateDocs : Documentation {
1253  let Category = DocCatFunction;
1254  let Content = [{
1255The ``noduplicate`` attribute can be placed on function declarations to control
1256whether function calls to this function can be duplicated or not as a result of
1257optimizations. This is required for the implementation of functions with
1258certain special requirements, like the OpenCL "barrier" function, that might
1259need to be run concurrently by all the threads that are executing in lockstep
1260on the hardware. For example this attribute applied on the function
1261"nodupfunc" in the code below avoids that:
1262
1263.. code-block:: c
1264
1265  void nodupfunc() __attribute__((noduplicate));
1266  // Setting it as a C++11 attribute is also valid
1267  // void nodupfunc() [[clang::noduplicate]];
1268  void foo();
1269  void bar();
1270
1271  nodupfunc();
1272  if (a > n) {
1273    foo();
1274  } else {
1275    bar();
1276  }
1277
1278gets possibly modified by some optimizations into code similar to this:
1279
1280.. code-block:: c
1281
1282  if (a > n) {
1283    nodupfunc();
1284    foo();
1285  } else {
1286    nodupfunc();
1287    bar();
1288  }
1289
1290where the call to "nodupfunc" is duplicated and sunk into the two branches
1291of the condition.
1292  }];
1293}
1294
1295def ConvergentDocs : Documentation {
1296  let Category = DocCatFunction;
1297  let Content = [{
1298The ``convergent`` attribute can be placed on a function declaration. It is
1299translated into the LLVM ``convergent`` attribute, which indicates that the call
1300instructions of a function with this attribute cannot be made control-dependent
1301on any additional values.
1302
1303In languages designed for SPMD/SIMT programming model, e.g. OpenCL or CUDA,
1304the call instructions of a function with this attribute must be executed by
1305all work items or threads in a work group or sub group.
1306
1307This attribute is different from ``noduplicate`` because it allows duplicating
1308function calls if it can be proved that the duplicated function calls are
1309not made control-dependent on any additional values, e.g., unrolling a loop
1310executed by all work items.
1311
1312Sample usage:
1313
1314.. code-block:: c
1315
1316  void convfunc(void) __attribute__((convergent));
1317  // Setting it as a C++11 attribute is also valid in a C++ program.
1318  // void convfunc(void) [[clang::convergent]];
1319
1320  }];
1321}
1322
1323def NoSplitStackDocs : Documentation {
1324  let Category = DocCatFunction;
1325  let Content = [{
1326The ``no_split_stack`` attribute disables the emission of the split stack
1327preamble for a particular function. It has no effect if ``-fsplit-stack``
1328is not specified.
1329  }];
1330}
1331
1332def NoUniqueAddressDocs : Documentation {
1333  let Category = DocCatField;
1334  let Content = [{
1335The ``no_unique_address`` attribute allows tail padding in a non-static data
1336member to overlap other members of the enclosing class (and in the special
1337case when the type is empty, permits it to fully overlap other members).
1338The field is laid out as if a base class were encountered at the corresponding
1339point within the class (except that it does not share a vptr with the enclosing
1340object).
1341
1342Example usage:
1343
1344.. code-block:: c++
1345
1346  template<typename T, typename Alloc> struct my_vector {
1347    T *p;
1348    [[no_unique_address]] Alloc alloc;
1349    // ...
1350  };
1351  static_assert(sizeof(my_vector<int, std::allocator<int>>) == sizeof(int*));
1352
1353``[[no_unique_address]]`` is a standard C++20 attribute. Clang supports its use
1354in C++11 onwards.
1355  }];
1356}
1357
1358def ObjCRequiresSuperDocs : Documentation {
1359  let Category = DocCatFunction;
1360  let Content = [{
1361Some Objective-C classes allow a subclass to override a particular method in a
1362parent class but expect that the overriding method also calls the overridden
1363method in the parent class. For these cases, we provide an attribute to
1364designate that a method requires a "call to ``super``" in the overriding
1365method in the subclass.
1366
1367**Usage**: ``__attribute__((objc_requires_super))``. This attribute can only
1368be placed at the end of a method declaration:
1369
1370.. code-block:: objc
1371
1372  - (void)foo __attribute__((objc_requires_super));
1373
1374This attribute can only be applied the method declarations within a class, and
1375not a protocol. Currently this attribute does not enforce any placement of
1376where the call occurs in the overriding method (such as in the case of
1377``-dealloc`` where the call must appear at the end). It checks only that it
1378exists.
1379
1380Note that on both OS X and iOS that the Foundation framework provides a
1381convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this
1382attribute:
1383
1384.. code-block:: objc
1385
1386  - (void)foo NS_REQUIRES_SUPER;
1387
1388This macro is conditionally defined depending on the compiler's support for
1389this attribute. If the compiler does not support the attribute the macro
1390expands to nothing.
1391
1392Operationally, when a method has this annotation the compiler will warn if the
1393implementation of an override in a subclass does not call super. For example:
1394
1395.. code-block:: objc
1396
1397   warning: method possibly missing a [super AnnotMeth] call
1398   - (void) AnnotMeth{};
1399                      ^
1400  }];
1401}
1402
1403def ObjCRuntimeNameDocs : Documentation {
1404    let Category = DocCatDecl;
1405    let Content = [{
1406By default, the Objective-C interface or protocol identifier is used
1407in the metadata name for that object. The ``objc_runtime_name``
1408attribute allows annotated interfaces or protocols to use the
1409specified string argument in the object's metadata name instead of the
1410default name.
1411
1412**Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``. This attribute
1413can only be placed before an @protocol or @interface declaration:
1414
1415.. code-block:: objc
1416
1417  __attribute__((objc_runtime_name("MyLocalName")))
1418  @interface Message
1419  @end
1420
1421    }];
1422}
1423
1424def ObjCRuntimeVisibleDocs : Documentation {
1425    let Category = DocCatDecl;
1426    let Content = [{
1427This attribute specifies that the Objective-C class to which it applies is
1428visible to the Objective-C runtime but not to the linker. Classes annotated
1429with this attribute cannot be subclassed and cannot have categories defined for
1430them.
1431    }];
1432}
1433
1434def ObjCClassStubDocs : Documentation {
1435    let Category = DocCatType;
1436    let Content = [{
1437This attribute specifies that the Objective-C class to which it applies is
1438instantiated at runtime.
1439
1440Unlike ``__attribute__((objc_runtime_visible))``, a class having this attribute
1441still has a "class stub" that is visible to the linker. This allows categories
1442to be defined. Static message sends with the class as a receiver use a special
1443access pattern to ensure the class is lazily instantiated from the class stub.
1444
1445Classes annotated with this attribute cannot be subclassed and cannot have
1446implementations defined for them. This attribute is intended for use in
1447Swift-generated headers for classes defined in Swift.
1448
1449Adding or removing this attribute to a class is an ABI-breaking change.
1450    }];
1451}
1452
1453def ObjCBoxableDocs : Documentation {
1454    let Category = DocCatDecl;
1455    let Content = [{
1456Structs and unions marked with the ``objc_boxable`` attribute can be used
1457with the Objective-C boxed expression syntax, ``@(...)``.
1458
1459**Usage**: ``__attribute__((objc_boxable))``. This attribute
1460can only be placed on a declaration of a trivially-copyable struct or union:
1461
1462.. code-block:: objc
1463
1464  struct __attribute__((objc_boxable)) some_struct {
1465    int i;
1466  };
1467  union __attribute__((objc_boxable)) some_union {
1468    int i;
1469    float f;
1470  };
1471  typedef struct __attribute__((objc_boxable)) _some_struct some_struct;
1472
1473  // ...
1474
1475  some_struct ss;
1476  NSValue *boxed = @(ss);
1477
1478    }];
1479}
1480
1481def AvailabilityDocs : Documentation {
1482  let Category = DocCatFunction;
1483  let Content = [{
1484The ``availability`` attribute can be placed on declarations to describe the
1485lifecycle of that declaration relative to operating system versions. Consider
1486the function declaration for a hypothetical function ``f``:
1487
1488.. code-block:: c++
1489
1490  void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
1491
1492The availability attribute states that ``f`` was introduced in macOS 10.4,
1493deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information
1494is used by Clang to determine when it is safe to use ``f``: for example, if
1495Clang is instructed to compile code for macOS 10.5, a call to ``f()``
1496succeeds. If Clang is instructed to compile code for macOS 10.6, the call
1497succeeds but Clang emits a warning specifying that the function is deprecated.
1498Finally, if Clang is instructed to compile code for macOS 10.7, the call
1499fails because ``f()`` is no longer available.
1500
1501The availability attribute is a comma-separated list starting with the
1502platform name and then including clauses specifying important milestones in the
1503declaration's lifetime (in any order) along with additional information. Those
1504clauses can be:
1505
1506introduced=\ *version*
1507  The first version in which this declaration was introduced.
1508
1509deprecated=\ *version*
1510  The first version in which this declaration was deprecated, meaning that
1511  users should migrate away from this API.
1512
1513obsoleted=\ *version*
1514  The first version in which this declaration was obsoleted, meaning that it
1515  was removed completely and can no longer be used.
1516
1517unavailable
1518  This declaration is never available on this platform.
1519
1520message=\ *string-literal*
1521  Additional message text that Clang will provide when emitting a warning or
1522  error about use of a deprecated or obsoleted declaration. Useful to direct
1523  users to replacement APIs.
1524
1525replacement=\ *string-literal*
1526  Additional message text that Clang will use to provide Fix-It when emitting
1527  a warning about use of a deprecated declaration. The Fix-It will replace
1528  the deprecated declaration with the new declaration specified.
1529
1530Multiple availability attributes can be placed on a declaration, which may
1531correspond to different platforms. For most platforms, the availability
1532attribute with the platform corresponding to the target platform will be used;
1533any others will be ignored. However, the availability for ``watchOS`` and
1534``tvOS`` can be implicitly inferred from an ``iOS`` availability attribute.
1535Any explicit availability attributes for those platforms are still preferred over
1536the implicitly inferred availability attributes. If no availability attribute
1537specifies availability for the current target platform, the availability
1538attributes are ignored. Supported platforms are:
1539
1540``ios``
1541  Apple's iOS operating system. The minimum deployment target is specified by
1542  the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*``
1543  command-line arguments.
1544
1545``macos``
1546  Apple's macOS operating system. The minimum deployment target is
1547  specified by the ``-mmacosx-version-min=*version*`` command-line argument.
1548  ``macosx`` is supported for backward-compatibility reasons, but it is
1549  deprecated.
1550
1551``tvos``
1552  Apple's tvOS operating system. The minimum deployment target is specified by
1553  the ``-mtvos-version-min=*version*`` command-line argument.
1554
1555``watchos``
1556  Apple's watchOS operating system. The minimum deployment target is specified by
1557  the ``-mwatchos-version-min=*version*`` command-line argument.
1558
1559``driverkit``
1560  Apple's DriverKit userspace kernel extensions. The minimum deployment target
1561  is specified as part of the triple.
1562
1563A declaration can typically be used even when deploying back to a platform
1564version prior to when the declaration was introduced. When this happens, the
1565declaration is `weakly linked
1566<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
1567as if the ``weak_import`` attribute were added to the declaration. A
1568weakly-linked declaration may or may not be present a run-time, and a program
1569can determine whether the declaration is present by checking whether the
1570address of that declaration is non-NULL.
1571
1572The flag ``strict`` disallows using API when deploying back to a
1573platform version prior to when the declaration was introduced. An
1574attempt to use such API before its introduction causes a hard error.
1575Weakly-linking is almost always a better API choice, since it allows
1576users to query availability at runtime.
1577
1578If there are multiple declarations of the same entity, the availability
1579attributes must either match on a per-platform basis or later
1580declarations must not have availability attributes for that
1581platform. For example:
1582
1583.. code-block:: c
1584
1585  void g(void) __attribute__((availability(macos,introduced=10.4)));
1586  void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches
1587  void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
1588  void g(void); // okay, inherits both macos and ios availability from above.
1589  void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch
1590
1591When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
1592
1593.. code-block:: objc
1594
1595  @interface A
1596  - (id)method __attribute__((availability(macos,introduced=10.4)));
1597  - (id)method2 __attribute__((availability(macos,introduced=10.4)));
1598  @end
1599
1600  @interface B : A
1601  - (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later
1602  - (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4
1603  @end
1604
1605Starting with the macOS 10.12 SDK, the ``API_AVAILABLE`` macro from
1606``<os/availability.h>`` can simplify the spelling:
1607
1608.. code-block:: objc
1609
1610  @interface A
1611  - (id)method API_AVAILABLE(macos(10.11)));
1612  - (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0));
1613  @end
1614
1615Availability attributes can also be applied using a ``#pragma clang attribute``.
1616Any explicit availability attribute whose platform corresponds to the target
1617platform is applied to a declaration regardless of the availability attributes
1618specified in the pragma. For example, in the code below,
1619``hasExplicitAvailabilityAttribute`` will use the ``macOS`` availability
1620attribute that is specified with the declaration, whereas
1621``getsThePragmaAvailabilityAttribute`` will use the ``macOS`` availability
1622attribute that is applied by the pragma.
1623
1624.. code-block:: c
1625
1626  #pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function)
1627  void getsThePragmaAvailabilityAttribute(void);
1628  void hasExplicitAvailabilityAttribute(void) __attribute__((availability(macos,introduced=10.4)));
1629  #pragma clang attribute pop
1630
1631For platforms like ``watchOS`` and ``tvOS``, whose availability attributes can
1632be implicitly inferred from an ``iOS`` availability attribute, the logic is
1633slightly more complex. The explicit and the pragma-applied availability
1634attributes whose platform corresponds to the target platform are applied as
1635described in the previous paragraph. However, the implicitly inferred attributes
1636are applied to a declaration only when there is no explicit or pragma-applied
1637availability attribute whose platform corresponds to the target platform. For
1638example, the function below will receive the ``tvOS`` availability from the
1639pragma rather than using the inferred ``iOS`` availability from the declaration:
1640
1641.. code-block:: c
1642
1643  #pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function)
1644  void getsThePragmaTVOSAvailabilityAttribute(void) __attribute__((availability(iOS,introduced=11.0)));
1645  #pragma clang attribute pop
1646
1647The compiler is also able to apply implicitly inferred attributes from a pragma
1648as well. For example, when targeting ``tvOS``, the function below will receive
1649a ``tvOS`` availability attribute that is implicitly inferred from the ``iOS``
1650availability attribute applied by the pragma:
1651
1652.. code-block:: c
1653
1654  #pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function)
1655  void infersTVOSAvailabilityFromPragma(void);
1656  #pragma clang attribute pop
1657
1658The implicit attributes that are inferred from explicitly specified attributes
1659whose platform corresponds to the target platform are applied to the declaration
1660even if there is an availability attribute that can be inferred from a pragma.
1661For example, the function below will receive the ``tvOS, introduced=11.0``
1662availability that is inferred from the attribute on the declaration rather than
1663inferring availability from the pragma:
1664
1665.. code-block:: c
1666
1667  #pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function)
1668  void infersTVOSAvailabilityFromAttributeNextToDeclaration(void)
1669    __attribute__((availability(iOS,introduced=11.0)));
1670  #pragma clang attribute pop
1671
1672Also see the documentation for `@available
1673<http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-available>`_
1674  }];
1675}
1676
1677def ExternalSourceSymbolDocs : Documentation {
1678  let Category = DocCatDecl;
1679  let Content = [{
1680The ``external_source_symbol`` attribute specifies that a declaration originates
1681from an external source and describes the nature of that source.
1682
1683The fact that Clang is capable of recognizing declarations that were defined
1684externally can be used to provide better tooling support for mixed-language
1685projects or projects that rely on auto-generated code. For instance, an IDE that
1686uses Clang and that supports mixed-language projects can use this attribute to
1687provide a correct 'jump-to-definition' feature. For a concrete example,
1688consider a protocol that's defined in a Swift file:
1689
1690.. code-block:: swift
1691
1692  @objc public protocol SwiftProtocol {
1693    func method()
1694  }
1695
1696This protocol can be used from Objective-C code by including a header file that
1697was generated by the Swift compiler. The declarations in that header can use
1698the ``external_source_symbol`` attribute to make Clang aware of the fact
1699that ``SwiftProtocol`` actually originates from a Swift module:
1700
1701.. code-block:: objc
1702
1703  __attribute__((external_source_symbol(language="Swift",defined_in="module")))
1704  @protocol SwiftProtocol
1705  @required
1706  - (void) method;
1707  @end
1708
1709Consequently, when 'jump-to-definition' is performed at a location that
1710references ``SwiftProtocol``, the IDE can jump to the original definition in
1711the Swift source file rather than jumping to the Objective-C declaration in the
1712auto-generated header file.
1713
1714The ``external_source_symbol`` attribute is a comma-separated list that includes
1715clauses that describe the origin and the nature of the particular declaration.
1716Those clauses can be:
1717
1718language=\ *string-literal*
1719  The name of the source language in which this declaration was defined.
1720
1721defined_in=\ *string-literal*
1722  The name of the source container in which the declaration was defined. The
1723  exact definition of source container is language-specific, e.g. Swift's
1724  source containers are modules, so ``defined_in`` should specify the Swift
1725  module name.
1726
1727generated_declaration
1728  This declaration was automatically generated by some tool.
1729
1730The clauses can be specified in any order. The clauses that are listed above are
1731all optional, but the attribute has to have at least one clause.
1732  }];
1733}
1734
1735def ConstInitDocs : Documentation {
1736  let Category = DocCatVariable;
1737  let Heading = "require_constant_initialization, constinit (C++20)";
1738  let Content = [{
1739This attribute specifies that the variable to which it is attached is intended
1740to have a `constant initializer <http://en.cppreference.com/w/cpp/language/constant_initialization>`_
1741according to the rules of [basic.start.static]. The variable is required to
1742have static or thread storage duration. If the initialization of the variable
1743is not a constant initializer an error will be produced. This attribute may
1744only be used in C++; the ``constinit`` spelling is only accepted in C++20
1745onwards.
1746
1747Note that in C++03 strict constant expression checking is not done. Instead
1748the attribute reports if Clang can emit the variable as a constant, even if it's
1749not technically a 'constant initializer'. This behavior is non-portable.
1750
1751Static storage duration variables with constant initializers avoid hard-to-find
1752bugs caused by the indeterminate order of dynamic initialization. They can also
1753be safely used during dynamic initialization across translation units.
1754
1755This attribute acts as a compile time assertion that the requirements
1756for constant initialization have been met. Since these requirements change
1757between dialects and have subtle pitfalls it's important to fail fast instead
1758of silently falling back on dynamic initialization.
1759
1760The first use of the attribute on a variable must be part of, or precede, the
1761initializing declaration of the variable. C++20 requires the ``constinit``
1762spelling of the attribute to be present on the initializing declaration if it
1763is used anywhere. The other spellings can be specified on a forward declaration
1764and omitted on a later initializing declaration.
1765
1766.. code-block:: c++
1767
1768  // -std=c++14
1769  #define SAFE_STATIC [[clang::require_constant_initialization]]
1770  struct T {
1771    constexpr T(int) {}
1772    ~T(); // non-trivial
1773  };
1774  SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor.
1775  SAFE_STATIC T y = 42; // error: variable does not have a constant initializer
1776  // copy initialization is not a constant expression on a non-literal type.
1777  }];
1778}
1779
1780def WarnMaybeUnusedDocs : Documentation {
1781  let Category = DocCatVariable;
1782  let Heading = "maybe_unused, unused";
1783  let Content = [{
1784When passing the ``-Wunused`` flag to Clang, entities that are unused by the
1785program may be diagnosed. The ``[[maybe_unused]]`` (or
1786``__attribute__((unused))``) attribute can be used to silence such diagnostics
1787when the entity cannot be removed. For instance, a local variable may exist
1788solely for use in an ``assert()`` statement, which makes the local variable
1789unused when ``NDEBUG`` is defined.
1790
1791The attribute may be applied to the declaration of a class, a typedef, a
1792variable, a function or method, a function parameter, an enumeration, an
1793enumerator, a non-static data member, or a label.
1794
1795.. code-block: c++
1796  #include <cassert>
1797
1798  [[maybe_unused]] void f([[maybe_unused]] bool thing1,
1799                          [[maybe_unused]] bool thing2) {
1800    [[maybe_unused]] bool b = thing1 && thing2;
1801    assert(b);
1802  }
1803  }];
1804}
1805
1806def WarnUnusedResultsDocs : Documentation {
1807  let Category = DocCatFunction;
1808  let Heading = "nodiscard, warn_unused_result";
1809  let Content  = [{
1810Clang supports the ability to diagnose when the results of a function call
1811expression are discarded under suspicious circumstances. A diagnostic is
1812generated when a function or its return type is marked with ``[[nodiscard]]``
1813(or ``__attribute__((warn_unused_result))``) and the function call appears as a
1814potentially-evaluated discarded-value expression that is not explicitly cast to
1815``void``.
1816
1817A string literal may optionally be provided to the attribute, which will be
1818reproduced in any resulting diagnostics. Redeclarations using different forms
1819of the attribute (with or without the string literal or with different string
1820literal contents) are allowed. If there are redeclarations of the entity with
1821differing string literals, it is unspecified which one will be used by Clang
1822in any resulting diagnostics.
1823
1824.. code-block: c++
1825  struct [[nodiscard]] error_info { /*...*/ };
1826  error_info enable_missile_safety_mode();
1827
1828  void launch_missiles();
1829  void test_missiles() {
1830    enable_missile_safety_mode(); // diagnoses
1831    launch_missiles();
1832  }
1833  error_info &foo();
1834  void f() { foo(); } // Does not diagnose, error_info is a reference.
1835
1836Additionally, discarded temporaries resulting from a call to a constructor
1837marked with ``[[nodiscard]]`` or a constructor of a type marked
1838``[[nodiscard]]`` will also diagnose. This also applies to type conversions that
1839use the annotated ``[[nodiscard]]`` constructor or result in an annotated type.
1840
1841.. code-block: c++
1842  struct [[nodiscard]] marked_type {/*..*/ };
1843  struct marked_ctor {
1844    [[nodiscard]] marked_ctor();
1845    marked_ctor(int);
1846  };
1847
1848  struct S {
1849    operator marked_type() const;
1850    [[nodiscard]] operator int() const;
1851  };
1852
1853  void usages() {
1854    marked_type(); // diagnoses.
1855    marked_ctor(); // diagnoses.
1856    marked_ctor(3); // Does not diagnose, int constructor isn't marked nodiscard.
1857
1858    S s;
1859    static_cast<marked_type>(s); // diagnoses
1860    (int)s; // diagnoses
1861  }
1862  }];
1863}
1864
1865def FallthroughDocs : Documentation {
1866  let Category = DocCatStmt;
1867  let Heading = "fallthrough";
1868  let Content = [{
1869The ``fallthrough`` (or ``clang::fallthrough``) attribute is used
1870to annotate intentional fall-through
1871between switch labels. It can only be applied to a null statement placed at a
1872point of execution between any statement and the next switch label. It is
1873common to mark these places with a specific comment, but this attribute is
1874meant to replace comments with a more strict annotation, which can be checked
1875by the compiler. This attribute doesn't change semantics of the code and can
1876be used wherever an intended fall-through occurs. It is designed to mimic
1877control-flow statements like ``break;``, so it can be placed in most places
1878where ``break;`` can, but only if there are no statements on the execution path
1879between it and the next switch label.
1880
1881By default, Clang does not warn on unannotated fallthrough from one ``switch``
1882case to another. Diagnostics on fallthrough without a corresponding annotation
1883can be enabled with the ``-Wimplicit-fallthrough`` argument.
1884
1885Here is an example:
1886
1887.. code-block:: c++
1888
1889  // compile with -Wimplicit-fallthrough
1890  switch (n) {
1891  case 22:
1892  case 33:  // no warning: no statements between case labels
1893    f();
1894  case 44:  // warning: unannotated fall-through
1895    g();
1896    [[clang::fallthrough]];
1897  case 55:  // no warning
1898    if (x) {
1899      h();
1900      break;
1901    }
1902    else {
1903      i();
1904      [[clang::fallthrough]];
1905    }
1906  case 66:  // no warning
1907    p();
1908    [[clang::fallthrough]]; // warning: fallthrough annotation does not
1909                            //          directly precede case label
1910    q();
1911  case 77:  // warning: unannotated fall-through
1912    r();
1913  }
1914  }];
1915}
1916
1917def LikelihoodDocs : Documentation {
1918  let Category = DocCatStmt;
1919  let Heading = "likely and unlikely";
1920  let Content = [{
1921The ``likely`` and ``unlikely`` attributes are used as compiler hints.
1922The attributes are used to aid the compiler to determine which branch is
1923likely or unlikely to be taken. This is done by marking the branch substatement
1924with one of the two attributes.
1925
1926It isn't allowed to annotate a single statement with both ``likely`` and
1927``unlikely``. Annotating the ``true`` and ``false`` branch of an ``if``
1928statement with the same likelihood attribute will result in a diagnostic and
1929the attributes are ignored on both branches.
1930
1931In a ``switch`` statement it's allowed to annotate multiple ``case`` labels
1932or the ``default`` label with the same likelihood attribute. This makes
1933* all labels without an attribute have a neutral likelihood,
1934* all labels marked ``[[likely]]`` have an equally positive likelihood, and
1935* all labels marked ``[[unlikely]]`` have an equally negative likelihood.
1936The neutral likelihood is the more likely of path execution than the negative
1937likelihood. The positive likelihood is the more likely of path of execution
1938than the neutral likelihood.
1939
1940These attributes have no effect on the generated code when using
1941PGO (Profile-Guided Optimization) or at optimization level 0.
1942
1943In Clang, the attributes will be ignored if they're not placed on
1944* the ``case`` or ``default`` label of a ``switch`` statement,
1945* or on the substatement of an ``if`` or ``else`` statement,
1946* or on the substatement of an ``for`` or ``while`` statement.
1947The C++ Standard recommends to honor them on every statement in the
1948path of execution, but that can be confusing:
1949
1950.. code-block:: c++
1951
1952  if (b) {
1953    [[unlikely]] --b; // In the path of execution,
1954                      // this branch is considered unlikely.
1955  }
1956
1957  if (b) {
1958    --b;
1959    if(b)
1960      return;
1961    [[unlikely]] --b; // Not in the path of execution,
1962  }                   // the branch has no likelihood information.
1963
1964  if (b) {
1965    --b;
1966    foo(b);
1967    // Whether or not the next statement is in the path of execution depends
1968    // on the declaration of foo():
1969    // In the path of execution: void foo(int);
1970    // Not in the path of execution: [[noreturn]] void foo(int);
1971    // This means the likelihood of the branch depends on the declaration
1972    // of foo().
1973    [[unlikely]] --b;
1974  }
1975
1976
1977Below are some example usages of the likelihood attributes and their effects:
1978
1979.. code-block:: c++
1980
1981  if (b) [[likely]] { // Placement on the first statement in the branch.
1982    // The compiler will optimize to execute the code here.
1983  } else {
1984  }
1985
1986  if (b)
1987    [[unlikely]] b++; // Placement on the first statement in the branch.
1988  else {
1989    // The compiler will optimize to execute the code here.
1990  }
1991
1992  if (b) {
1993    [[unlikely]] b++; // Placement on the second statement in the branch.
1994  }                   // The attribute will be ignored.
1995
1996  if (b) [[likely]] {
1997    [[unlikely]] b++; // No contradiction since the second attribute
1998  }                   // is ignored.
1999
2000  if (b)
2001    ;
2002  else [[likely]] {
2003    // The compiler will optimize to execute the code here.
2004  }
2005
2006  if (b)
2007    ;
2008  else
2009    // The compiler will optimize to execute the next statement.
2010    [[likely]] b = f();
2011
2012  if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
2013  else [[likely]];   // and the attributes are ignored.
2014
2015  if (b)
2016    [[likely]] int i = 5; // Issues a diagnostic since the attribute
2017                          // isn't allowed on a declaration.
2018
2019  switch (i) {
2020    [[likely]] case 1:    // This value is likely
2021      ...
2022      break;
2023
2024    [[unlikely]] case 2:  // This value is unlikely
2025      ...
2026      [[fallthrough]];
2027
2028    case 3:               // No likelihood attribute
2029      ...
2030      [[likely]] break;   // No effect
2031
2032    case 4: [[likely]] {  // attribute on substatement has no effect
2033      ...
2034      break;
2035      }
2036
2037    [[unlikely]] default: // All other values are unlikely
2038      ...
2039      break;
2040  }
2041
2042  switch (i) {
2043    [[likely]] case 0:    // This value and code path is likely
2044      ...
2045      [[fallthrough]];
2046
2047    case 1:               // No likelihood attribute, code path is neutral
2048      break;              // falling through has no effect on the likelihood
2049
2050    case 2:               // No likelihood attribute, code path is neutral
2051      [[fallthrough]];
2052
2053    [[unlikely]] default: // This value and code path are both unlikely
2054      break;
2055  }
2056
2057  for(int i = 0; i != size; ++i) [[likely]] {
2058    ...               // The loop is the likely path of execution
2059  }
2060
2061  for(const auto &E : Elements) [[likely]] {
2062    ...               // The loop is the likely path of execution
2063  }
2064
2065  while(i != size) [[unlikely]] {
2066    ...               // The loop is the unlikely path of execution
2067  }                   // The generated code will optimize to skip the loop body
2068
2069  while(true) [[unlikely]] {
2070    ...               // The attribute has no effect
2071  }                   // Clang elides the comparison and generates an infinite
2072                      // loop
2073
2074  }];
2075}
2076
2077def ARMInterruptDocs : Documentation {
2078  let Category = DocCatFunction;
2079  let Heading = "interrupt (ARM)";
2080  let Content = [{
2081Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on
2082ARM targets. This attribute may be attached to a function definition and
2083instructs the backend to generate appropriate function entry/exit code so that
2084it can be used directly as an interrupt service routine.
2085
2086The parameter passed to the interrupt attribute is optional, but if
2087provided it must be a string literal with one of the following values: "IRQ",
2088"FIQ", "SWI", "ABORT", "UNDEF".
2089
2090The semantics are as follows:
2091
2092- If the function is AAPCS, Clang instructs the backend to realign the stack to
2093  8 bytes on entry. This is a general requirement of the AAPCS at public
2094  interfaces, but may not hold when an exception is taken. Doing this allows
2095  other AAPCS functions to be called.
2096- If the CPU is M-class this is all that needs to be done since the architecture
2097  itself is designed in such a way that functions obeying the normal AAPCS ABI
2098  constraints are valid exception handlers.
2099- If the CPU is not M-class, the prologue and epilogue are modified to save all
2100  non-banked registers that are used, so that upon return the user-mode state
2101  will not be corrupted. Note that to avoid unnecessary overhead, only
2102  general-purpose (integer) registers are saved in this way. If VFP operations
2103  are needed, that state must be saved manually.
2104
2105  Specifically, interrupt kinds other than "FIQ" will save all core registers
2106  except "lr" and "sp". "FIQ" interrupts will save r0-r7.
2107- If the CPU is not M-class, the return instruction is changed to one of the
2108  canonical sequences permitted by the architecture for exception return. Where
2109  possible the function itself will make the necessary "lr" adjustments so that
2110  the "preferred return address" is selected.
2111
2112  Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
2113  handler, where the offset from "lr" to the preferred return address depends on
2114  the execution state of the code which generated the exception. In this case
2115  a sequence equivalent to "movs pc, lr" will be used.
2116  }];
2117}
2118
2119def BPFPreserveAccessIndexDocs : Documentation {
2120  let Category = DocCatFunction;
2121  let Content = [{
2122Clang supports the ``__attribute__((preserve_access_index))``
2123attribute for the BPF target. This attribute may be attached to a
2124struct or union declaration, where if -g is specified, it enables
2125preserving struct or union member access debuginfo indices of this
2126struct or union, similar to clang ``__builtin_preserve_access_index()``.
2127  }];
2128}
2129def BTFDeclTagDocs : Documentation {
2130  let Category = DocCatFunction;
2131  let Content = [{
2132Clang supports the ``__attribute__((btf_decl_tag("ARGUMENT")))`` attribute for
2133all targets. This attribute may be attached to a struct/union, struct/union
2134field, function, function parameter, variable or typedef declaration. If -g is
2135specified, the ``ARGUMENT`` info will be preserved in IR and be emitted to
2136dwarf. For BPF targets, the ``ARGUMENT`` info will be emitted to .BTF ELF
2137section too.
2138  }];
2139}
2140
2141def BTFTypeTagDocs : Documentation {
2142  let Category = DocCatType;
2143  let Content = [{
2144Clang supports the ``__attribute__((btf_type_tag("ARGUMENT")))`` attribute for
2145all targets. It only has effect when ``-g`` is specified on the command line and
2146is currently silently ignored when not applied to a pointer type (note: this
2147scenario may be diagnosed in the future).
2148
2149The ``ARGUMENT`` string will be preserved in IR and emitted to DWARF for the
2150types used in variable declarations, function declarations, or typedef
2151declarations.
2152
2153For BPF targets, the ``ARGUMENT`` string will also be emitted to .BTF ELF
2154section.
2155  }];
2156}
2157
2158def MipsInterruptDocs : Documentation {
2159  let Category = DocCatFunction;
2160  let Heading = "interrupt (MIPS)";
2161  let Content = [{
2162Clang supports the GNU style ``__attribute__((interrupt("ARGUMENT")))`` attribute on
2163MIPS targets. This attribute may be attached to a function definition and instructs
2164the backend to generate appropriate function entry/exit code so that it can be used
2165directly as an interrupt service routine.
2166
2167By default, the compiler will produce a function prologue and epilogue suitable for
2168an interrupt service routine that handles an External Interrupt Controller (eic)
2169generated interrupt. This behavior can be explicitly requested with the "eic"
2170argument.
2171
2172Otherwise, for use with vectored interrupt mode, the argument passed should be
2173of the form "vector=LEVEL" where LEVEL is one of the following values:
2174"sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will
2175then set the interrupt mask to the corresponding level which will mask all
2176interrupts up to and including the argument.
2177
2178The semantics are as follows:
2179
2180- The prologue is modified so that the Exception Program Counter (EPC) and
2181  Status coprocessor registers are saved to the stack. The interrupt mask is
2182  set so that the function can only be interrupted by a higher priority
2183  interrupt. The epilogue will restore the previous values of EPC and Status.
2184
2185- The prologue and epilogue are modified to save and restore all non-kernel
2186  registers as necessary.
2187
2188- The FPU is disabled in the prologue, as the floating pointer registers are not
2189  spilled to the stack.
2190
2191- The function return sequence is changed to use an exception return instruction.
2192
2193- The parameter sets the interrupt mask for the function corresponding to the
2194  interrupt level specified. If no mask is specified the interrupt mask
2195  defaults to "eic".
2196  }];
2197}
2198
2199def MicroMipsDocs : Documentation {
2200  let Category = DocCatFunction;
2201  let Content = [{
2202Clang supports the GNU style ``__attribute__((micromips))`` and
2203``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes
2204may be attached to a function definition and instructs the backend to generate
2205or not to generate microMIPS code for that function.
2206
2207These attributes override the ``-mmicromips`` and ``-mno-micromips`` options
2208on the command line.
2209  }];
2210}
2211
2212def MipsLongCallStyleDocs : Documentation {
2213  let Category = DocCatFunction;
2214  let Heading = "long_call, far";
2215  let Content = [{
2216Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
2217and ``__attribute__((near))`` attributes on MIPS targets. These attributes may
2218only be added to function declarations and change the code generated
2219by the compiler when directly calling the function. The ``near`` attribute
2220allows calls to the function to be made using the ``jal`` instruction, which
2221requires the function to be located in the same naturally aligned 256MB
2222segment as the caller. The ``long_call`` and ``far`` attributes are synonyms
2223and require the use of a different call sequence that works regardless
2224of the distance between the functions.
2225
2226These attributes have no effect for position-independent code.
2227
2228These attributes take priority over command line switches such
2229as ``-mlong-calls`` and ``-mno-long-calls``.
2230  }];
2231}
2232
2233def MipsShortCallStyleDocs : Documentation {
2234  let Category = DocCatFunction;
2235  let Heading = "short_call, near";
2236  let Content = [{
2237Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
2238``__attribute__((short__call))``, and ``__attribute__((near))`` attributes
2239on MIPS targets. These attributes may only be added to function declarations
2240and change the code generated by the compiler when directly calling
2241the function. The ``short_call`` and ``near`` attributes are synonyms and
2242allow calls to the function to be made using the ``jal`` instruction, which
2243requires the function to be located in the same naturally aligned 256MB segment
2244as the caller. The ``long_call`` and ``far`` attributes are synonyms and
2245require the use of a different call sequence that works regardless
2246of the distance between the functions.
2247
2248These attributes have no effect for position-independent code.
2249
2250These attributes take priority over command line switches such
2251as ``-mlong-calls`` and ``-mno-long-calls``.
2252  }];
2253}
2254
2255def RISCVInterruptDocs : Documentation {
2256  let Category = DocCatFunction;
2257  let Heading = "interrupt (RISCV)";
2258  let Content = [{
2259Clang supports the GNU style ``__attribute__((interrupt))`` attribute on RISCV
2260targets. This attribute may be attached to a function definition and instructs
2261the backend to generate appropriate function entry/exit code so that it can be
2262used directly as an interrupt service routine.
2263
2264Permissible values for this parameter are ``user``, ``supervisor``,
2265and ``machine``. If there is no parameter, then it defaults to machine.
2266
2267Repeated interrupt attribute on the same declaration will cause a warning
2268to be emitted. In case of repeated declarations, the last one prevails.
2269
2270Refer to:
2271https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html
2272https://riscv.org/specifications/privileged-isa/
2273The RISC-V Instruction Set Manual Volume II: Privileged Architecture
2274Version 1.10.
2275  }];
2276}
2277
2278def AVRInterruptDocs : Documentation {
2279  let Category = DocCatFunction;
2280  let Heading = "interrupt (AVR)";
2281  let Content = [{
2282Clang supports the GNU style ``__attribute__((interrupt))`` attribute on
2283AVR targets. This attribute may be attached to a function definition and instructs
2284the backend to generate appropriate function entry/exit code so that it can be used
2285directly as an interrupt service routine.
2286
2287On the AVR, the hardware globally disables interrupts when an interrupt is executed.
2288The first instruction of an interrupt handler declared with this attribute is a SEI
2289instruction to re-enable interrupts. See also the signal attribute that
2290does not insert a SEI instruction.
2291  }];
2292}
2293
2294def AVRSignalDocs : Documentation {
2295  let Category = DocCatFunction;
2296  let Content = [{
2297Clang supports the GNU style ``__attribute__((signal))`` attribute on
2298AVR targets. This attribute may be attached to a function definition and instructs
2299the backend to generate appropriate function entry/exit code so that it can be used
2300directly as an interrupt service routine.
2301
2302Interrupt handler functions defined with the signal attribute do not re-enable interrupts.
2303}];
2304}
2305
2306def TargetDocs : Documentation {
2307  let Category = DocCatFunction;
2308  let Content = [{
2309Clang supports the GNU style ``__attribute__((target("OPTIONS")))`` attribute.
2310This attribute may be attached to a function definition and instructs
2311the backend to use different code generation options than were passed on the
2312command line.
2313
2314The current set of options correspond to the existing "subtarget features" for
2315the target with or without a "-mno-" in front corresponding to the absence
2316of the feature, as well as ``arch="CPU"`` which will change the default "CPU"
2317for the function.
2318
2319For X86, the attribute also allows ``tune="CPU"`` to optimize the generated
2320code for the given CPU without changing the available instructions.
2321
2322For AArch64, the attribute also allows the "branch-protection=<args>" option,
2323where the permissible arguments and their effect on code generation are the same
2324as for the command-line option ``-mbranch-protection``.
2325
2326Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
2327"avx", "xop" and largely correspond to the machine specific options handled by
2328the front end.
2329
2330Additionally, this attribute supports function multiversioning for ELF based
2331x86/x86-64 targets, which can be used to create multiple implementations of the
2332same function that will be resolved at runtime based on the priority of their
2333``target`` attribute strings. A function is considered a multiversioned function
2334if either two declarations of the function have different ``target`` attribute
2335strings, or if it has a ``target`` attribute string of ``default``. For
2336example:
2337
2338  .. code-block:: c++
2339
2340    __attribute__((target("arch=atom")))
2341    void foo() {} // will be called on 'atom' processors.
2342    __attribute__((target("default")))
2343    void foo() {} // will be called on any other processors.
2344
2345All multiversioned functions must contain a ``default`` (fallback)
2346implementation, otherwise usages of the function are considered invalid.
2347Additionally, a function may not become multiversioned after its first use.
2348}];
2349}
2350
2351def TargetClonesDocs : Documentation {
2352  let Category = DocCatFunction;
2353  let Content = [{
2354Clang supports the ``target_clones("OPTIONS")`` attribute. This attribute may be
2355attached to a function declaration and causes function multiversioning, where
2356multiple versions of the function will be emitted with different code
2357generation options.  Additionally, these versions will be resolved at runtime
2358based on the priority of their attribute options. All ``target_clone`` functions
2359are considered multiversioned functions.
2360
2361All multiversioned functions must contain a ``default`` (fallback)
2362implementation, otherwise usages of the function are considered invalid.
2363Additionally, a function may not become multiversioned after its first use.
2364
2365The options to ``target_clones`` can either be a target-specific architecture
2366(specified as ``arch=CPU``), or one of a list of subtarget features.
2367
2368Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
2369"avx", "xop" and largely correspond to the machine specific options handled by
2370the front end.
2371
2372The versions can either be listed as a comma-separated sequence of string
2373literals or as a single string literal containing a comma-separated list of
2374versions.  For compatibility with GCC, the two formats can be mixed.  For
2375example, the following will emit 4 versions of the function:
2376
2377  .. code-block:: c++
2378
2379    __attribute__((target_clones("arch=atom,avx2","arch=ivybridge","default")))
2380    void foo() {}
2381
2382}];
2383}
2384
2385def MinVectorWidthDocs : Documentation {
2386  let Category = DocCatFunction;
2387  let Content = [{
2388Clang supports the ``__attribute__((min_vector_width(width)))`` attribute. This
2389attribute may be attached to a function and informs the backend that this
2390function desires vectors of at least this width to be generated. Target-specific
2391maximum vector widths still apply. This means even if you ask for something
2392larger than the target supports, you will only get what the target supports.
2393This attribute is meant to be a hint to control target heuristics that may
2394generate narrower vectors than what the target hardware supports.
2395
2396This is currently used by the X86 target to allow some CPUs that support 512-bit
2397vectors to be limited to using 256-bit vectors to avoid frequency penalties.
2398This is currently enabled with the ``-prefer-vector-width=256`` command line
2399option. The ``min_vector_width`` attribute can be used to prevent the backend
2400from trying to split vector operations to match the ``prefer-vector-width``. All
2401X86 vector intrinsics from x86intrin.h already set this attribute. Additionally,
2402use of any of the X86-specific vector builtins will implicitly set this
2403attribute on the calling function. The intent is that explicitly writing vector
2404code using the X86 intrinsics will prevent ``prefer-vector-width`` from
2405affecting the code.
2406}];
2407}
2408
2409def DocCatAMDGPUAttributes : DocumentationCategory<"AMD GPU Attributes">;
2410
2411def AMDGPUFlatWorkGroupSizeDocs : Documentation {
2412  let Category = DocCatAMDGPUAttributes;
2413  let Content = [{
2414The flat work-group size is the number of work-items in the work-group size
2415specified when the kernel is dispatched. It is the product of the sizes of the
2416x, y, and z dimension of the work-group.
2417
2418Clang supports the
2419``__attribute__((amdgpu_flat_work_group_size(<min>, <max>)))`` attribute for the
2420AMDGPU target. This attribute may be attached to a kernel function definition
2421and is an optimization hint.
2422
2423``<min>`` parameter specifies the minimum flat work-group size, and ``<max>``
2424parameter specifies the maximum flat work-group size (must be greater than
2425``<min>``) to which all dispatches of the kernel will conform. Passing ``0, 0``
2426as ``<min>, <max>`` implies the default behavior (``128, 256``).
2427
2428If specified, the AMDGPU target backend might be able to produce better machine
2429code for barriers and perform scratch promotion by estimating available group
2430segment size.
2431
2432An error will be given if:
2433  - Specified values violate subtarget specifications;
2434  - Specified values are not compatible with values provided through other
2435    attributes.
2436  }];
2437}
2438
2439def AMDGPUWavesPerEUDocs : Documentation {
2440  let Category = DocCatAMDGPUAttributes;
2441  let Content = [{
2442A compute unit (CU) is responsible for executing the wavefronts of a work-group.
2443It is composed of one or more execution units (EU), which are responsible for
2444executing the wavefronts. An EU can have enough resources to maintain the state
2445of more than one executing wavefront. This allows an EU to hide latency by
2446switching between wavefronts in a similar way to symmetric multithreading on a
2447CPU. In order to allow the state for multiple wavefronts to fit on an EU, the
2448resources used by a single wavefront have to be limited. For example, the number
2449of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding,
2450but can result in having to spill some register state to memory.
2451
2452Clang supports the ``__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))``
2453attribute for the AMDGPU target. This attribute may be attached to a kernel
2454function definition and is an optimization hint.
2455
2456``<min>`` parameter specifies the requested minimum number of waves per EU, and
2457*optional* ``<max>`` parameter specifies the requested maximum number of waves
2458per EU (must be greater than ``<min>`` if specified). If ``<max>`` is omitted,
2459then there is no restriction on the maximum number of waves per EU other than
2460the one dictated by the hardware for which the kernel is compiled. Passing
2461``0, 0`` as ``<min>, <max>`` implies the default behavior (no limits).
2462
2463If specified, this attribute allows an advanced developer to tune the number of
2464wavefronts that are capable of fitting within the resources of an EU. The AMDGPU
2465target backend can use this information to limit resources, such as number of
2466SGPRs, number of VGPRs, size of available group and private memory segments, in
2467such a way that guarantees that at least ``<min>`` wavefronts and at most
2468``<max>`` wavefronts are able to fit within the resources of an EU. Requesting
2469more wavefronts can hide memory latency but limits available registers which
2470can result in spilling. Requesting fewer wavefronts can help reduce cache
2471thrashing, but can reduce memory latency hiding.
2472
2473This attribute controls the machine code generated by the AMDGPU target backend
2474to ensure it is capable of meeting the requested values. However, when the
2475kernel is executed, there may be other reasons that prevent meeting the request,
2476for example, there may be wavefronts from other kernels executing on the EU.
2477
2478An error will be given if:
2479  - Specified values violate subtarget specifications;
2480  - Specified values are not compatible with values provided through other
2481    attributes;
2482  - The AMDGPU target backend is unable to create machine code that can meet the
2483    request.
2484  }];
2485}
2486
2487def AMDGPUNumSGPRNumVGPRDocs : Documentation {
2488  let Category = DocCatAMDGPUAttributes;
2489  let Content = [{
2490Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and
2491``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU
2492target. These attributes may be attached to a kernel function definition and are
2493an optimization hint.
2494
2495If these attributes are specified, then the AMDGPU target backend will attempt
2496to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
2497number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
2498allocation requirements or constraints of the subtarget. Passing ``0`` as
2499``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits).
2500
2501These attributes can be used to test the AMDGPU target backend. It is
2502recommended that the ``amdgpu_waves_per_eu`` attribute be used to control
2503resources such as SGPRs and VGPRs since it is aware of the limits for different
2504subtargets.
2505
2506An error will be given if:
2507  - Specified values violate subtarget specifications;
2508  - Specified values are not compatible with values provided through other
2509    attributes;
2510  - The AMDGPU target backend is unable to create machine code that can meet the
2511    request.
2512  }];
2513}
2514
2515def DocCatCallingConvs : DocumentationCategory<"Calling Conventions"> {
2516  let Content = [{
2517Clang supports several different calling conventions, depending on the target
2518platform and architecture. The calling convention used for a function determines
2519how parameters are passed, how results are returned to the caller, and other
2520low-level details of calling a function.
2521  }];
2522}
2523
2524def PcsDocs : Documentation {
2525  let Category = DocCatCallingConvs;
2526  let Content = [{
2527On ARM targets, this attribute can be used to select calling conventions
2528similar to ``stdcall`` on x86. Valid parameter values are "aapcs" and
2529"aapcs-vfp".
2530  }];
2531}
2532
2533def AArch64VectorPcsDocs : Documentation {
2534  let Category = DocCatCallingConvs;
2535  let Content = [{
2536On AArch64 targets, this attribute changes the calling convention of a
2537function to preserve additional floating-point and Advanced SIMD registers
2538relative to the default calling convention used for AArch64.
2539
2540This means it is more efficient to call such functions from code that performs
2541extensive floating-point and vector calculations, because fewer live SIMD and FP
2542registers need to be saved. This property makes it well-suited for e.g.
2543floating-point or vector math library functions, which are typically leaf
2544functions that require a small number of registers.
2545
2546However, using this attribute also means that it is more expensive to call
2547a function that adheres to the default calling convention from within such
2548a function. Therefore, it is recommended that this attribute is only used
2549for leaf functions.
2550
2551For more information, see the documentation for `aarch64_vector_pcs`_ on
2552the Arm Developer website.
2553
2554.. _`aarch64_vector_pcs`: https://developer.arm.com/products/software-development-tools/hpc/arm-compiler-for-hpc/vector-function-abi
2555  }];
2556}
2557
2558def AArch64SVEPcsDocs : Documentation {
2559  let Category = DocCatCallingConvs;
2560  let Content = [{
2561On AArch64 targets, this attribute changes the calling convention of a
2562function to preserve additional Scalable Vector registers and Scalable
2563Predicate registers relative to the default calling convention used for
2564AArch64.
2565
2566This means it is more efficient to call such functions from code that performs
2567extensive scalable vector and scalable predicate calculations, because fewer
2568live SVE registers need to be saved. This property makes it well-suited for SVE
2569math library functions, which are typically leaf functions that require a small
2570number of registers.
2571
2572However, using this attribute also means that it is more expensive to call
2573a function that adheres to the default calling convention from within such
2574a function. Therefore, it is recommended that this attribute is only used
2575for leaf functions.
2576
2577For more information, see the documentation for `aarch64_sve_pcs` in the
2578ARM C Language Extension (ACLE) documentation.
2579
2580.. _`aarch64_sve_pcs`: https://github.com/ARM-software/acle/blob/main/main/acle.md#scalable-vector-extension-procedure-call-standard-attribute
2581  }];
2582}
2583
2584def RegparmDocs : Documentation {
2585  let Category = DocCatCallingConvs;
2586  let Content = [{
2587On 32-bit x86 targets, the regparm attribute causes the compiler to pass
2588the first three integer parameters in EAX, EDX, and ECX instead of on the
2589stack. This attribute has no effect on variadic functions, and all parameters
2590are passed via the stack as normal.
2591  }];
2592}
2593
2594def SysVABIDocs : Documentation {
2595  let Category = DocCatCallingConvs;
2596  let Content = [{
2597On Windows x86_64 targets, this attribute changes the calling convention of a
2598function to match the default convention used on Sys V targets such as Linux,
2599Mac, and BSD. This attribute has no effect on other targets.
2600  }];
2601}
2602
2603def MSABIDocs : Documentation {
2604  let Category = DocCatCallingConvs;
2605  let Content = [{
2606On non-Windows x86_64 targets, this attribute changes the calling convention of
2607a function to match the default convention used on Windows x86_64. This
2608attribute has no effect on Windows targets or non-x86_64 targets.
2609  }];
2610}
2611
2612def StdCallDocs : Documentation {
2613  let Category = DocCatCallingConvs;
2614  let Content = [{
2615On 32-bit x86 targets, this attribute changes the calling convention of a
2616function to clear parameters off of the stack on return. This convention does
2617not support variadic calls or unprototyped functions in C, and has no effect on
2618x86_64 targets. This calling convention is used widely by the Windows API and
2619COM applications. See the documentation for `__stdcall`_ on MSDN.
2620
2621.. _`__stdcall`: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx
2622  }];
2623}
2624
2625def FastCallDocs : Documentation {
2626  let Category = DocCatCallingConvs;
2627  let Content = [{
2628On 32-bit x86 targets, this attribute changes the calling convention of a
2629function to use ECX and EDX as register parameters and clear parameters off of
2630the stack on return. This convention does not support variadic calls or
2631unprototyped functions in C, and has no effect on x86_64 targets. This calling
2632convention is supported primarily for compatibility with existing code. Users
2633seeking register parameters should use the ``regparm`` attribute, which does
2634not require callee-cleanup. See the documentation for `__fastcall`_ on MSDN.
2635
2636.. _`__fastcall`: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx
2637  }];
2638}
2639
2640def RegCallDocs : Documentation {
2641  let Category = DocCatCallingConvs;
2642  let Content = [{
2643On x86 targets, this attribute changes the calling convention to
2644`__regcall`_ convention. This convention aims to pass as many arguments
2645as possible in registers. It also tries to utilize registers for the
2646return value whenever it is possible.
2647
2648.. _`__regcall`: https://software.intel.com/en-us/node/693069
2649  }];
2650}
2651
2652def ThisCallDocs : Documentation {
2653  let Category = DocCatCallingConvs;
2654  let Content = [{
2655On 32-bit x86 targets, this attribute changes the calling convention of a
2656function to use ECX for the first parameter (typically the implicit ``this``
2657parameter of C++ methods) and clear parameters off of the stack on return. This
2658convention does not support variadic calls or unprototyped functions in C, and
2659has no effect on x86_64 targets. See the documentation for `__thiscall`_ on
2660MSDN.
2661
2662.. _`__thiscall`: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx
2663  }];
2664}
2665
2666def VectorCallDocs : Documentation {
2667  let Category = DocCatCallingConvs;
2668  let Content = [{
2669On 32-bit x86 *and* x86_64 targets, this attribute changes the calling
2670convention of a function to pass vector parameters in SSE registers.
2671
2672On 32-bit x86 targets, this calling convention is similar to ``__fastcall``.
2673The first two integer parameters are passed in ECX and EDX. Subsequent integer
2674parameters are passed in memory, and callee clears the stack. On x86_64
2675targets, the callee does *not* clear the stack, and integer parameters are
2676passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling
2677convention.
2678
2679On both 32-bit x86 and x86_64 targets, vector and floating point arguments are
2680passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are
2681passed in sequential SSE registers if enough are available. If AVX is enabled,
2682256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that
2683cannot be passed in registers for any reason is passed by reference, which
2684allows the caller to align the parameter memory.
2685
2686See the documentation for `__vectorcall`_ on MSDN for more details.
2687
2688.. _`__vectorcall`: http://msdn.microsoft.com/en-us/library/dn375768.aspx
2689  }];
2690}
2691
2692def DocCatConsumed : DocumentationCategory<"Consumed Annotation Checking"> {
2693  let Content = [{
2694Clang supports additional attributes for checking basic resource management
2695properties, specifically for unique objects that have a single owning reference.
2696The following attributes are currently supported, although **the implementation
2697for these annotations is currently in development and are subject to change.**
2698  }];
2699}
2700
2701def SetTypestateDocs : Documentation {
2702  let Category = DocCatConsumed;
2703  let Content = [{
2704Annotate methods that transition an object into a new state with
2705``__attribute__((set_typestate(new_state)))``. The new state must be
2706unconsumed, consumed, or unknown.
2707  }];
2708}
2709
2710def CallableWhenDocs : Documentation {
2711  let Category = DocCatConsumed;
2712  let Content = [{
2713Use ``__attribute__((callable_when(...)))`` to indicate what states a method
2714may be called in. Valid states are unconsumed, consumed, or unknown. Each
2715argument to this attribute must be a quoted string. E.g.:
2716
2717``__attribute__((callable_when("unconsumed", "unknown")))``
2718  }];
2719}
2720
2721def TestTypestateDocs : Documentation {
2722  let Category = DocCatConsumed;
2723  let Content = [{
2724Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method
2725returns true if the object is in the specified state..
2726  }];
2727}
2728
2729def ParamTypestateDocs : Documentation {
2730  let Category = DocCatConsumed;
2731  let Content = [{
2732This attribute specifies expectations about function parameters. Calls to an
2733function with annotated parameters will issue a warning if the corresponding
2734argument isn't in the expected state. The attribute is also used to set the
2735initial state of the parameter when analyzing the function's body.
2736  }];
2737}
2738
2739def ReturnTypestateDocs : Documentation {
2740  let Category = DocCatConsumed;
2741  let Content = [{
2742The ``return_typestate`` attribute can be applied to functions or parameters.
2743When applied to a function the attribute specifies the state of the returned
2744value. The function's body is checked to ensure that it always returns a value
2745in the specified state. On the caller side, values returned by the annotated
2746function are initialized to the given state.
2747
2748When applied to a function parameter it modifies the state of an argument after
2749a call to the function returns. The function's body is checked to ensure that
2750the parameter is in the expected state before returning.
2751  }];
2752}
2753
2754def ConsumableDocs : Documentation {
2755  let Category = DocCatConsumed;
2756  let Content = [{
2757Each ``class`` that uses any of the typestate annotations must first be marked
2758using the ``consumable`` attribute. Failure to do so will result in a warning.
2759
2760This attribute accepts a single parameter that must be one of the following:
2761``unknown``, ``consumed``, or ``unconsumed``.
2762  }];
2763}
2764
2765def NoProfileInstrumentFunctionDocs : Documentation {
2766  let Category = DocCatFunction;
2767  let Content = [{
2768Use the ``no_profile_instrument_function`` attribute on a function declaration
2769to denote that the compiler should not instrument the function with
2770profile-related instrumentation, such as via the
2771``-fprofile-generate`` / ``-fprofile-instr-generate`` /
2772``-fcs-profile-generate`` / ``-fprofile-arcs`` flags.
2773}];
2774}
2775
2776def NoSanitizeDocs : Documentation {
2777  let Category = DocCatFunction;
2778  let Content = [{
2779Use the ``no_sanitize`` attribute on a function or a global variable
2780declaration to specify that a particular instrumentation or set of
2781instrumentations should not be applied.
2782
2783The attribute takes a list of string literals with the following accepted
2784values:
2785* all values accepted by ``-fno-sanitize=``;
2786* ``coverage``, to disable SanitizerCoverage instrumentation.
2787
2788For example, ``__attribute__((no_sanitize("address", "thread")))`` specifies
2789that AddressSanitizer and ThreadSanitizer should not be applied to the function
2790or variable. Using ``__attribute__((no_sanitize("coverage")))`` specifies that
2791SanitizerCoverage should not be applied to the function.
2792
2793See :ref:`Controlling Code Generation <controlling-code-generation>` for a
2794full list of supported sanitizer flags.
2795  }];
2796}
2797
2798def DisableSanitizerInstrumentationDocs : Documentation {
2799  let Category = DocCatFunction;
2800  let Content = [{
2801Use the ``disable_sanitizer_instrumentation`` attribute on a function,
2802Objective-C method, or global variable, to specify that no sanitizer
2803instrumentation should be applied.
2804
2805This is not the same as ``__attribute__((no_sanitize(...)))``, which depending
2806on the tool may still insert instrumentation to prevent false positive reports.
2807  }];
2808}
2809
2810def NoSanitizeAddressDocs : Documentation {
2811  let Category = DocCatFunction;
2812  // This function has multiple distinct spellings, and so it requires a custom
2813  // heading to be specified. The most common spelling is sufficient.
2814  let Heading = "no_sanitize_address, no_address_safety_analysis";
2815  let Content = [{
2816.. _langext-address_sanitizer:
2817
2818Use ``__attribute__((no_sanitize_address))`` on a function or a global
2819variable declaration to specify that address safety instrumentation
2820(e.g. AddressSanitizer) should not be applied.
2821  }];
2822}
2823
2824def NoSanitizeThreadDocs : Documentation {
2825  let Category = DocCatFunction;
2826  let Heading = "no_sanitize_thread";
2827  let Content = [{
2828.. _langext-thread_sanitizer:
2829
2830Use ``__attribute__((no_sanitize_thread))`` on a function declaration to
2831specify that checks for data races on plain (non-atomic) memory accesses should
2832not be inserted by ThreadSanitizer. The function is still instrumented by the
2833tool to avoid false positives and provide meaningful stack traces.
2834  }];
2835}
2836
2837def NoSanitizeMemoryDocs : Documentation {
2838  let Category = DocCatFunction;
2839  let Heading = "no_sanitize_memory";
2840  let Content = [{
2841.. _langext-memory_sanitizer:
2842
2843Use ``__attribute__((no_sanitize_memory))`` on a function declaration to
2844specify that checks for uninitialized memory should not be inserted
2845(e.g. by MemorySanitizer). The function may still be instrumented by the tool
2846to avoid false positives in other places.
2847  }];
2848}
2849
2850def CFICanonicalJumpTableDocs : Documentation {
2851  let Category = DocCatFunction;
2852  let Heading = "cfi_canonical_jump_table";
2853  let Content = [{
2854.. _langext-cfi_canonical_jump_table:
2855
2856Use ``__attribute__((cfi_canonical_jump_table))`` on a function declaration to
2857make the function's CFI jump table canonical. See :ref:`the CFI documentation
2858<cfi-canonical-jump-tables>` for more details.
2859  }];
2860}
2861
2862def DocCatTypeSafety : DocumentationCategory<"Type Safety Checking"> {
2863  let Content = [{
2864Clang supports additional attributes to enable checking type safety properties
2865that can't be enforced by the C type system. To see warnings produced by these
2866checks, ensure that -Wtype-safety is enabled. Use cases include:
2867
2868* MPI library implementations, where these attributes enable checking that
2869  the buffer type matches the passed ``MPI_Datatype``;
2870* for HDF5 library there is a similar use case to MPI;
2871* checking types of variadic functions' arguments for functions like
2872  ``fcntl()`` and ``ioctl()``.
2873
2874You can detect support for these attributes with ``__has_attribute()``. For
2875example:
2876
2877.. code-block:: c++
2878
2879  #if defined(__has_attribute)
2880  #  if __has_attribute(argument_with_type_tag) && \
2881        __has_attribute(pointer_with_type_tag) && \
2882        __has_attribute(type_tag_for_datatype)
2883  #    define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx)))
2884  /* ... other macros ... */
2885  #  endif
2886  #endif
2887
2888  #if !defined(ATTR_MPI_PWT)
2889  # define ATTR_MPI_PWT(buffer_idx, type_idx)
2890  #endif
2891
2892  int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
2893      ATTR_MPI_PWT(1,3);
2894  }];
2895}
2896
2897def ArgumentWithTypeTagDocs : Documentation {
2898  let Category = DocCatTypeSafety;
2899  let Heading = "argument_with_type_tag";
2900  let Content = [{
2901Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
2902type_tag_idx)))`` on a function declaration to specify that the function
2903accepts a type tag that determines the type of some other argument.
2904
2905This attribute is primarily useful for checking arguments of variadic functions
2906(``pointer_with_type_tag`` can be used in most non-variadic cases).
2907
2908In the attribute prototype above:
2909  * ``arg_kind`` is an identifier that should be used when annotating all
2910    applicable type tags.
2911  * ``arg_idx`` provides the position of a function argument. The expected type of
2912    this function argument will be determined by the function argument specified
2913    by ``type_tag_idx``. In the code example below, "3" means that the type of the
2914    function's third argument will be determined by ``type_tag_idx``.
2915  * ``type_tag_idx`` provides the position of a function argument. This function
2916    argument will be a type tag. The type tag will determine the expected type of
2917    the argument specified by ``arg_idx``. In the code example below, "2" means
2918    that the type tag associated with the function's second argument should agree
2919    with the type of the argument specified by ``arg_idx``.
2920
2921For example:
2922
2923.. code-block:: c++
2924
2925  int fcntl(int fd, int cmd, ...)
2926      __attribute__(( argument_with_type_tag(fcntl,3,2) ));
2927  // The function's second argument will be a type tag; this type tag will
2928  // determine the expected type of the function's third argument.
2929  }];
2930}
2931
2932def PointerWithTypeTagDocs : Documentation {
2933  let Category = DocCatTypeSafety;
2934  let Heading = "pointer_with_type_tag";
2935  let Content = [{
2936Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))``
2937on a function declaration to specify that the function accepts a type tag that
2938determines the pointee type of some other pointer argument.
2939
2940In the attribute prototype above:
2941  * ``ptr_kind`` is an identifier that should be used when annotating all
2942    applicable type tags.
2943  * ``ptr_idx`` provides the position of a function argument; this function
2944    argument will have a pointer type. The expected pointee type of this pointer
2945    type will be determined by the function argument specified by
2946    ``type_tag_idx``. In the code example below, "1" means that the pointee type
2947    of the function's first argument will be determined by ``type_tag_idx``.
2948  * ``type_tag_idx`` provides the position of a function argument; this function
2949    argument will be a type tag. The type tag will determine the expected pointee
2950    type of the pointer argument specified by ``ptr_idx``. In the code example
2951    below, "3" means that the type tag associated with the function's third
2952    argument should agree with the pointee type of the pointer argument specified
2953    by ``ptr_idx``.
2954
2955For example:
2956
2957.. code-block:: c++
2958
2959  typedef int MPI_Datatype;
2960  int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
2961      __attribute__(( pointer_with_type_tag(mpi,1,3) ));
2962  // The function's 3rd argument will be a type tag; this type tag will
2963  // determine the expected pointee type of the function's 1st argument.
2964  }];
2965}
2966
2967def TypeTagForDatatypeDocs : Documentation {
2968  let Category = DocCatTypeSafety;
2969  let Content = [{
2970When declaring a variable, use
2971``__attribute__((type_tag_for_datatype(kind, type)))`` to create a type tag that
2972is tied to the ``type`` argument given to the attribute.
2973
2974In the attribute prototype above:
2975  * ``kind`` is an identifier that should be used when annotating all applicable
2976    type tags.
2977  * ``type`` indicates the name of the type.
2978
2979Clang supports annotating type tags of two forms.
2980
2981  * **Type tag that is a reference to a declared identifier.**
2982    Use ``__attribute__((type_tag_for_datatype(kind, type)))`` when declaring that
2983    identifier:
2984
2985    .. code-block:: c++
2986
2987      typedef int MPI_Datatype;
2988      extern struct mpi_datatype mpi_datatype_int
2989          __attribute__(( type_tag_for_datatype(mpi,int) ));
2990      #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
2991      // &mpi_datatype_int is a type tag. It is tied to type "int".
2992
2993  * **Type tag that is an integral literal.**
2994    Declare a ``static const`` variable with an initializer value and attach
2995    ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration:
2996
2997    .. code-block:: c++
2998
2999      typedef int MPI_Datatype;
3000      static const MPI_Datatype mpi_datatype_int
3001          __attribute__(( type_tag_for_datatype(mpi,int) )) = 42;
3002      #define MPI_INT ((MPI_Datatype) 42)
3003      // The number 42 is a type tag. It is tied to type "int".
3004
3005
3006The ``type_tag_for_datatype`` attribute also accepts an optional third argument
3007that determines how the type of the function argument specified by either
3008``arg_idx`` or ``ptr_idx`` is compared against the type associated with the type
3009tag. (Recall that for the ``argument_with_type_tag`` attribute, the type of the
3010function argument specified by ``arg_idx`` is compared against the type
3011associated with the type tag. Also recall that for the ``pointer_with_type_tag``
3012attribute, the pointee type of the function argument specified by ``ptr_idx`` is
3013compared against the type associated with the type tag.) There are two supported
3014values for this optional third argument:
3015
3016  * ``layout_compatible`` will cause types to be compared according to
3017    layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the
3018    layout-compatibility rules for two standard-layout struct types and for two
3019    standard-layout union types). This is useful when creating a type tag
3020    associated with a struct or union type. For example:
3021
3022    .. code-block:: c++
3023
3024      /* In mpi.h */
3025      typedef int MPI_Datatype;
3026      struct internal_mpi_double_int { double d; int i; };
3027      extern struct mpi_datatype mpi_datatype_double_int
3028          __attribute__(( type_tag_for_datatype(mpi,
3029                          struct internal_mpi_double_int, layout_compatible) ));
3030
3031      #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
3032
3033      int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
3034          __attribute__(( pointer_with_type_tag(mpi,1,3) ));
3035
3036      /* In user code */
3037      struct my_pair { double a; int b; };
3038      struct my_pair *buffer;
3039      MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the
3040                                                       // layout of my_pair is
3041                                                       // compatible with that of
3042                                                       // internal_mpi_double_int
3043
3044      struct my_int_pair { int a; int b; }
3045      struct my_int_pair *buffer2;
3046      MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the
3047                                                        // layout of my_int_pair
3048                                                        // does not match that of
3049                                                        // internal_mpi_double_int
3050
3051  * ``must_be_null`` specifies that the function argument specified by either
3052    ``arg_idx`` (for the ``argument_with_type_tag`` attribute) or ``ptr_idx`` (for
3053    the ``pointer_with_type_tag`` attribute) should be a null pointer constant.
3054    The second argument to the ``type_tag_for_datatype`` attribute is ignored. For
3055    example:
3056
3057    .. code-block:: c++
3058
3059      /* In mpi.h */
3060      typedef int MPI_Datatype;
3061      extern struct mpi_datatype mpi_datatype_null
3062          __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
3063
3064      #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
3065      int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
3066          __attribute__(( pointer_with_type_tag(mpi,1,3) ));
3067
3068      /* In user code */
3069      struct my_pair { double a; int b; };
3070      struct my_pair *buffer;
3071      MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
3072                                                          // was specified but buffer
3073                                                          // is not a null pointer
3074  }];
3075}
3076
3077def FlattenDocs : Documentation {
3078  let Category = DocCatFunction;
3079  let Content = [{
3080The ``flatten`` attribute causes calls within the attributed function to
3081be inlined unless it is impossible to do so, for example if the body of the
3082callee is unavailable or if the callee has the ``noinline`` attribute.
3083  }];
3084}
3085
3086def FormatDocs : Documentation {
3087  let Category = DocCatFunction;
3088  let Content = [{
3089
3090Clang supports the ``format`` attribute, which indicates that the function
3091accepts (among other possibilities) a ``printf`` or ``scanf``-like format string
3092and corresponding arguments or a ``va_list`` that contains these arguments.
3093
3094Please see `GCC documentation about format attribute
3095<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details
3096about attribute syntax.
3097
3098Clang implements two kinds of checks with this attribute.
3099
3100#. Clang checks that the function with the ``format`` attribute is called with
3101   a format string that uses format specifiers that are allowed, and that
3102   arguments match the format string. This is the ``-Wformat`` warning, it is
3103   on by default.
3104
3105#. Clang checks that the format string argument is a literal string. This is
3106   the ``-Wformat-nonliteral`` warning, it is off by default.
3107
3108   Clang implements this mostly the same way as GCC, but there is a difference
3109   for functions that accept a ``va_list`` argument (for example, ``vprintf``).
3110   GCC does not emit ``-Wformat-nonliteral`` warning for calls to such
3111   functions. Clang does not warn if the format string comes from a function
3112   parameter, where the function is annotated with a compatible attribute,
3113   otherwise it warns. For example:
3114
3115   .. code-block:: c
3116
3117     __attribute__((__format__ (__scanf__, 1, 3)))
3118     void foo(const char* s, char *buf, ...) {
3119       va_list ap;
3120       va_start(ap, buf);
3121
3122       vprintf(s, ap); // warning: format string is not a string literal
3123     }
3124
3125   In this case we warn because ``s`` contains a format string for a
3126   ``scanf``-like function, but it is passed to a ``printf``-like function.
3127
3128   If the attribute is removed, clang still warns, because the format string is
3129   not a string literal.
3130
3131   Another example:
3132
3133   .. code-block:: c
3134
3135     __attribute__((__format__ (__printf__, 1, 3)))
3136     void foo(const char* s, char *buf, ...) {
3137       va_list ap;
3138       va_start(ap, buf);
3139
3140       vprintf(s, ap); // warning
3141     }
3142
3143   In this case Clang does not warn because the format string ``s`` and
3144   the corresponding arguments are annotated. If the arguments are
3145   incorrect, the caller of ``foo`` will receive a warning.
3146
3147As an extension to GCC's behavior, Clang accepts the ``format`` attribute on
3148non-variadic functions. Clang checks non-variadic format functions for the same
3149classes of issues that can be found on variadic functions, as controlled by the
3150same warning flags, except that the types of formatted arguments is forced by
3151the function signature. For example:
3152
3153.. code-block:: c
3154
3155  __attribute__((__format__(__printf__, 1, 2)))
3156  void fmt(const char *s, const char *a, int b);
3157
3158  void bar(void) {
3159    fmt("%s %i", "hello", 123); // OK
3160    fmt("%i %g", "hello", 123); // warning: arguments don't match format
3161    extern const char *fmt;
3162    fmt(fmt, "hello", 123); // warning: format string is not a string literal
3163  }
3164
3165Using the ``format`` attribute on a non-variadic function emits a GCC
3166compatibility diagnostic.
3167  }];
3168}
3169
3170def AlignValueDocs : Documentation {
3171  let Category = DocCatType;
3172  let Content = [{
3173The align_value attribute can be added to the typedef of a pointer type or the
3174declaration of a variable of pointer or reference type. It specifies that the
3175pointer will point to, or the reference will bind to, only objects with at
3176least the provided alignment. This alignment value must be some positive power
3177of 2.
3178
3179   .. code-block:: c
3180
3181     typedef double * aligned_double_ptr __attribute__((align_value(64)));
3182     void foo(double & x  __attribute__((align_value(128)),
3183              aligned_double_ptr y) { ... }
3184
3185If the pointer value does not have the specified alignment at runtime, the
3186behavior of the program is undefined.
3187  }];
3188}
3189
3190def FlagEnumDocs : Documentation {
3191  let Category = DocCatDecl;
3192  let Content = [{
3193This attribute can be added to an enumerator to signal to the compiler that it
3194is intended to be used as a flag type. This will cause the compiler to assume
3195that the range of the type includes all of the values that you can get by
3196manipulating bits of the enumerator when issuing warnings.
3197  }];
3198}
3199
3200def AsmLabelDocs : Documentation {
3201  let Category = DocCatDecl;
3202  let Content = [{
3203This attribute can be used on a function or variable to specify its symbol name.
3204
3205On some targets, all C symbols are prefixed by default with a single character,
3206typically ``_``. This was done historically to distinguish them from symbols
3207used by other languages. (This prefix is also added to the standard Itanium
3208C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true
3209symbol name for a C++ variable declared as ``int cppvar;`` would be
3210``__Z6cppvar``; note the two underscores.)  This prefix is *not* added to the
3211symbol names specified by the ``asm`` attribute; programmers wishing to match a
3212C symbol name must compensate for this.
3213
3214For example, consider the following C code:
3215
3216.. code-block:: c
3217
3218  int var1 asm("altvar") = 1;  // "altvar" in symbol table.
3219  int var2 = 1; // "_var2" in symbol table.
3220
3221  void func1(void) asm("altfunc");
3222  void func1(void) {} // "altfunc" in symbol table.
3223  void func2(void) {} // "_func2" in symbol table.
3224
3225Clang's implementation of this attribute is compatible with GCC's, `documented here <https://gcc.gnu.org/onlinedocs/gcc/Asm-Labels.html>`_.
3226
3227While it is possible to use this attribute to name a special symbol used
3228internally by the compiler, such as an LLVM intrinsic, this is neither
3229recommended nor supported and may cause the compiler to crash or miscompile.
3230Users who wish to gain access to intrinsic behavior are strongly encouraged to
3231request new builtin functions.
3232  }];
3233}
3234
3235def EnumExtensibilityDocs : Documentation {
3236  let Category = DocCatDecl;
3237  let Content = [{
3238Attribute ``enum_extensibility`` is used to distinguish between enum definitions
3239that are extensible and those that are not. The attribute can take either
3240``closed`` or ``open`` as an argument. ``closed`` indicates a variable of the
3241enum type takes a value that corresponds to one of the enumerators listed in the
3242enum definition or, when the enum is annotated with ``flag_enum``, a value that
3243can be constructed using values corresponding to the enumerators. ``open``
3244indicates a variable of the enum type can take any values allowed by the
3245standard and instructs clang to be more lenient when issuing warnings.
3246
3247.. code-block:: c
3248
3249  enum __attribute__((enum_extensibility(closed))) ClosedEnum {
3250    A0, A1
3251  };
3252
3253  enum __attribute__((enum_extensibility(open))) OpenEnum {
3254    B0, B1
3255  };
3256
3257  enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum {
3258    C0 = 1 << 0, C1 = 1 << 1
3259  };
3260
3261  enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum {
3262    D0 = 1 << 0, D1 = 1 << 1
3263  };
3264
3265  void foo1() {
3266    enum ClosedEnum ce;
3267    enum OpenEnum oe;
3268    enum ClosedFlagEnum cfe;
3269    enum OpenFlagEnum ofe;
3270
3271    ce = A1;           // no warnings
3272    ce = 100;          // warning issued
3273    oe = B1;           // no warnings
3274    oe = 100;          // no warnings
3275    cfe = C0 | C1;     // no warnings
3276    cfe = C0 | C1 | 4; // warning issued
3277    ofe = D0 | D1;     // no warnings
3278    ofe = D0 | D1 | 4; // no warnings
3279  }
3280
3281  }];
3282}
3283
3284def EmptyBasesDocs : Documentation {
3285  let Category = DocCatDecl;
3286  let Content = [{
3287The empty_bases attribute permits the compiler to utilize the
3288empty-base-optimization more frequently.
3289This attribute only applies to struct, class, and union types.
3290It is only supported when using the Microsoft C++ ABI.
3291  }];
3292}
3293
3294def LayoutVersionDocs : Documentation {
3295  let Category = DocCatDecl;
3296  let Content = [{
3297The layout_version attribute requests that the compiler utilize the class
3298layout rules of a particular compiler version.
3299This attribute only applies to struct, class, and union types.
3300It is only supported when using the Microsoft C++ ABI.
3301  }];
3302}
3303
3304def LifetimeBoundDocs : Documentation {
3305  let Category = DocCatFunction;
3306  let Content = [{
3307The ``lifetimebound`` attribute on a function parameter or implicit object
3308parameter indicates that objects that are referred to by that parameter may
3309also be referred to by the return value of the annotated function (or, for a
3310parameter of a constructor, by the value of the constructed object). It is only
3311supported in C++.
3312
3313By default, a reference is considered to refer to its referenced object, a
3314pointer is considered to refer to its pointee, a ``std::initializer_list<T>``
3315is considered to refer to its underlying array, and aggregates (arrays and
3316simple ``struct``\s) are considered to refer to all objects that their
3317transitive subobjects refer to.
3318
3319Clang warns if it is able to detect that an object or reference refers to
3320another object with a shorter lifetime. For example, Clang will warn if a
3321function returns a reference to a local variable, or if a reference is bound to
3322a temporary object whose lifetime is not extended. By using the
3323``lifetimebound`` attribute, this determination can be extended to look through
3324user-declared functions. For example:
3325
3326.. code-block:: c++
3327
3328    // Returns m[key] if key is present, or default_value if not.
3329    template<typename T, typename U>
3330    const U &get_or_default(const std::map<T, U> &m [[clang::lifetimebound]],
3331                            const T &key, /* note, not lifetimebound */
3332                            const U &default_value [[clang::lifetimebound]]);
3333
3334    std::map<std::string, std::string> m;
3335    // warning: temporary "bar"s that might be bound to local reference 'val'
3336    // will be destroyed at the end of the full-expression
3337    const std::string &val = get_or_default(m, "foo"s, "bar"s);
3338
3339    // No warning in this case.
3340    std::string def_val = "bar"s;
3341    const std::string &val = get_or_default(m, "foo"s, def_val);
3342
3343The attribute can be applied to the implicit ``this`` parameter of a member
3344function by writing the attribute after the function type:
3345
3346.. code-block:: c++
3347
3348    struct string {
3349      // The returned pointer should not outlive ``*this``.
3350      const char *data() const [[clang::lifetimebound]];
3351    };
3352
3353This attribute is inspired by the C++ committee paper `P0936R0
3354<http://wg21.link/p0936r0>`_, but does not affect whether temporary objects
3355have their lifetimes extended.
3356  }];
3357}
3358
3359def TrivialABIDocs : Documentation {
3360  let Category = DocCatDecl;
3361  let Content = [{
3362The ``trivial_abi`` attribute can be applied to a C++ class, struct, or union.
3363It instructs the compiler to pass and return the type using the C ABI for the
3364underlying type when the type would otherwise be considered non-trivial for the
3365purpose of calls.
3366A class annotated with ``trivial_abi`` can have non-trivial destructors or
3367copy/move constructors without automatically becoming non-trivial for the
3368purposes of calls. For example:
3369
3370  .. code-block:: c++
3371
3372    // A is trivial for the purposes of calls because ``trivial_abi`` makes the
3373    // user-provided special functions trivial.
3374    struct __attribute__((trivial_abi)) A {
3375      ~A();
3376      A(const A &);
3377      A(A &&);
3378      int x;
3379    };
3380
3381    // B's destructor and copy/move constructor are considered trivial for the
3382    // purpose of calls because A is trivial.
3383    struct B {
3384      A a;
3385    };
3386
3387If a type is trivial for the purposes of calls, has a non-trivial destructor,
3388and is passed as an argument by value, the convention is that the callee will
3389destroy the object before returning.
3390
3391If a type is trivial for the purpose of calls, it is assumed to be trivially
3392relocatable for the purpose of ``__is_trivially_relocatable``.
3393
3394Attribute ``trivial_abi`` has no effect in the following cases:
3395
3396- The class directly declares a virtual base or virtual methods.
3397- Copy constructors and move constructors of the class are all deleted.
3398- The class has a base class that is non-trivial for the purposes of calls.
3399- The class has a non-static data member whose type is non-trivial for the
3400  purposes of calls, which includes:
3401
3402  - classes that are non-trivial for the purposes of calls
3403  - __weak-qualified types in Objective-C++
3404  - arrays of any of the above
3405  }];
3406}
3407
3408def MSInheritanceDocs : Documentation {
3409  let Category = DocCatDecl;
3410  let Heading = "__single_inhertiance, __multiple_inheritance, __virtual_inheritance";
3411  let Content = [{
3412This collection of keywords is enabled under ``-fms-extensions`` and controls
3413the pointer-to-member representation used on ``*-*-win32`` targets.
3414
3415The ``*-*-win32`` targets utilize a pointer-to-member representation which
3416varies in size and alignment depending on the definition of the underlying
3417class.
3418
3419However, this is problematic when a forward declaration is only available and
3420no definition has been made yet. In such cases, Clang is forced to utilize the
3421most general representation that is available to it.
3422
3423These keywords make it possible to use a pointer-to-member representation other
3424than the most general one regardless of whether or not the definition will ever
3425be present in the current translation unit.
3426
3427This family of keywords belong between the ``class-key`` and ``class-name``:
3428
3429.. code-block:: c++
3430
3431  struct __single_inheritance S;
3432  int S::*i;
3433  struct S {};
3434
3435This keyword can be applied to class templates but only has an effect when used
3436on full specializations:
3437
3438.. code-block:: c++
3439
3440  template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
3441  template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
3442  template <> struct __single_inheritance A<int, float>;
3443
3444Note that choosing an inheritance model less general than strictly necessary is
3445an error:
3446
3447.. code-block:: c++
3448
3449  struct __multiple_inheritance S; // error: inheritance model does not match definition
3450  int S::*i;
3451  struct S {};
3452}];
3453}
3454
3455def MSNoVTableDocs : Documentation {
3456  let Category = DocCatDecl;
3457  let Content = [{
3458This attribute can be added to a class declaration or definition to signal to
3459the compiler that constructors and destructors will not reference the virtual
3460function table. It is only supported when using the Microsoft C++ ABI.
3461  }];
3462}
3463
3464def OptnoneDocs : Documentation {
3465  let Category = DocCatFunction;
3466  let Content = [{
3467The ``optnone`` attribute suppresses essentially all optimizations
3468on a function or method, regardless of the optimization level applied to
3469the compilation unit as a whole. This is particularly useful when you
3470need to debug a particular function, but it is infeasible to build the
3471entire application without optimization. Avoiding optimization on the
3472specified function can improve the quality of the debugging information
3473for that function.
3474
3475This attribute is incompatible with the ``always_inline`` and ``minsize``
3476attributes.
3477  }];
3478}
3479
3480def LoopHintDocs : Documentation {
3481  let Category = DocCatStmt;
3482  let Heading = "#pragma clang loop";
3483  let Content = [{
3484The ``#pragma clang loop`` directive allows loop optimization hints to be
3485specified for the subsequent loop. The directive allows pipelining to be
3486disabled, or vectorization, vector predication, interleaving, and unrolling to
3487be enabled or disabled. Vector width, vector predication, interleave count,
3488unrolling count, and the initiation interval for pipelining can be explicitly
3489specified. See `language extensions
3490<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
3491for details.
3492  }];
3493}
3494
3495def UnrollHintDocs : Documentation {
3496  let Category = DocCatStmt;
3497  let Heading = "#pragma unroll, #pragma nounroll";
3498  let Content = [{
3499Loop unrolling optimization hints can be specified with ``#pragma unroll`` and
3500``#pragma nounroll``. The pragma is placed immediately before a for, while,
3501do-while, or c++11 range-based for loop. GCC's loop unrolling hints
3502``#pragma GCC unroll`` and ``#pragma GCC nounroll`` are also supported and have
3503identical semantics to ``#pragma unroll`` and ``#pragma nounroll``.
3504
3505Specifying ``#pragma unroll`` without a parameter directs the loop unroller to
3506attempt to fully unroll the loop if the trip count is known at compile time and
3507attempt to partially unroll the loop if the trip count is not known at compile
3508time:
3509
3510.. code-block:: c++
3511
3512  #pragma unroll
3513  for (...) {
3514    ...
3515  }
3516
3517Specifying the optional parameter, ``#pragma unroll _value_``, directs the
3518unroller to unroll the loop ``_value_`` times. The parameter may optionally be
3519enclosed in parentheses:
3520
3521.. code-block:: c++
3522
3523  #pragma unroll 16
3524  for (...) {
3525    ...
3526  }
3527
3528  #pragma unroll(16)
3529  for (...) {
3530    ...
3531  }
3532
3533Specifying ``#pragma nounroll`` indicates that the loop should not be unrolled:
3534
3535.. code-block:: c++
3536
3537  #pragma nounroll
3538  for (...) {
3539    ...
3540  }
3541
3542``#pragma unroll`` and ``#pragma unroll _value_`` have identical semantics to
3543``#pragma clang loop unroll(full)`` and
3544``#pragma clang loop unroll_count(_value_)`` respectively. ``#pragma nounroll``
3545is equivalent to ``#pragma clang loop unroll(disable)``. See
3546`language extensions
3547<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
3548for further details including limitations of the unroll hints.
3549  }];
3550}
3551
3552def PipelineHintDocs : Documentation {
3553  let Category = DocCatStmt;
3554  let Heading = "#pragma clang loop pipeline, #pragma clang loop pipeline_initiation_interval";
3555  let Content = [{
3556    Software Pipelining optimization is a technique used to optimize loops by
3557  utilizing instruction-level parallelism. It reorders loop instructions to
3558  overlap iterations. As a result, the next iteration starts before the previous
3559  iteration has finished. The module scheduling technique creates a schedule for
3560  one iteration such that when repeating at regular intervals, no inter-iteration
3561  dependencies are violated. This constant interval(in cycles) between the start
3562  of iterations is called the initiation interval. i.e. The initiation interval
3563  is the number of cycles between two iterations of an unoptimized loop in the
3564  newly created schedule. A new, optimized loop is created such that a single iteration
3565  of the loop executes in the same number of cycles as the initiation interval.
3566    For further details see <https://llvm.org/pubs/2005-06-17-LattnerMSThesis-book.pdf>.
3567
3568  ``#pragma clang loop pipeline and #pragma loop pipeline_initiation_interval``
3569  could be used as hints for the software pipelining optimization. The pragma is
3570  placed immediately before a for, while, do-while, or a C++11 range-based for
3571  loop.
3572
3573  Using ``#pragma clang loop pipeline(disable)`` avoids the software pipelining
3574  optimization. The disable state can only be specified:
3575
3576  .. code-block:: c++
3577
3578  #pragma clang loop pipeline(disable)
3579  for (...) {
3580    ...
3581  }
3582
3583  Using ``#pragma loop pipeline_initiation_interval`` instructs
3584  the software pipeliner to try the specified initiation interval.
3585  If a schedule was found then the resulting loop iteration would have
3586  the specified cycle count. If a schedule was not found then loop
3587  remains unchanged. The initiation interval must be a positive number
3588  greater than zero:
3589
3590  .. code-block:: c++
3591
3592  #pragma loop pipeline_initiation_interval(10)
3593  for (...) {
3594    ...
3595  }
3596
3597  }];
3598}
3599
3600def OpenCLUnrollHintDocs : Documentation {
3601  let Category = DocCatStmt;
3602  let Content = [{
3603The opencl_unroll_hint attribute qualifier can be used to specify that a loop
3604(for, while and do loops) can be unrolled. This attribute qualifier can be
3605used to specify full unrolling or partial unrolling by a specified amount.
3606This is a compiler hint and the compiler may ignore this directive. See
3607`OpenCL v2.0 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf>`_
3608s6.11.5 for details.
3609  }];
3610}
3611
3612def OpenCLIntelReqdSubGroupSizeDocs : Documentation {
3613  let Category = DocCatStmt;
3614  let Content = [{
3615The optional attribute intel_reqd_sub_group_size can be used to indicate that
3616the kernel must be compiled and executed with the specified subgroup size. When
3617this attribute is present, get_max_sub_group_size() is guaranteed to return the
3618specified integer value. This is important for the correctness of many subgroup
3619algorithms, and in some cases may be used by the compiler to generate more optimal
3620code. See `cl_intel_required_subgroup_size
3621<https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.txt>`
3622for details.
3623  }];
3624}
3625
3626def OpenCLAccessDocs : Documentation {
3627  let Category = DocCatStmt;
3628  let Heading = "__read_only, __write_only, __read_write (read_only, write_only, read_write)";
3629  let Content = [{
3630The access qualifiers must be used with image object arguments or pipe arguments
3631to declare if they are being read or written by a kernel or function.
3632
3633The read_only/__read_only, write_only/__write_only and read_write/__read_write
3634names are reserved for use as access qualifiers and shall not be used otherwise.
3635
3636.. code-block:: c
3637
3638  kernel void
3639  foo (read_only image2d_t imageA,
3640       write_only image2d_t imageB) {
3641    ...
3642  }
3643
3644In the above example imageA is a read-only 2D image object, and imageB is a
3645write-only 2D image object.
3646
3647The read_write (or __read_write) qualifier can not be used with pipe.
3648
3649More details can be found in the OpenCL C language Spec v2.0, Section 6.6.
3650    }];
3651}
3652
3653def DocOpenCLAddressSpaces : DocumentationCategory<"OpenCL Address Spaces"> {
3654  let Content = [{
3655The address space qualifier may be used to specify the region of memory that is
3656used to allocate the object. OpenCL supports the following address spaces:
3657__generic(generic), __global(global), __local(local), __private(private),
3658__constant(constant).
3659
3660  .. code-block:: c
3661
3662    __constant int c = ...;
3663
3664    __generic int* foo(global int* g) {
3665      __local int* l;
3666      private int p;
3667      ...
3668      return l;
3669    }
3670
3671More details can be found in the OpenCL C language Spec v2.0, Section 6.5.
3672  }];
3673}
3674
3675def OpenCLAddressSpaceGenericDocs : Documentation {
3676  let Category = DocOpenCLAddressSpaces;
3677  let Heading = "__generic, generic, [[clang::opencl_generic]]";
3678  let Content = [{
3679The generic address space attribute is only available with OpenCL v2.0 and later.
3680It can be used with pointer types. Variables in global and local scope and
3681function parameters in non-kernel functions can have the generic address space
3682type attribute. It is intended to be a placeholder for any other address space
3683except for '__constant' in OpenCL code which can be used with multiple address
3684spaces.
3685  }];
3686}
3687
3688def OpenCLAddressSpaceConstantDocs : Documentation {
3689  let Category = DocOpenCLAddressSpaces;
3690  let Heading = "__constant, constant, [[clang::opencl_constant]]";
3691  let Content = [{
3692The constant address space attribute signals that an object is located in
3693a constant (non-modifiable) memory region. It is available to all work items.
3694Any type can be annotated with the constant address space attribute. Objects
3695with the constant address space qualifier can be declared in any scope and must
3696have an initializer.
3697  }];
3698}
3699
3700def OpenCLAddressSpaceGlobalDocs : Documentation {
3701  let Category = DocOpenCLAddressSpaces;
3702  let Heading = "__global, global, [[clang::opencl_global]]";
3703  let Content = [{
3704The global address space attribute specifies that an object is allocated in
3705global memory, which is accessible by all work items. The content stored in this
3706memory area persists between kernel executions. Pointer types to the global
3707address space are allowed as function parameters or local variables. Starting
3708with OpenCL v2.0, the global address space can be used with global (program
3709scope) variables and static local variable as well.
3710  }];
3711}
3712
3713def OpenCLAddressSpaceGlobalExtDocs : Documentation {
3714  let Category = DocOpenCLAddressSpaces;
3715  let Heading = "[[clang::opencl_global_device]], [[clang::opencl_global_host]]";
3716  let Content = [{
3717The ``global_device`` and ``global_host`` address space attributes specify that
3718an object is allocated in global memory on the device/host. It helps to
3719distinguish USM (Unified Shared Memory) pointers that access global device
3720memory from those that access global host memory. These new address spaces are
3721a subset of the ``__global/opencl_global`` address space, the full address space
3722set model for OpenCL 2.0 with the extension looks as follows:
3723
3724  | generic->global->host
3725  |                ->device
3726  |        ->private
3727  |        ->local
3728  | constant
3729
3730As ``global_device`` and ``global_host`` are a subset of
3731``__global/opencl_global`` address spaces it is allowed to convert
3732``global_device`` and ``global_host`` address spaces to
3733``__global/opencl_global`` address spaces (following ISO/IEC TR 18037 5.1.3
3734"Address space nesting and rules for pointers").
3735  }];
3736}
3737
3738def OpenCLAddressSpaceLocalDocs : Documentation {
3739  let Category = DocOpenCLAddressSpaces;
3740  let Heading = "__local, local, [[clang::opencl_local]]";
3741  let Content = [{
3742The local address space specifies that an object is allocated in the local (work
3743group) memory area, which is accessible to all work items in the same work
3744group. The content stored in this memory region is not accessible after
3745the kernel execution ends. In a kernel function scope, any variable can be in
3746the local address space. In other scopes, only pointer types to the local address
3747space are allowed. Local address space variables cannot have an initializer.
3748  }];
3749}
3750
3751def OpenCLAddressSpacePrivateDocs : Documentation {
3752  let Category = DocOpenCLAddressSpaces;
3753  let Heading = "__private, private, [[clang::opencl_private]]";
3754  let Content = [{
3755The private address space specifies that an object is allocated in the private
3756(work item) memory. Other work items cannot access the same memory area and its
3757content is destroyed after work item execution ends. Local variables can be
3758declared in the private address space. Function arguments are always in the
3759private address space. Kernel function arguments of a pointer or an array type
3760cannot point to the private address space.
3761  }];
3762}
3763
3764def OpenCLNoSVMDocs : Documentation {
3765  let Category = DocCatVariable;
3766  let Content = [{
3767OpenCL 2.0 supports the optional ``__attribute__((nosvm))`` qualifier for
3768pointer variable. It informs the compiler that the pointer does not refer
3769to a shared virtual memory region. See OpenCL v2.0 s6.7.2 for details.
3770
3771Since it is not widely used and has been removed from OpenCL 2.1, it is ignored
3772by Clang.
3773  }];
3774}
3775
3776def Ptr32Docs : Documentation {
3777  let Category = DocCatType;
3778  let Content = [{
3779The ``__ptr32`` qualifier represents a native pointer on a 32-bit system. On a
378064-bit system, a pointer with ``__ptr32`` is extended to a 64-bit pointer. The
3781``__sptr`` and ``__uptr`` qualifiers can be used to specify whether the pointer
3782is sign extended or zero extended. This qualifier is enabled under
3783``-fms-extensions``.
3784  }];
3785}
3786
3787def Ptr64Docs : Documentation {
3788  let Category = DocCatType;
3789  let Content = [{
3790The ``__ptr64`` qualifier represents a native pointer on a 64-bit system. On a
379132-bit system, a ``__ptr64`` pointer is truncated to a 32-bit pointer. This
3792qualifier is enabled under ``-fms-extensions``.
3793  }];
3794}
3795
3796def SPtrDocs : Documentation {
3797  let Category = DocCatType;
3798  let Content = [{
3799The ``__sptr`` qualifier specifies that a 32-bit pointer should be sign
3800extended when converted to a 64-bit pointer.
3801  }];
3802}
3803
3804def UPtrDocs : Documentation {
3805  let Category = DocCatType;
3806  let Content = [{
3807The ``__uptr`` qualifier specifies that a 32-bit pointer should be zero
3808extended when converted to a 64-bit pointer.
3809  }];
3810}
3811
3812
3813def NullabilityDocs : DocumentationCategory<"Nullability Attributes"> {
3814  let Content = [{
3815Whether a particular pointer may be "null" is an important concern when working
3816with pointers in the C family of languages. The various nullability attributes
3817indicate whether a particular pointer can be null or not, which makes APIs more
3818expressive and can help static analysis tools identify bugs involving null
3819pointers. Clang supports several kinds of nullability attributes: the
3820``nonnull`` and ``returns_nonnull`` attributes indicate which function or
3821method parameters and result types can never be null, while nullability type
3822qualifiers indicate which pointer types can be null (``_Nullable``) or cannot
3823be null (``_Nonnull``).
3824
3825The nullability (type) qualifiers express whether a value of a given pointer
3826type can be null (the ``_Nullable`` qualifier), doesn't have a defined meaning
3827for null (the ``_Nonnull`` qualifier), or for which the purpose of null is
3828unclear (the ``_Null_unspecified`` qualifier). Because nullability qualifiers
3829are expressed within the type system, they are more general than the
3830``nonnull`` and ``returns_nonnull`` attributes, allowing one to express (for
3831example) a nullable pointer to an array of nonnull pointers. Nullability
3832qualifiers are written to the right of the pointer to which they apply. For
3833example:
3834
3835  .. code-block:: c
3836
3837    // No meaningful result when 'ptr' is null (here, it happens to be undefined behavior).
3838    int fetch(int * _Nonnull ptr) { return *ptr; }
3839
3840    // 'ptr' may be null.
3841    int fetch_or_zero(int * _Nullable ptr) {
3842      return ptr ? *ptr : 0;
3843    }
3844
3845    // A nullable pointer to non-null pointers to const characters.
3846    const char *join_strings(const char * _Nonnull * _Nullable strings, unsigned n);
3847
3848In Objective-C, there is an alternate spelling for the nullability qualifiers
3849that can be used in Objective-C methods and properties using context-sensitive,
3850non-underscored keywords. For example:
3851
3852  .. code-block:: objective-c
3853
3854    @interface NSView : NSResponder
3855      - (nullable NSView *)ancestorSharedWithView:(nonnull NSView *)aView;
3856      @property (assign, nullable) NSView *superview;
3857      @property (readonly, nonnull) NSArray *subviews;
3858    @end
3859  }];
3860}
3861
3862def TypeNonNullDocs : Documentation {
3863  let Category = NullabilityDocs;
3864  let Content = [{
3865The ``_Nonnull`` nullability qualifier indicates that null is not a meaningful
3866value for a value of the ``_Nonnull`` pointer type. For example, given a
3867declaration such as:
3868
3869  .. code-block:: c
3870
3871    int fetch(int * _Nonnull ptr);
3872
3873a caller of ``fetch`` should not provide a null value, and the compiler will
3874produce a warning if it sees a literal null value passed to ``fetch``. Note
3875that, unlike the declaration attribute ``nonnull``, the presence of
3876``_Nonnull`` does not imply that passing null is undefined behavior: ``fetch``
3877is free to consider null undefined behavior or (perhaps for
3878backward-compatibility reasons) defensively handle null.
3879  }];
3880}
3881
3882def TypeNullableDocs : Documentation {
3883  let Category = NullabilityDocs;
3884  let Content = [{
3885The ``_Nullable`` nullability qualifier indicates that a value of the
3886``_Nullable`` pointer type can be null. For example, given:
3887
3888  .. code-block:: c
3889
3890    int fetch_or_zero(int * _Nullable ptr);
3891
3892a caller of ``fetch_or_zero`` can provide null.
3893  }];
3894}
3895
3896def TypeNullableResultDocs : Documentation {
3897  let Category = NullabilityDocs;
3898  let Content = [{
3899The ``_Nullable_result`` nullability qualifier means that a value of the
3900``_Nullable_result`` pointer can be ``nil``, just like ``_Nullable``. Where this
3901attribute differs from ``_Nullable`` is when it's used on a parameter to a
3902completion handler in a Swift async method. For instance, here:
3903
3904  .. code-block:: objc
3905
3906    -(void)fetchSomeDataWithID:(int)identifier
3907             completionHandler:(void (^)(Data *_Nullable_result result, NSError *error))completionHandler;
3908
3909This method asynchronously calls ``completionHandler`` when the data is
3910available, or calls it with an error. ``_Nullable_result`` indicates to the
3911Swift importer that this is the uncommon case where ``result`` can get ``nil``
3912even if no error has occurred, and will therefore import it as a Swift optional
3913type. Otherwise, if ``result`` was annotated with ``_Nullable``, the Swift
3914importer will assume that ``result`` will always be non-nil unless an error
3915occurred.
3916}];
3917}
3918
3919def TypeNullUnspecifiedDocs : Documentation {
3920  let Category = NullabilityDocs;
3921  let Content = [{
3922The ``_Null_unspecified`` nullability qualifier indicates that neither the
3923``_Nonnull`` nor ``_Nullable`` qualifiers make sense for a particular pointer
3924type. It is used primarily to indicate that the role of null with specific
3925pointers in a nullability-annotated header is unclear, e.g., due to
3926overly-complex implementations or historical factors with a long-lived API.
3927  }];
3928}
3929
3930def NonNullDocs : Documentation {
3931  let Category = NullabilityDocs;
3932  let Content = [{
3933The ``nonnull`` attribute indicates that some function parameters must not be
3934null, and can be used in several different ways. It's original usage
3935(`from GCC <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes>`_)
3936is as a function (or Objective-C method) attribute that specifies which
3937parameters of the function are nonnull in a comma-separated list. For example:
3938
3939  .. code-block:: c
3940
3941    extern void * my_memcpy (void *dest, const void *src, size_t len)
3942                    __attribute__((nonnull (1, 2)));
3943
3944Here, the ``nonnull`` attribute indicates that parameters 1 and 2
3945cannot have a null value. Omitting the parenthesized list of parameter indices
3946means that all parameters of pointer type cannot be null:
3947
3948  .. code-block:: c
3949
3950    extern void * my_memcpy (void *dest, const void *src, size_t len)
3951                    __attribute__((nonnull));
3952
3953Clang also allows the ``nonnull`` attribute to be placed directly on a function
3954(or Objective-C method) parameter, eliminating the need to specify the
3955parameter index ahead of type. For example:
3956
3957  .. code-block:: c
3958
3959    extern void * my_memcpy (void *dest __attribute__((nonnull)),
3960                             const void *src __attribute__((nonnull)), size_t len);
3961
3962Note that the ``nonnull`` attribute indicates that passing null to a non-null
3963parameter is undefined behavior, which the optimizer may take advantage of to,
3964e.g., remove null checks. The ``_Nonnull`` type qualifier indicates that a
3965pointer cannot be null in a more general manner (because it is part of the type
3966system) and does not imply undefined behavior, making it more widely applicable.
3967  }];
3968}
3969
3970def RestrictDocs : Documentation {
3971  let Category = DocCatFunction;
3972  let Heading = "malloc";
3973  let Content = [{
3974The ``malloc`` attribute indicates that the function acts like a system memory
3975allocation function, returning a pointer to allocated storage disjoint from the
3976storage for any other object accessible to the caller.
3977  }];
3978}
3979
3980def ReturnsNonNullDocs : Documentation {
3981  let Category = NullabilityDocs;
3982  let Content = [{
3983The ``returns_nonnull`` attribute indicates that a particular function (or
3984Objective-C method) always returns a non-null pointer. For example, a
3985particular system ``malloc`` might be defined to terminate a process when
3986memory is not available rather than returning a null pointer:
3987
3988  .. code-block:: c
3989
3990    extern void * malloc (size_t size) __attribute__((returns_nonnull));
3991
3992The ``returns_nonnull`` attribute implies that returning a null pointer is
3993undefined behavior, which the optimizer may take advantage of. The ``_Nonnull``
3994type qualifier indicates that a pointer cannot be null in a more general manner
3995(because it is part of the type system) and does not imply undefined behavior,
3996making it more widely applicable
3997}];
3998}
3999
4000def NoAliasDocs : Documentation {
4001  let Category = DocCatFunction;
4002  let Content = [{
4003The ``noalias`` attribute indicates that the only memory accesses inside
4004function are loads and stores from objects pointed to by its pointer-typed
4005arguments, with arbitrary offsets.
4006  }];
4007}
4008
4009def NSErrorDomainDocs : Documentation {
4010  let Category = DocCatDecl;
4011  let Content = [{
4012In Cocoa frameworks in Objective-C, one can group related error codes in enums
4013and categorize these enums with error domains.
4014
4015The ``ns_error_domain`` attribute indicates a global ``NSString`` or
4016``CFString`` constant representing the error domain that an error code belongs
4017to. For pointer uniqueness and code size this is a constant symbol, not a
4018literal.
4019
4020The domain and error code need to be used together. The ``ns_error_domain``
4021attribute links error codes to their domain at the source level.
4022
4023This metadata is useful for documentation purposes, for static analysis, and for
4024improving interoperability between Objective-C and Swift. It is not used for
4025code generation in Objective-C.
4026
4027For example:
4028
4029  .. code-block:: objc
4030
4031    #define NS_ERROR_ENUM(_type, _name, _domain)  \
4032      enum _name : _type _name; enum __attribute__((ns_error_domain(_domain))) _name : _type
4033
4034    extern NSString *const MyErrorDomain;
4035    typedef NS_ERROR_ENUM(unsigned char, MyErrorEnum, MyErrorDomain) {
4036      MyErrFirst,
4037      MyErrSecond,
4038    };
4039  }];
4040}
4041
4042def SwiftDocs : DocumentationCategory<"Customizing Swift Import"> {
4043  let Content = [{
4044Clang supports additional attributes for customizing how APIs are imported into
4045Swift.
4046  }];
4047}
4048
4049def SwiftAsyncNameDocs : Documentation {
4050  let Category = SwiftDocs;
4051  let Heading = "swift_async_name";
4052  let Content = [{
4053The ``swift_async_name`` attribute provides the name of the ``async`` overload for
4054the given declaration in Swift. If this attribute is absent, the name is
4055transformed according to the algorithm built into the Swift compiler.
4056
4057The argument is a string literal that contains the Swift name of the function or
4058method. The name may be a compound Swift name. The function or method with such
4059an attribute must have more than zero parameters, as its last parameter is
4060assumed to be a callback that's eliminated in the Swift ``async`` name.
4061
4062  .. code-block:: objc
4063
4064    @interface URL
4065    + (void) loadContentsFrom:(URL *)url callback:(void (^)(NSData *))data __attribute__((__swift_async_name__("URL.loadContentsFrom(_:)")))
4066    @end
4067  }];
4068}
4069
4070def SwiftAttrDocs : Documentation {
4071  let Category = SwiftDocs;
4072  let Heading = "swift_attr";
4073  let Content = [{
4074The ``swift_attr`` provides a Swift-specific annotation for the declaration
4075to which the attribute appertains to. It can be used on any declaration
4076in Clang. This kind of annotation is ignored by Clang as it doesn't have any
4077semantic meaning in languages supported by Clang. The Swift compiler can
4078interpret these annotations according to its own rules when importing C or
4079Objective-C declarations.
4080}];
4081}
4082
4083def SwiftBridgeDocs : Documentation {
4084  let Category = SwiftDocs;
4085  let Heading = "swift_bridge";
4086  let Content = [{
4087The ``swift_bridge`` attribute indicates that the declaration to which the
4088attribute appertains is bridged to the named Swift type.
4089
4090  .. code-block:: objc
4091
4092    __attribute__((__objc_root__))
4093    @interface Base
4094    - (instancetype)init;
4095    @end
4096
4097    __attribute__((__swift_bridge__("BridgedI")))
4098    @interface I : Base
4099    @end
4100
4101In this example, the Objective-C interface ``I`` will be made available to Swift
4102with the name ``BridgedI``. It would be possible for the compiler to refer to
4103``I`` still in order to bridge the type back to Objective-C.
4104  }];
4105}
4106
4107def SwiftBridgedTypedefDocs : Documentation {
4108  let Category = SwiftDocs;
4109  let Heading = "swift_bridged";
4110  let Content = [{
4111The ``swift_bridged_typedef`` attribute indicates that when the typedef to which
4112the attribute appertains is imported into Swift, it should refer to the bridged
4113Swift type (e.g. Swift's ``String``) rather than the Objective-C type as written
4114(e.g. ``NSString``).
4115
4116  .. code-block:: objc
4117
4118    @interface NSString;
4119    typedef NSString *AliasedString __attribute__((__swift_bridged_typedef__));
4120
4121    extern void acceptsAliasedString(AliasedString _Nonnull parameter);
4122
4123In this case, the function ``acceptsAliasedString`` will be imported into Swift
4124as a function which accepts a ``String`` type parameter.
4125  }];
4126}
4127
4128def SwiftObjCMembersDocs : Documentation {
4129  let Category = SwiftDocs;
4130  let Heading = "swift_objc_members";
4131  let Content = [{
4132This attribute indicates that Swift subclasses and members of Swift extensions
4133of this class will be implicitly marked with the ``@objcMembers`` Swift
4134attribute, exposing them back to Objective-C.
4135  }];
4136}
4137
4138def SwiftErrorDocs : Documentation {
4139  let Category = SwiftDocs;
4140  let Heading = "swift_error";
4141  let Content = [{
4142The ``swift_error`` attribute controls whether a particular function (or
4143Objective-C method) is imported into Swift as a throwing function, and if so,
4144which dynamic convention it uses.
4145
4146All of these conventions except ``none`` require the function to have an error
4147parameter. Currently, the error parameter is always the last parameter of type
4148``NSError**`` or ``CFErrorRef*``. Swift will remove the error parameter from
4149the imported API. When calling the API, Swift will always pass a valid address
4150initialized to a null pointer.
4151
4152* ``swift_error(none)`` means that the function should not be imported as
4153  throwing. The error parameter and result type will be imported normally.
4154
4155* ``swift_error(null_result)`` means that calls to the function should be
4156  considered to have thrown if they return a null value. The return type must be
4157  a pointer type, and it will be imported into Swift with a non-optional type.
4158  This is the default error convention for Objective-C methods that return
4159  pointers.
4160
4161* ``swift_error(zero_result)`` means that calls to the function should be
4162  considered to have thrown if they return a zero result. The return type must be
4163  an integral type. If the return type would have been imported as ``Bool``, it
4164  is instead imported as ``Void``. This is the default error convention for
4165  Objective-C methods that return a type that would be imported as ``Bool``.
4166
4167* ``swift_error(nonzero_result)`` means that calls to the function should be
4168  considered to have thrown if they return a non-zero result. The return type must
4169  be an integral type. If the return type would have been imported as ``Bool``,
4170  it is instead imported as ``Void``.
4171
4172* ``swift_error(nonnull_error)`` means that calls to the function should be
4173  considered to have thrown if they leave a non-null error in the error parameter.
4174  The return type is left unmodified.
4175
4176  }];
4177}
4178
4179def SwiftNameDocs : Documentation {
4180  let Category = SwiftDocs;
4181  let Heading = "swift_name";
4182  let Content = [{
4183The ``swift_name`` attribute provides the name of the declaration in Swift. If
4184this attribute is absent, the name is transformed according to the algorithm
4185built into the Swift compiler.
4186
4187The argument is a string literal that contains the Swift name of the function,
4188variable, or type. When renaming a function, the name may be a compound Swift
4189name. For a type, enum constant, property, or variable declaration, the name
4190must be a simple or qualified identifier.
4191
4192  .. code-block:: objc
4193
4194    @interface URL
4195    - (void) initWithString:(NSString *)s __attribute__((__swift_name__("URL.init(_:)")))
4196    @end
4197
4198    void __attribute__((__swift_name__("squareRoot()"))) sqrt(double v) {
4199    }
4200  }];
4201}
4202
4203def SwiftNewTypeDocs : Documentation {
4204  let Category = SwiftDocs;
4205  let Heading = "swift_newtype";
4206  let Content = [{
4207The ``swift_newtype`` attribute indicates that the typedef to which the
4208attribute appertains is imported as a new Swift type of the typedef's name.
4209Previously, the attribute was spelt ``swift_wrapper``. While the behaviour of
4210the attribute is identical with either spelling, ``swift_wrapper`` is
4211deprecated, only exists for compatibility purposes, and should not be used in
4212new code.
4213
4214* ``swift_newtype(struct)`` means that a Swift struct will be created for this
4215  typedef.
4216
4217* ``swift_newtype(enum)`` means that a Swift enum will be created for this
4218  typedef.
4219
4220  .. code-block:: c
4221
4222    // Import UIFontTextStyle as an enum type, with enumerated values being
4223    // constants.
4224    typedef NSString * UIFontTextStyle __attribute__((__swift_newtype__(enum)));
4225
4226    // Import UIFontDescriptorFeatureKey as a structure type, with enumerated
4227    // values being members of the type structure.
4228    typedef NSString * UIFontDescriptorFeatureKey __attribute__((__swift_newtype__(struct)));
4229
4230  }];
4231}
4232
4233def SwiftPrivateDocs : Documentation {
4234  let Category = SwiftDocs;
4235  let Heading = "swift_private";
4236  let Content = [{
4237Declarations marked with the ``swift_private`` attribute are hidden from the
4238framework client but are still made available for use within the framework or
4239Swift SDK overlay.
4240
4241The purpose of this attribute is to permit a more idomatic implementation of
4242declarations in Swift while hiding the non-idiomatic one.
4243  }];
4244}
4245
4246def OMPDeclareSimdDocs : Documentation {
4247  let Category = DocCatFunction;
4248  let Heading = "#pragma omp declare simd";
4249  let Content = [{
4250The ``declare simd`` construct can be applied to a function to enable the creation
4251of one or more versions that can process multiple arguments using SIMD
4252instructions from a single invocation in a SIMD loop. The ``declare simd``
4253directive is a declarative directive. There may be multiple ``declare simd``
4254directives for a function. The use of a ``declare simd`` construct on a function
4255enables the creation of SIMD versions of the associated function that can be
4256used to process multiple arguments from a single invocation from a SIMD loop
4257concurrently.
4258The syntax of the ``declare simd`` construct is as follows:
4259
4260  .. code-block:: none
4261
4262    #pragma omp declare simd [clause[[,] clause] ...] new-line
4263    [#pragma omp declare simd [clause[[,] clause] ...] new-line]
4264    [...]
4265    function definition or declaration
4266
4267where clause is one of the following:
4268
4269  .. code-block:: none
4270
4271    simdlen(length)
4272    linear(argument-list[:constant-linear-step])
4273    aligned(argument-list[:alignment])
4274    uniform(argument-list)
4275    inbranch
4276    notinbranch
4277
4278  }];
4279}
4280
4281def OMPDeclareTargetDocs : Documentation {
4282  let Category = DocCatFunction;
4283  let Heading = "#pragma omp declare target";
4284  let Content = [{
4285The ``declare target`` directive specifies that variables and functions are mapped
4286to a device for OpenMP offload mechanism.
4287
4288The syntax of the declare target directive is as follows:
4289
4290  .. code-block:: c
4291
4292    #pragma omp declare target new-line
4293    declarations-definition-seq
4294    #pragma omp end declare target new-line
4295
4296or
4297
4298  .. code-block:: c
4299
4300    #pragma omp declare target (extended-list) new-line
4301
4302or
4303
4304  .. code-block:: c
4305
4306    #pragma omp declare target clause[ [,] clause ... ] new-line
4307
4308where clause is one of the following:
4309
4310
4311  .. code-block:: c
4312
4313     to(extended-list)
4314     link(list)
4315     device_type(host | nohost | any)
4316  }];
4317}
4318
4319def OMPDeclareVariantDocs : Documentation {
4320  let Category = DocCatFunction;
4321  let Heading = "#pragma omp declare variant";
4322  let Content = [{
4323The ``declare variant`` directive declares a specialized variant of a base
4324function and specifies the context in which that specialized variant is used.
4325The declare variant directive is a declarative directive.
4326The syntax of the ``declare variant`` construct is as follows:
4327
4328  .. code-block:: none
4329
4330    #pragma omp declare variant(variant-func-id) clause new-line
4331    [#pragma omp declare variant(variant-func-id) clause new-line]
4332    [...]
4333    function definition or declaration
4334
4335where clause is one of the following:
4336
4337  .. code-block:: none
4338
4339    match(context-selector-specification)
4340
4341and where ``variant-func-id`` is the name of a function variant that is either a
4342base language identifier or, for C++, a template-id.
4343
4344Clang provides the following context selector extensions, used via
4345``implementation={extension(EXTENSION)}``:
4346
4347  .. code-block:: none
4348
4349    match_all
4350    match_any
4351    match_none
4352    disable_implicit_base
4353    allow_templates
4354    bind_to_declaration
4355
4356The match extensions change when the *entire* context selector is considered a
4357match for an OpenMP context. The default is ``all``, with ``none`` no trait in the
4358selector is allowed to be in the OpenMP context, with ``any`` a single trait in
4359both the selector and OpenMP context is sufficient. Only a single match
4360extension trait is allowed per context selector.
4361The disable extensions remove default effects of the ``begin declare variant``
4362applied to a definition. If ``disable_implicit_base`` is given, we will not
4363introduce an implicit base function for a variant if no base function was
4364found. The variant is still generated but will never be called, due to the
4365absence of a base function and consequently calls to a base function.
4366The allow extensions change when the ``begin declare variant`` effect is
4367applied to a definition. If ``allow_templates`` is given, template function
4368definitions are considered as specializations of existing or assumed template
4369declarations with the same name. The template parameters for the base functions
4370are used to instantiate the specialization. If ``bind_to_declartion`` is given,
4371apply the same variant rules to function declarations. This allows the user to
4372override declarations with only a function declaration.
4373  }];
4374}
4375
4376def LeafDocs : Documentation {
4377  let Category = DocCatVariable;
4378  let Content = [{
4379
4380The ``leaf`` attribute is used as a compiler hint to improve dataflow analysis
4381in library functions. Functions marked with the ``leaf`` attribute are not allowed
4382to jump back into the caller's translation unit, whether through invoking a
4383callback function, an external function call, use of ``longjmp``, or other means.
4384Therefore, they cannot use or modify any data that does not escape the caller function's
4385compilation unit.
4386
4387For more information see
4388`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html>`
4389}];
4390}
4391
4392def AssumptionDocs : Documentation {
4393  let Category = DocCatFunction;
4394  let Heading = "assume";
4395  let Content = [{
4396Clang supports the ``__attribute__((assume("assumption")))`` attribute to
4397provide additional information to the optimizer. The string-literal, here
4398"assumption", will be attached to the function declaration such that later
4399analysis and optimization passes can assume the "assumption" to hold.
4400This is similar to :ref:`__builtin_assume <langext-__builtin_assume>` but
4401instead of an expression that can be assumed to be non-zero, the assumption is
4402expressed as a string and it holds for the entire function.
4403
4404A function can have multiple assume attributes and they propagate from prior
4405declarations to later definitions. Multiple assumptions are aggregated into a
4406single comma separated string. Thus, one can provide multiple assumptions via
4407a comma separated string, i.a.,
4408``__attribute__((assume("assumption1,assumption2")))``.
4409
4410While LLVM plugins might provide more assumption strings, the default LLVM
4411optimization passes are aware of the following assumptions:
4412
4413  .. code-block:: none
4414
4415    "omp_no_openmp"
4416    "omp_no_openmp_routines"
4417    "omp_no_parallelism"
4418
4419The OpenMP standard defines the meaning of OpenMP assumptions ("omp_XYZ" is
4420spelled "XYZ" in the `OpenMP 5.1 Standard`_).
4421
4422.. _`OpenMP 5.1 Standard`: https://www.openmp.org/spec-html/5.1/openmpsu37.html#x56-560002.5.2
4423
4424}];
4425}
4426
4427def NoStackProtectorDocs : Documentation {
4428  let Category = DocCatFunction;
4429  let Content = [{
4430Clang supports the ``__attribute__((no_stack_protector))`` attribute which disables
4431the stack protector on the specified function. This attribute is useful for
4432selectively disabling the stack protector on some functions when building with
4433``-fstack-protector`` compiler option.
4434
4435For example, it disables the stack protector for the function ``foo`` but function
4436``bar`` will still be built with the stack protector with the ``-fstack-protector``
4437option.
4438
4439.. code-block:: c
4440
4441    int __attribute__((no_stack_protector))
4442    foo (int x); // stack protection will be disabled for foo.
4443
4444    int bar(int y); // bar can be built with the stack protector.
4445
4446    }];
4447}
4448
4449def NotTailCalledDocs : Documentation {
4450  let Category = DocCatFunction;
4451  let Content = [{
4452The ``not_tail_called`` attribute prevents tail-call optimization on statically
4453bound calls. Objective-c methods, and functions marked as ``always_inline``
4454cannot be marked as ``not_tail_called``.
4455
4456For example, it prevents tail-call optimization in the following case:
4457
4458  .. code-block:: c
4459
4460    int __attribute__((not_tail_called)) foo1(int);
4461
4462    int foo2(int a) {
4463      return foo1(a); // No tail-call optimization on direct calls.
4464    }
4465
4466However, it doesn't prevent tail-call optimization in this case:
4467
4468  .. code-block:: c
4469
4470    int __attribute__((not_tail_called)) foo1(int);
4471
4472    int foo2(int a) {
4473      int (*fn)(int) = &foo1;
4474
4475      // not_tail_called has no effect on an indirect call even if the call can
4476      // be resolved at compile time.
4477      return (*fn)(a);
4478    }
4479
4480Generally, marking an overriding virtual function as ``not_tail_called`` is
4481not useful, because this attribute is a property of the static type. Calls
4482made through a pointer or reference to the base class type will respect
4483the ``not_tail_called`` attribute of the base class's member function,
4484regardless of the runtime destination of the call:
4485
4486  .. code-block:: c++
4487
4488    struct Foo { virtual void f(); };
4489    struct Bar : Foo {
4490      [[clang::not_tail_called]] void f() override;
4491    };
4492    void callera(Bar& bar) {
4493      Foo& foo = bar;
4494      // not_tail_called has no effect on here, even though the
4495      // underlying method is f from Bar.
4496      foo.f();
4497      bar.f(); // No tail-call optimization on here.
4498    }
4499  }];
4500}
4501
4502def NoThrowDocs : Documentation {
4503  let Category = DocCatFunction;
4504  let Content = [{
4505Clang supports the GNU style ``__attribute__((nothrow))`` and Microsoft style
4506``__declspec(nothrow)`` attribute as an equivalent of ``noexcept`` on function
4507declarations. This attribute informs the compiler that the annotated function
4508does not throw an exception. This prevents exception-unwinding. This attribute
4509is particularly useful on functions in the C Standard Library that are
4510guaranteed to not throw an exception.
4511    }];
4512}
4513
4514def InternalLinkageDocs : Documentation {
4515  let Category = DocCatFunction;
4516  let Content = [{
4517The ``internal_linkage`` attribute changes the linkage type of the declaration
4518to internal. This is similar to C-style ``static``, but can be used on classes
4519and class methods. When applied to a class definition, this attribute affects
4520all methods and static data members of that class. This can be used to contain
4521the ABI of a C++ library by excluding unwanted class methods from the export
4522tables.
4523  }];
4524}
4525
4526def ExcludeFromExplicitInstantiationDocs : Documentation {
4527  let Category = DocCatFunction;
4528  let Content = [{
4529The ``exclude_from_explicit_instantiation`` attribute opts-out a member of a
4530class template from being part of explicit template instantiations of that
4531class template. This means that an explicit instantiation will not instantiate
4532members of the class template marked with the attribute, but also that code
4533where an extern template declaration of the enclosing class template is visible
4534will not take for granted that an external instantiation of the class template
4535would provide those members (which would otherwise be a link error, since the
4536explicit instantiation won't provide those members). For example, let's say we
4537don't want the ``data()`` method to be part of libc++'s ABI. To make sure it
4538is not exported from the dylib, we give it hidden visibility:
4539
4540  .. code-block:: c++
4541
4542    // in <string>
4543    template <class CharT>
4544    class basic_string {
4545    public:
4546      __attribute__((__visibility__("hidden")))
4547      const value_type* data() const noexcept { ... }
4548    };
4549
4550    template class basic_string<char>;
4551
4552Since an explicit template instantiation declaration for ``basic_string<char>``
4553is provided, the compiler is free to assume that ``basic_string<char>::data()``
4554will be provided by another translation unit, and it is free to produce an
4555external call to this function. However, since ``data()`` has hidden visibility
4556and the explicit template instantiation is provided in a shared library (as
4557opposed to simply another translation unit), ``basic_string<char>::data()``
4558won't be found and a link error will ensue. This happens because the compiler
4559assumes that ``basic_string<char>::data()`` is part of the explicit template
4560instantiation declaration, when it really isn't. To tell the compiler that
4561``data()`` is not part of the explicit template instantiation declaration, the
4562``exclude_from_explicit_instantiation`` attribute can be used:
4563
4564  .. code-block:: c++
4565
4566    // in <string>
4567    template <class CharT>
4568    class basic_string {
4569    public:
4570      __attribute__((__visibility__("hidden")))
4571      __attribute__((exclude_from_explicit_instantiation))
4572      const value_type* data() const noexcept { ... }
4573    };
4574
4575    template class basic_string<char>;
4576
4577Now, the compiler won't assume that ``basic_string<char>::data()`` is provided
4578externally despite there being an explicit template instantiation declaration:
4579the compiler will implicitly instantiate ``basic_string<char>::data()`` in the
4580TUs where it is used.
4581
4582This attribute can be used on static and non-static member functions of class
4583templates, static data members of class templates and member classes of class
4584templates.
4585  }];
4586}
4587
4588def DisableTailCallsDocs : Documentation {
4589  let Category = DocCatFunction;
4590  let Content = [{
4591The ``disable_tail_calls`` attribute instructs the backend to not perform tail
4592call optimization inside the marked function.
4593
4594For example:
4595
4596  .. code-block:: c
4597
4598    int callee(int);
4599
4600    int foo(int a) __attribute__((disable_tail_calls)) {
4601      return callee(a); // This call is not tail-call optimized.
4602    }
4603
4604Marking virtual functions as ``disable_tail_calls`` is legal.
4605
4606  .. code-block:: c++
4607
4608    int callee(int);
4609
4610    class Base {
4611    public:
4612      [[clang::disable_tail_calls]] virtual int foo1() {
4613        return callee(); // This call is not tail-call optimized.
4614      }
4615    };
4616
4617    class Derived1 : public Base {
4618    public:
4619      int foo1() override {
4620        return callee(); // This call is tail-call optimized.
4621      }
4622    };
4623
4624  }];
4625}
4626
4627def AnyX86NoCallerSavedRegistersDocs : Documentation {
4628  let Category = DocCatFunction;
4629  let Content = [{
4630Use this attribute to indicate that the specified function has no
4631caller-saved registers. That is, all registers are callee-saved except for
4632registers used for passing parameters to the function or returning parameters
4633from the function.
4634The compiler saves and restores any modified registers that were not used for
4635passing or returning arguments to the function.
4636
4637The user can call functions specified with the 'no_caller_saved_registers'
4638attribute from an interrupt handler without saving and restoring all
4639call-clobbered registers.
4640
4641Note that 'no_caller_saved_registers' attribute is not a calling convention.
4642In fact, it only overrides the decision of which registers should be saved by
4643the caller, but not how the parameters are passed from the caller to the callee.
4644
4645For example:
4646
4647  .. code-block:: c
4648
4649    __attribute__ ((no_caller_saved_registers, fastcall))
4650    void f (int arg1, int arg2) {
4651      ...
4652    }
4653
4654  In this case parameters 'arg1' and 'arg2' will be passed in registers.
4655  In this case, on 32-bit x86 targets, the function 'f' will use ECX and EDX as
4656  register parameters. However, it will not assume any scratch registers and
4657  should save and restore any modified registers except for ECX and EDX.
4658  }];
4659}
4660
4661def X86ForceAlignArgPointerDocs : Documentation {
4662  let Category = DocCatFunction;
4663  let Content = [{
4664Use this attribute to force stack alignment.
4665
4666Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions
4667(like 'movaps') that work with the stack require operands to be 16-byte aligned.
4668This attribute realigns the stack in the function prologue to make sure the
4669stack can be used with SSE instructions.
4670
4671Note that the x86_64 ABI forces 16-byte stack alignment at the call site.
4672Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in
4673rare cases where the caller does not align the stack properly (e.g. flow
4674jumps from i386 arch code).
4675
4676  .. code-block:: c
4677
4678    __attribute__ ((force_align_arg_pointer))
4679    void f () {
4680      ...
4681    }
4682
4683  }];
4684}
4685
4686def AnyX86NoCfCheckDocs : Documentation {
4687  let Category = DocCatFunction;
4688  let Content = [{
4689Jump Oriented Programming attacks rely on tampering with addresses used by
4690indirect call / jmp, e.g. redirect control-flow to non-programmer
4691intended bytes in the binary.
4692X86 Supports Indirect Branch Tracking (IBT) as part of Control-Flow
4693Enforcement Technology (CET). IBT instruments ENDBR instructions used to
4694specify valid targets of indirect call / jmp.
4695The ``nocf_check`` attribute has two roles:
46961. Appertains to a function - do not add ENDBR instruction at the beginning of
4697the function.
46982. Appertains to a function pointer - do not track the target function of this
4699pointer (by adding nocf_check prefix to the indirect-call instruction).
4700}];
4701}
4702
4703def SwiftCallDocs : Documentation {
4704  let Category = DocCatVariable;
4705  let Content = [{
4706The ``swiftcall`` attribute indicates that a function should be called
4707using the Swift calling convention for a function or function pointer.
4708
4709The lowering for the Swift calling convention, as described by the Swift
4710ABI documentation, occurs in multiple phases. The first, "high-level"
4711phase breaks down the formal parameters and results into innately direct
4712and indirect components, adds implicit parameters for the generic
4713signature, and assigns the context and error ABI treatments to parameters
4714where applicable. The second phase breaks down the direct parameters
4715and results from the first phase and assigns them to registers or the
4716stack. The ``swiftcall`` convention only handles this second phase of
4717lowering; the C function type must accurately reflect the results
4718of the first phase, as follows:
4719
4720- Results classified as indirect by high-level lowering should be
4721  represented as parameters with the ``swift_indirect_result`` attribute.
4722
4723- Results classified as direct by high-level lowering should be represented
4724  as follows:
4725
4726  - First, remove any empty direct results.
4727
4728  - If there are no direct results, the C result type should be ``void``.
4729
4730  - If there is one direct result, the C result type should be a type with
4731    the exact layout of that result type.
4732
4733  - If there are a multiple direct results, the C result type should be
4734    a struct type with the exact layout of a tuple of those results.
4735
4736- Parameters classified as indirect by high-level lowering should be
4737  represented as parameters of pointer type.
4738
4739- Parameters classified as direct by high-level lowering should be
4740  omitted if they are empty types; otherwise, they should be represented
4741  as a parameter type with a layout exactly matching the layout of the
4742  Swift parameter type.
4743
4744- The context parameter, if present, should be represented as a trailing
4745  parameter with the ``swift_context`` attribute.
4746
4747- The error result parameter, if present, should be represented as a
4748  trailing parameter (always following a context parameter) with the
4749  ``swift_error_result`` attribute.
4750
4751``swiftcall`` does not support variadic arguments or unprototyped functions.
4752
4753The parameter ABI treatment attributes are aspects of the function type.
4754A function type which applies an ABI treatment attribute to a
4755parameter is a different type from an otherwise-identical function type
4756that does not. A single parameter may not have multiple ABI treatment
4757attributes.
4758
4759Support for this feature is target-dependent, although it should be
4760supported on every target that Swift supports. Query for this support
4761with ``__has_attribute(swiftcall)``. This implies support for the
4762``swift_context``, ``swift_error_result``, and ``swift_indirect_result``
4763attributes.
4764  }];
4765}
4766
4767def SwiftContextDocs : Documentation {
4768  let Category = DocCatVariable;
4769  let Content = [{
4770The ``swift_context`` attribute marks a parameter of a ``swiftcall``
4771or ``swiftasynccall`` function as having the special context-parameter
4772ABI treatment.
4773
4774This treatment generally passes the context value in a special register
4775which is normally callee-preserved.
4776
4777A ``swift_context`` parameter must either be the last parameter or must be
4778followed by a ``swift_error_result`` parameter (which itself must always be
4779the last parameter).
4780
4781A context parameter must have pointer or reference type.
4782  }];
4783}
4784
4785def SwiftAsyncCallDocs : Documentation {
4786  let Category = DocCatVariable;
4787  let Content = [{
4788The ``swiftasynccall`` attribute indicates that a function is
4789compatible with the low-level conventions of Swift async functions,
4790provided it declares the right formal arguments.
4791
4792In most respects, this is similar to the ``swiftcall`` attribute, except for
4793the following:
4794
4795- A parameter may be marked ``swift_async_context``, ``swift_context``
4796  or ``swift_indirect_result`` (with the same restrictions on parameter
4797  ordering as ``swiftcall``) but the parameter attribute
4798  ``swift_error_result`` is not permitted.
4799
4800- A ``swiftasynccall`` function must have return type ``void``.
4801
4802- Within a ``swiftasynccall`` function, a call to a ``swiftasynccall``
4803  function that is the immediate operand of a ``return`` statement is
4804  guaranteed to be performed as a tail call. This syntax is allowed even
4805  in C as an extension (a call to a void-returning function cannot be a
4806  return operand in standard C). If something in the calling function would
4807  semantically be performed after a guaranteed tail call, such as the
4808  non-trivial destruction of a local variable or temporary,
4809  then the program is ill-formed.
4810  }];
4811}
4812
4813def SwiftAsyncContextDocs : Documentation {
4814  let Category = DocCatVariable;
4815  let Content = [{
4816The ``swift_async_context`` attribute marks a parameter of a ``swiftasynccall``
4817function as having the special asynchronous context-parameter ABI treatment.
4818
4819If the function is not ``swiftasynccall``, this attribute only generates
4820extended frame information.
4821
4822A context parameter must have pointer or reference type.
4823  }];
4824}
4825
4826def SwiftErrorResultDocs : Documentation {
4827  let Category = DocCatVariable;
4828  let Content = [{
4829The ``swift_error_result`` attribute marks a parameter of a ``swiftcall``
4830function as having the special error-result ABI treatment.
4831
4832This treatment generally passes the underlying error value in and out of
4833the function through a special register which is normally callee-preserved.
4834This is modeled in C by pretending that the register is addressable memory:
4835
4836- The caller appears to pass the address of a variable of pointer type.
4837  The current value of this variable is copied into the register before
4838  the call; if the call returns normally, the value is copied back into the
4839  variable.
4840
4841- The callee appears to receive the address of a variable. This address
4842  is actually a hidden location in its own stack, initialized with the
4843  value of the register upon entry. When the function returns normally,
4844  the value in that hidden location is written back to the register.
4845
4846A ``swift_error_result`` parameter must be the last parameter, and it must be
4847preceded by a ``swift_context`` parameter.
4848
4849A ``swift_error_result`` parameter must have type ``T**`` or ``T*&`` for some
4850type T. Note that no qualifiers are permitted on the intermediate level.
4851
4852It is undefined behavior if the caller does not pass a pointer or
4853reference to a valid object.
4854
4855The standard convention is that the error value itself (that is, the
4856value stored in the apparent argument) will be null upon function entry,
4857but this is not enforced by the ABI.
4858  }];
4859}
4860
4861def SwiftIndirectResultDocs : Documentation {
4862  let Category = DocCatVariable;
4863  let Content = [{
4864The ``swift_indirect_result`` attribute marks a parameter of a ``swiftcall``
4865or ``swiftasynccall`` function as having the special indirect-result ABI
4866treatment.
4867
4868This treatment gives the parameter the target's normal indirect-result
4869ABI treatment, which may involve passing it differently from an ordinary
4870parameter. However, only the first indirect result will receive this
4871treatment. Furthermore, low-level lowering may decide that a direct result
4872must be returned indirectly; if so, this will take priority over the
4873``swift_indirect_result`` parameters.
4874
4875A ``swift_indirect_result`` parameter must either be the first parameter or
4876follow another ``swift_indirect_result`` parameter.
4877
4878A ``swift_indirect_result`` parameter must have type ``T*`` or ``T&`` for
4879some object type ``T``. If ``T`` is a complete type at the point of
4880definition of a function, it is undefined behavior if the argument
4881value does not point to storage of adequate size and alignment for a
4882value of type ``T``.
4883
4884Making indirect results explicit in the signature allows C functions to
4885directly construct objects into them without relying on language
4886optimizations like C++'s named return value optimization (NRVO).
4887  }];
4888}
4889
4890def SwiftAsyncDocs : Documentation {
4891  let Category = SwiftDocs;
4892  let Heading = "swift_async";
4893  let Content = [{
4894The ``swift_async`` attribute specifies if and how a particular function or
4895Objective-C method is imported into a swift async method. For instance:
4896
4897.. code-block:: objc
4898
4899  @interface MyClass : NSObject
4900  -(void)notActuallyAsync:(int)p1 withCompletionHandler:(void (^)())handler
4901      __attribute__((swift_async(none)));
4902
4903  -(void)actuallyAsync:(int)p1 callThisAsync:(void (^)())fun
4904      __attribute__((swift_async(swift_private, 1)));
4905  @end
4906
4907Here, ``notActuallyAsync:withCompletionHandler`` would have been imported as
4908``async`` (because it's last parameter's selector piece is
4909``withCompletionHandler``) if not for the ``swift_async(none)`` attribute.
4910Conversely, ``actuallyAsync:callThisAsync`` wouldn't have been imported as
4911``async`` if not for the ``swift_async`` attribute because it doesn't match the
4912naming convention.
4913
4914When using ``swift_async`` to enable importing, the first argument to the
4915attribute is either ``swift_private`` or ``not_swift_private`` to indicate
4916whether the function/method is private to the current framework, and the second
4917argument is the index of the completion handler parameter.
4918  }];
4919}
4920
4921def SwiftAsyncErrorDocs : Documentation {
4922  let Category = SwiftDocs;
4923  let Heading = "swift_async_error";
4924  let Content = [{
4925The ``swift_async_error`` attribute specifies how an error state will be
4926represented in a swift async method. It's a bit analogous to the ``swift_error``
4927attribute for the generated async method. The ``swift_async_error`` attribute
4928can indicate a variety of different ways of representing an error.
4929
4930- ``__attribute__((swift_async_error(zero_argument, N)))``, specifies that the
4931  async method is considered to have failed if the Nth argument to the
4932  completion handler is zero.
4933
4934- ``__attribute__((swift_async_error(nonzero_argument, N)))``, specifies that
4935  the async method is considered to have failed if the Nth argument to the
4936  completion handler is non-zero.
4937
4938- ``__attribute__((swift_async_error(nonnull_error)))``, specifies that the
4939  async method is considered to have failed if the ``NSError *`` argument to the
4940  completion handler is non-null.
4941
4942- ``__attribute__((swift_async_error(none)))``, specifies that the async method
4943  cannot fail.
4944
4945
4946For instance:
4947
4948.. code-block:: objc
4949
4950  @interface MyClass : NSObject
4951  -(void)asyncMethod:(void (^)(char, int, float))handler
4952      __attribute__((swift_async(swift_private, 1)))
4953      __attribute__((swift_async_error(zero_argument, 2)));
4954  @end
4955
4956Here, the ``swift_async`` attribute specifies that ``handler`` is the completion
4957handler for this method, and the ``swift_async_error`` attribute specifies that
4958the ``int`` parameter is the one that represents the error.
4959}];
4960}
4961
4962def SuppressDocs : Documentation {
4963  let Category = DocCatStmt;
4964  let Content = [{
4965The ``[[gsl::suppress]]`` attribute suppresses specific
4966clang-tidy diagnostics for rules of the `C++ Core Guidelines`_ in a portable
4967way. The attribute can be attached to declarations, statements, and at
4968namespace scope.
4969
4970.. code-block:: c++
4971
4972  [[gsl::suppress("Rh-public")]]
4973  void f_() {
4974    int *p;
4975    [[gsl::suppress("type")]] {
4976      p = reinterpret_cast<int*>(7);
4977    }
4978  }
4979  namespace N {
4980    [[clang::suppress("type", "bounds")]];
4981    ...
4982  }
4983
4984.. _`C++ Core Guidelines`: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement
4985  }];
4986}
4987
4988def AbiTagsDocs : Documentation {
4989  let Category = DocCatFunction;
4990  let Content = [{
4991The ``abi_tag`` attribute can be applied to a function, variable, class or
4992inline namespace declaration to modify the mangled name of the entity. It gives
4993the ability to distinguish between different versions of the same entity but
4994with different ABI versions supported. For example, a newer version of a class
4995could have a different set of data members and thus have a different size. Using
4996the ``abi_tag`` attribute, it is possible to have different mangled names for
4997a global variable of the class type. Therefore, the old code could keep using
4998the old mangled name and the new code will use the new mangled name with tags.
4999  }];
5000}
5001
5002def BuiltinAliasDocs : Documentation {
5003  let Category = DocCatFunction;
5004  let Heading = "clang::builtin_alias, clang_builtin_alias";
5005  let Content = [{
5006This attribute is used in the implementation of the C intrinsics.
5007It allows the C intrinsic functions to be declared using the names defined
5008in target builtins, and still be recognized as clang builtins equivalent to the
5009underlying name. For example, ``riscv_vector.h`` declares the function ``vadd``
5010with ``__attribute__((clang_builtin_alias(__builtin_rvv_vadd_vv_i8m1)))``.
5011This ensures that both functions are recognized as that clang builtin,
5012and in the latter case, the choice of which builtin to identify the
5013function as can be deferred until after overload resolution.
5014
5015This attribute can only be used to set up the aliases for certain ARM/RISC-V
5016C intrinsic functions; it is intended for use only inside ``arm_*.h`` and
5017``riscv_*.h`` and is not a general mechanism for declaring arbitrary aliases
5018for clang builtin functions.
5019  }];
5020}
5021
5022def PreferredNameDocs : Documentation {
5023  let Category = DocCatDecl;
5024  let Content = [{
5025The ``preferred_name`` attribute can be applied to a class template, and
5026specifies a preferred way of naming a specialization of the template. The
5027preferred name will be used whenever the corresponding template specialization
5028would otherwise be printed in a diagnostic or similar context.
5029
5030The preferred name must be a typedef or type alias declaration that refers to a
5031specialization of the class template (not including any type qualifiers). In
5032general this requires the template to be declared at least twice. For example:
5033
5034.. code-block:: c++
5035
5036  template<typename T> struct basic_string;
5037  using string = basic_string<char>;
5038  using wstring = basic_string<wchar_t>;
5039  template<typename T> struct [[clang::preferred_name(string),
5040                                clang::preferred_name(wstring)]] basic_string {
5041    // ...
5042  };
5043
5044
5045Note that the ``preferred_name`` attribute will be ignored when the compiler
5046writes a C++20 Module interface now. This is due to a compiler issue
5047(https://github.com/llvm/llvm-project/issues/56490) that blocks users to modularize
5048declarations with `preferred_name`. This is intended to be fixed in the future.
5049  }];
5050}
5051
5052def PreserveMostDocs : Documentation {
5053  let Category = DocCatCallingConvs;
5054  let Content = [{
5055On X86-64 and AArch64 targets, this attribute changes the calling convention of
5056a function. The ``preserve_most`` calling convention attempts to make the code
5057in the caller as unintrusive as possible. This convention behaves identically
5058to the ``C`` calling convention on how arguments and return values are passed,
5059but it uses a different set of caller/callee-saved registers. This alleviates
5060the burden of saving and recovering a large register set before and after the
5061call in the caller. If the arguments are passed in callee-saved registers,
5062then they will be preserved by the callee across the call. This doesn't
5063apply for values returned in callee-saved registers.
5064
5065- On X86-64 the callee preserves all general purpose registers, except for
5066  R11. R11 can be used as a scratch register. Floating-point registers
5067  (XMMs/YMMs) are not preserved and need to be saved by the caller.
5068
5069The idea behind this convention is to support calls to runtime functions
5070that have a hot path and a cold path. The hot path is usually a small piece
5071of code that doesn't use many registers. The cold path might need to call out to
5072another function and therefore only needs to preserve the caller-saved
5073registers, which haven't already been saved by the caller. The
5074``preserve_most`` calling convention is very similar to the ``cold`` calling
5075convention in terms of caller/callee-saved registers, but they are used for
5076different types of function calls. ``coldcc`` is for function calls that are
5077rarely executed, whereas ``preserve_most`` function calls are intended to be
5078on the hot path and definitely executed a lot. Furthermore ``preserve_most``
5079doesn't prevent the inliner from inlining the function call.
5080
5081This calling convention will be used by a future version of the Objective-C
5082runtime and should therefore still be considered experimental at this time.
5083Although this convention was created to optimize certain runtime calls to
5084the Objective-C runtime, it is not limited to this runtime and might be used
5085by other runtimes in the future too. The current implementation only
5086supports X86-64 and AArch64, but the intention is to support more architectures
5087in the future.
5088  }];
5089}
5090
5091def PreserveAllDocs : Documentation {
5092  let Category = DocCatCallingConvs;
5093  let Content = [{
5094On X86-64 and AArch64 targets, this attribute changes the calling convention of
5095a function. The ``preserve_all`` calling convention attempts to make the code
5096in the caller even less intrusive than the ``preserve_most`` calling convention.
5097This calling convention also behaves identical to the ``C`` calling convention
5098on how arguments and return values are passed, but it uses a different set of
5099caller/callee-saved registers. This removes the burden of saving and
5100recovering a large register set before and after the call in the caller. If
5101the arguments are passed in callee-saved registers, then they will be
5102preserved by the callee across the call. This doesn't apply for values
5103returned in callee-saved registers.
5104
5105- On X86-64 the callee preserves all general purpose registers, except for
5106  R11. R11 can be used as a scratch register. Furthermore it also preserves
5107  all floating-point registers (XMMs/YMMs).
5108
5109The idea behind this convention is to support calls to runtime functions
5110that don't need to call out to any other functions.
5111
5112This calling convention, like the ``preserve_most`` calling convention, will be
5113used by a future version of the Objective-C runtime and should be considered
5114experimental at this time.
5115  }];
5116}
5117
5118def DeprecatedDocs : Documentation {
5119  let Category = DocCatDecl;
5120  let Content = [{
5121The ``deprecated`` attribute can be applied to a function, a variable, or a
5122type. This is useful when identifying functions, variables, or types that are
5123expected to be removed in a future version of a program.
5124
5125Consider the function declaration for a hypothetical function ``f``:
5126
5127.. code-block:: c++
5128
5129  void f(void) __attribute__((deprecated("message", "replacement")));
5130
5131When spelled as ``__attribute__((deprecated))``, the deprecated attribute can have
5132two optional string arguments. The first one is the message to display when
5133emitting the warning; the second one enables the compiler to provide a Fix-It
5134to replace the deprecated name with a new name. Otherwise, when spelled as
5135``[[gnu::deprecated]]`` or ``[[deprecated]]``, the attribute can have one optional
5136string argument which is the message to display when emitting the warning.
5137  }];
5138}
5139
5140def IFuncDocs : Documentation {
5141  let Category = DocCatFunction;
5142  let Content = [{
5143``__attribute__((ifunc("resolver")))`` is used to mark that the address of a
5144declaration should be resolved at runtime by calling a resolver function.
5145
5146The symbol name of the resolver function is given in quotes. A function with
5147this name (after mangling) must be defined in the current translation unit; it
5148may be ``static``. The resolver function should return a pointer.
5149
5150The ``ifunc`` attribute may only be used on a function declaration. A function
5151declaration with an ``ifunc`` attribute is considered to be a definition of the
5152declared entity. The entity must not have weak linkage; for example, in C++,
5153it cannot be applied to a declaration if a definition at that location would be
5154considered inline.
5155
5156Not all targets support this attribute. ELF target support depends on both the
5157linker and runtime linker, and is available in at least lld 4.0 and later,
5158binutils 2.20.1 and later, glibc v2.11.1 and later, and FreeBSD 9.1 and later.
5159Non-ELF targets currently do not support this attribute.
5160  }];
5161}
5162
5163def LTOVisibilityDocs : Documentation {
5164  let Category = DocCatDecl;
5165  let Content = [{
5166See :doc:`LTOVisibility`.
5167  }];
5168}
5169
5170def RenderScriptKernelAttributeDocs : Documentation {
5171  let Category = DocCatFunction;
5172  let Content = [{
5173``__attribute__((kernel))`` is used to mark a ``kernel`` function in
5174RenderScript.
5175
5176In RenderScript, ``kernel`` functions are used to express data-parallel
5177computations. The RenderScript runtime efficiently parallelizes ``kernel``
5178functions to run on computational resources such as multi-core CPUs and GPUs.
5179See the RenderScript_ documentation for more information.
5180
5181.. _RenderScript: https://developer.android.com/guide/topics/renderscript/compute.html
5182  }];
5183}
5184
5185def XRayDocs : Documentation {
5186  let Category = DocCatFunction;
5187  let Heading = "xray_always_instrument, xray_never_instrument, xray_log_args";
5188  let Content = [{
5189``__attribute__((xray_always_instrument))`` or
5190``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++),
5191methods (in Objective C), and free functions (in C, C++, and Objective C) to be
5192instrumented with XRay. This will cause the function to always have space at
5193the beginning and exit points to allow for runtime patching.
5194
5195Conversely, ``__attribute__((xray_never_instrument))`` or
5196``[[clang::xray_never_instrument]]`` will inhibit the insertion of these
5197instrumentation points.
5198
5199If a function has neither of these attributes, they become subject to the XRay
5200heuristics used to determine whether a function should be instrumented or
5201otherwise.
5202
5203``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is
5204used to preserve N function arguments for the logging function. Currently,
5205only N==1 is supported.
5206  }];
5207}
5208
5209def PatchableFunctionEntryDocs : Documentation {
5210  let Category = DocCatFunction;
5211  let Content = [{
5212``__attribute__((patchable_function_entry(N,M)))`` is used to generate M NOPs
5213before the function entry and N-M NOPs after the function entry. This attribute
5214takes precedence over the command line option ``-fpatchable-function-entry=N,M``.
5215``M`` defaults to 0 if omitted.
5216
5217This attribute is only supported on
5218aarch64/aarch64-be/riscv32/riscv64/i386/x86-64 targets.
5219}];
5220}
5221
5222def TransparentUnionDocs : Documentation {
5223  let Category = DocCatDecl;
5224  let Content = [{
5225This attribute can be applied to a union to change the behavior of calls to
5226functions that have an argument with a transparent union type. The compiler
5227behavior is changed in the following manner:
5228
5229- A value whose type is any member of the transparent union can be passed as an
5230  argument without the need to cast that value.
5231
5232- The argument is passed to the function using the calling convention of the
5233  first member of the transparent union. Consequently, all the members of the
5234  transparent union should have the same calling convention as its first member.
5235
5236Transparent unions are not supported in C++.
5237  }];
5238}
5239
5240def ObjCSubclassingRestrictedDocs : Documentation {
5241  let Category = DocCatDecl;
5242  let Content = [{
5243This attribute can be added to an Objective-C ``@interface`` declaration to
5244ensure that this class cannot be subclassed.
5245  }];
5246}
5247
5248def ObjCNonLazyClassDocs : Documentation {
5249  let Category = DocCatDecl;
5250  let Content = [{
5251This attribute can be added to an Objective-C ``@interface`` or
5252``@implementation`` declaration to add the class to the list of non-lazily
5253initialized classes. A non-lazy class will be initialized eagerly when the
5254Objective-C runtime is loaded. This is required for certain system classes which
5255have instances allocated in non-standard ways, such as the classes for blocks
5256and constant strings. Adding this attribute is essentially equivalent to
5257providing a trivial ``+load`` method but avoids the (fairly small) load-time
5258overheads associated with defining and calling such a method.
5259  }];
5260}
5261
5262def ObjCDirectDocs : Documentation {
5263  let Category = DocCatDecl;
5264  let Content = [{
5265The ``objc_direct`` attribute can be used to mark an Objective-C method as
5266being *direct*. A direct method is treated statically like an ordinary method,
5267but dynamically it behaves more like a C function. This lowers some of the costs
5268associated with the method but also sacrifices some of the ordinary capabilities
5269of Objective-C methods.
5270
5271A message send of a direct method calls the implementation directly, as if it
5272were a C function, rather than using ordinary Objective-C method dispatch. This
5273is substantially faster and potentially allows the implementation to be inlined,
5274but it also means the method cannot be overridden in subclasses or replaced
5275dynamically, as ordinary Objective-C methods can.
5276
5277Furthermore, a direct method is not listed in the class's method lists. This
5278substantially reduces the code-size overhead of the method but also means it
5279cannot be called dynamically using ordinary Objective-C method dispatch at all;
5280in particular, this means that it cannot override a superclass method or satisfy
5281a protocol requirement.
5282
5283Because a direct method cannot be overridden, it is an error to perform
5284a ``super`` message send of one.
5285
5286Although a message send of a direct method causes the method to be called
5287directly as if it were a C function, it still obeys Objective-C semantics in other
5288ways:
5289
5290- If the receiver is ``nil``, the message send does nothing and returns the zero value
5291  for the return type.
5292
5293- A message send of a direct class method will cause the class to be initialized,
5294  including calling the ``+initialize`` method if present.
5295
5296- The implicit ``_cmd`` parameter containing the method's selector is still defined.
5297  In order to minimize code-size costs, the implementation will not emit a reference
5298  to the selector if the parameter is unused within the method.
5299
5300Symbols for direct method implementations are implicitly given hidden
5301visibility, meaning that they can only be called within the same linkage unit.
5302
5303It is an error to do any of the following:
5304
5305- declare a direct method in a protocol,
5306- declare an override of a direct method with a method in a subclass,
5307- declare an override of a non-direct method with a direct method in a subclass,
5308- declare a method with different directness in different class interfaces, or
5309- implement a non-direct method (as declared in any class interface) with a direct method.
5310
5311If any of these rules would be violated if every method defined in an
5312``@implementation`` within a single linkage unit were declared in an
5313appropriate class interface, the program is ill-formed with no diagnostic
5314required. If a violation of this rule is not diagnosed, behavior remains
5315well-defined; this paragraph is simply reserving the right to diagnose such
5316conflicts in the future, not to treat them as undefined behavior.
5317
5318Additionally, Clang will warn about any ``@selector`` expression that
5319names a selector that is only known to be used for direct methods.
5320
5321For the purpose of these rules, a "class interface" includes a class's primary
5322``@interface`` block, its class extensions, its categories, its declared protocols,
5323and all the class interfaces of its superclasses.
5324
5325An Objective-C property can be declared with the ``direct`` property
5326attribute. If a direct property declaration causes an implicit declaration of
5327a getter or setter method (that is, if the given method is not explicitly
5328declared elsewhere), the method is declared to be direct.
5329
5330Some programmers may wish to make many methods direct at once. In order
5331to simplify this, the ``objc_direct_members`` attribute is provided; see its
5332documentation for more information.
5333  }];
5334}
5335
5336def ObjCDirectMembersDocs : Documentation {
5337  let Category = DocCatDecl;
5338  let Content = [{
5339The ``objc_direct_members`` attribute can be placed on an Objective-C
5340``@interface`` or ``@implementation`` to mark that methods declared
5341therein should be considered direct by default. See the documentation
5342for ``objc_direct`` for more information about direct methods.
5343
5344When ``objc_direct_members`` is placed on an ``@interface`` block, every
5345method in the block is considered to be declared as direct. This includes any
5346implicit method declarations introduced by property declarations. If the method
5347redeclares a non-direct method, the declaration is ill-formed, exactly as if the
5348method was annotated with the ``objc_direct`` attribute.
5349
5350When ``objc_direct_members`` is placed on an ``@implementation`` block,
5351methods defined in the block are considered to be declared as direct unless
5352they have been previously declared as non-direct in any interface of the class.
5353This includes the implicit method definitions introduced by synthesized
5354properties, including auto-synthesized properties.
5355  }];
5356}
5357
5358def ObjCNonRuntimeProtocolDocs : Documentation {
5359  let Category = DocCatDecl;
5360  let Content = [{
5361The ``objc_non_runtime_protocol`` attribute can be used to mark that an
5362Objective-C protocol is only used during static type-checking and doesn't need
5363to be represented dynamically. This avoids several small code-size and run-time
5364overheads associated with handling the protocol's metadata. A non-runtime
5365protocol cannot be used as the operand of a ``@protocol`` expression, and
5366dynamic attempts to find it with ``objc_getProtocol`` will fail.
5367
5368If a non-runtime protocol inherits from any ordinary protocols, classes and
5369derived protocols that declare conformance to the non-runtime protocol will
5370dynamically list their conformance to those bare protocols.
5371  }];
5372}
5373
5374def SelectAnyDocs : Documentation {
5375  let Category = DocCatDecl;
5376  let Content = [{
5377This attribute appertains to a global symbol, causing it to have a weak
5378definition (
5379`linkonce <https://llvm.org/docs/LangRef.html#linkage-types>`_
5380), allowing the linker to select any definition.
5381
5382For more information see
5383`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html>`_
5384or `msvc documentation <https://docs.microsoft.com/pl-pl/cpp/cpp/selectany>`_.
5385}]; }
5386
5387def WebAssemblyExportNameDocs : Documentation {
5388  let Category = DocCatFunction;
5389  let Content = [{
5390Clang supports the ``__attribute__((export_name(<name>)))``
5391attribute for the WebAssembly target. This attribute may be attached to a
5392function declaration, where it modifies how the symbol is to be exported
5393from the linked WebAssembly.
5394
5395WebAssembly functions are exported via string name. By default when a symbol
5396is exported, the export name for C/C++ symbols are the same as their C/C++
5397symbol names. This attribute can be used to override the default behavior, and
5398request a specific string name be used instead.
5399  }];
5400}
5401
5402def WebAssemblyImportModuleDocs : Documentation {
5403  let Category = DocCatFunction;
5404  let Content = [{
5405Clang supports the ``__attribute__((import_module(<module_name>)))``
5406attribute for the WebAssembly target. This attribute may be attached to a
5407function declaration, where it modifies how the symbol is to be imported
5408within the WebAssembly linking environment.
5409
5410WebAssembly imports use a two-level namespace scheme, consisting of a module
5411name, which typically identifies a module from which to import, and a field
5412name, which typically identifies a field from that module to import. By
5413default, module names for C/C++ symbols are assigned automatically by the
5414linker. This attribute can be used to override the default behavior, and
5415request a specific module name be used instead.
5416  }];
5417}
5418
5419def WebAssemblyImportNameDocs : Documentation {
5420  let Category = DocCatFunction;
5421  let Content = [{
5422Clang supports the ``__attribute__((import_name(<name>)))``
5423attribute for the WebAssembly target. This attribute may be attached to a
5424function declaration, where it modifies how the symbol is to be imported
5425within the WebAssembly linking environment.
5426
5427WebAssembly imports use a two-level namespace scheme, consisting of a module
5428name, which typically identifies a module from which to import, and a field
5429name, which typically identifies a field from that module to import. By
5430default, field names for C/C++ symbols are the same as their C/C++ symbol
5431names. This attribute can be used to override the default behavior, and
5432request a specific field name be used instead.
5433  }];
5434}
5435
5436def ArtificialDocs : Documentation {
5437  let Category = DocCatFunction;
5438  let Content = [{
5439The ``artificial`` attribute can be applied to an inline function. If such a
5440function is inlined, the attribute indicates that debuggers should associate
5441the resulting instructions with the call site, rather than with the
5442corresponding line within the inlined callee.
5443  }];
5444}
5445
5446def NoDerefDocs : Documentation {
5447  let Category = DocCatType;
5448  let Content = [{
5449The ``noderef`` attribute causes clang to diagnose dereferences of annotated pointer types.
5450This is ideally used with pointers that point to special memory which cannot be read
5451from or written to, but allowing for the pointer to be used in pointer arithmetic.
5452The following are examples of valid expressions where dereferences are diagnosed:
5453
5454.. code-block:: c
5455
5456  int __attribute__((noderef)) *p;
5457  int x = *p;  // warning
5458
5459  int __attribute__((noderef)) **p2;
5460  x = **p2;  // warning
5461
5462  int * __attribute__((noderef)) *p3;
5463  p = *p3;  // warning
5464
5465  struct S {
5466    int a;
5467  };
5468  struct S __attribute__((noderef)) *s;
5469  x = s->a;    // warning
5470  x = (*s).a;  // warning
5471
5472Not all dereferences may diagnose a warning if the value directed by the pointer may not be
5473accessed. The following are examples of valid expressions where may not be diagnosed:
5474
5475.. code-block:: c
5476
5477  int *q;
5478  int __attribute__((noderef)) *p;
5479  q = &*p;
5480  q = *&p;
5481
5482  struct S {
5483    int a;
5484  };
5485  struct S __attribute__((noderef)) *s;
5486  p = &s->a;
5487  p = &(*s).a;
5488
5489``noderef`` is currently only supported for pointers and arrays and not usable
5490for references or Objective-C object pointers.
5491
5492.. code-block: c++
5493
5494  int x = 2;
5495  int __attribute__((noderef)) &y = x;  // warning: 'noderef' can only be used on an array or pointer type
5496
5497.. code-block: objc
5498
5499  id __attribute__((noderef)) obj = [NSObject new]; // warning: 'noderef' can only be used on an array or pointer type
5500}];
5501}
5502
5503def ReinitializesDocs : Documentation {
5504  let Category = DocCatFunction;
5505  let Content = [{
5506The ``reinitializes`` attribute can be applied to a non-static, non-const C++
5507member function to indicate that this member function reinitializes the entire
5508object to a known state, independent of the previous state of the object.
5509
5510This attribute can be interpreted by static analyzers that warn about uses of an
5511object that has been left in an indeterminate state by a move operation. If a
5512member function marked with the ``reinitializes`` attribute is called on a
5513moved-from object, the analyzer can conclude that the object is no longer in an
5514indeterminate state.
5515
5516A typical example where this attribute would be used is on functions that clear
5517a container class:
5518
5519.. code-block:: c++
5520
5521  template <class T>
5522  class Container {
5523  public:
5524    ...
5525    [[clang::reinitializes]] void Clear();
5526    ...
5527  };
5528  }];
5529}
5530
5531def AlwaysDestroyDocs : Documentation {
5532  let Category = DocCatVariable;
5533  let Content = [{
5534The ``always_destroy`` attribute specifies that a variable with static or thread
5535storage duration should have its exit-time destructor run. This attribute is the
5536default unless clang was invoked with -fno-c++-static-destructors.
5537  }];
5538}
5539
5540def NoDestroyDocs : Documentation {
5541  let Category = DocCatVariable;
5542  let Content = [{
5543The ``no_destroy`` attribute specifies that a variable with static or thread
5544storage duration shouldn't have its exit-time destructor run. Annotating every
5545static and thread duration variable with this attribute is equivalent to
5546invoking clang with -fno-c++-static-destructors.
5547
5548If a variable is declared with this attribute, clang doesn't access check or
5549generate the type's destructor. If you have a type that you only want to be
5550annotated with ``no_destroy``, you can therefore declare the destructor private:
5551
5552.. code-block:: c++
5553
5554  struct only_no_destroy {
5555    only_no_destroy();
5556  private:
5557    ~only_no_destroy();
5558  };
5559
5560  [[clang::no_destroy]] only_no_destroy global; // fine!
5561
5562Note that destructors are still required for subobjects of aggregates annotated
5563with this attribute. This is because previously constructed subobjects need to
5564be destroyed if an exception gets thrown before the initialization of the
5565complete object is complete. For instance:
5566
5567.. code-block:: c++
5568
5569  void f() {
5570    try {
5571      [[clang::no_destroy]]
5572      static only_no_destroy array[10]; // error, only_no_destroy has a private destructor.
5573    } catch (...) {
5574      // Handle the error
5575    }
5576  }
5577
5578Here, if the construction of ``array[9]`` fails with an exception, ``array[0..8]``
5579will be destroyed, so the element's destructor needs to be accessible.
5580  }];
5581}
5582
5583def UninitializedDocs : Documentation {
5584  let Category = DocCatVariable;
5585  let Content = [{
5586The command-line parameter ``-ftrivial-auto-var-init=*`` can be used to
5587initialize trivial automatic stack variables. By default, trivial automatic
5588stack variables are uninitialized. This attribute is used to override the
5589command-line parameter, forcing variables to remain uninitialized. It has no
5590semantic meaning in that using uninitialized values is undefined behavior,
5591it rather documents the programmer's intent.
5592  }];
5593}
5594
5595def LoaderUninitializedDocs : Documentation {
5596  let Category = DocCatVariable;
5597  let Content = [{
5598The ``loader_uninitialized`` attribute can be placed on global variables to
5599indicate that the variable does not need to be zero initialized by the loader.
5600On most targets, zero-initialization does not incur any additional cost.
5601For example, most general purpose operating systems deliberately ensure
5602that all memory is properly initialized in order to avoid leaking privileged
5603information from the kernel or other programs. However, some targets
5604do not make this guarantee, and on these targets, avoiding an unnecessary
5605zero-initialization can have a significant impact on load times and/or code
5606size.
5607
5608A declaration with this attribute is a non-tentative definition just as if it
5609provided an initializer. Variables with this attribute are considered to be
5610uninitialized in the same sense as a local variable, and the programs must
5611write to them before reading from them. If the variable's type is a C++ class
5612type with a non-trivial default constructor, or an array thereof, this attribute
5613only suppresses the static zero-initialization of the variable, not the dynamic
5614initialization provided by executing the default constructor.
5615  }];
5616}
5617
5618def CallbackDocs : Documentation {
5619  let Category = DocCatFunction;
5620  let Content = [{
5621The ``callback`` attribute specifies that the annotated function may invoke the
5622specified callback zero or more times. The callback, as well as the passed
5623arguments, are identified by their parameter name or position (starting with
56241!) in the annotated function. The first position in the attribute identifies
5625the callback callee, the following positions declare describe its arguments.
5626The callback callee is required to be callable with the number, and order, of
5627the specified arguments. The index ``0``, or the identifier ``this``, is used to
5628represent an implicit "this" pointer in class methods. If there is no implicit
5629"this" pointer it shall not be referenced. The index '-1', or the name "__",
5630represents an unknown callback callee argument. This can be a value which is
5631not present in the declared parameter list, or one that is, but is potentially
5632inspected, captured, or modified. Parameter names and indices can be mixed in
5633the callback attribute.
5634
5635The ``callback`` attribute, which is directly translated to ``callback``
5636metadata <http://llvm.org/docs/LangRef.html#callback-metadata>, make the
5637connection between the call to the annotated function and the callback callee.
5638This can enable interprocedural optimizations which were otherwise impossible.
5639If a function parameter is mentioned in the ``callback`` attribute, through its
5640position, it is undefined if that parameter is used for anything other than the
5641actual callback. Inspected, captured, or modified parameters shall not be
5642listed in the ``callback`` metadata.
5643
5644Example encodings for the callback performed by ``pthread_create`` are shown
5645below. The explicit attribute annotation indicates that the third parameter
5646(``start_routine``) is called zero or more times by the ``pthread_create`` function,
5647and that the fourth parameter (``arg``) is passed along. Note that the callback
5648behavior of ``pthread_create`` is automatically recognized by Clang. In addition,
5649the declarations of ``__kmpc_fork_teams`` and ``__kmpc_fork_call``, generated for
5650``#pragma omp target teams`` and ``#pragma omp parallel``, respectively, are also
5651automatically recognized as broker functions. Further functions might be added
5652in the future.
5653
5654  .. code-block:: c
5655
5656    __attribute__((callback (start_routine, arg)))
5657    int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
5658                       void *(*start_routine) (void *), void *arg);
5659
5660    __attribute__((callback (3, 4)))
5661    int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
5662                       void *(*start_routine) (void *), void *arg);
5663
5664  }];
5665}
5666
5667def CalledOnceDocs : Documentation {
5668  let Category = DocCatVariable;
5669  let Content = [{
5670The ``called_once`` attribute specifies that the annotated function or method
5671parameter is invoked exactly once on all execution paths. It only applies
5672to parameters with function-like types, i.e. function pointers or blocks. This
5673concept is particularly useful for asynchronous programs.
5674
5675Clang implements a check for ``called_once`` parameters,
5676``-Wcalled-once-parameter``. It is on by default and finds the following
5677violations:
5678
5679* Parameter is not called at all.
5680
5681* Parameter is called more than once.
5682
5683* Parameter is not called on one of the execution paths.
5684
5685In the latter case, Clang pinpoints the path where parameter is not invoked
5686by showing the control-flow statement where the path diverges.
5687
5688.. code-block:: objc
5689
5690  void fooWithCallback(void (^callback)(void) __attribute__((called_once))) {
5691    if (somePredicate()) {
5692      ...
5693      callback();
5694    } esle {
5695      callback(); // OK: callback is called on every path
5696    }
5697  }
5698
5699  void barWithCallback(void (^callback)(void) __attribute__((called_once))) {
5700    if (somePredicate()) {
5701      ...
5702      callback(); // note: previous call is here
5703    }
5704    callback(); // warning: callback is called twice
5705  }
5706
5707  void foobarWithCallback(void (^callback)(void) __attribute__((called_once))) {
5708    if (somePredicate()) {  // warning: callback is not called when condition is false
5709      ...
5710      callback();
5711    }
5712  }
5713
5714This attribute is useful for API developers who want to double-check if they
5715implemented their method correctly.
5716
5717  }];
5718}
5719
5720def GnuInlineDocs : Documentation {
5721  let Category = DocCatFunction;
5722  let Content = [{
5723The ``gnu_inline`` changes the meaning of ``extern inline`` to use GNU inline
5724semantics, meaning:
5725
5726* If any declaration that is declared ``inline`` is not declared ``extern``,
5727  then the ``inline`` keyword is just a hint. In particular, an out-of-line
5728  definition is still emitted for a function with external linkage, even if all
5729  call sites are inlined, unlike in C99 and C++ inline semantics.
5730
5731* If all declarations that are declared ``inline`` are also declared
5732  ``extern``, then the function body is present only for inlining and no
5733  out-of-line version is emitted.
5734
5735Some important consequences: ``static inline`` emits an out-of-line
5736version if needed, a plain ``inline`` definition emits an out-of-line version
5737always, and an ``extern inline`` definition (in a header) followed by a
5738(non-``extern``) ``inline`` declaration in a source file emits an out-of-line
5739version of the function in that source file but provides the function body for
5740inlining to all includers of the header.
5741
5742Either ``__GNUC_GNU_INLINE__`` (GNU inline semantics) or
5743``__GNUC_STDC_INLINE__`` (C99 semantics) will be defined (they are mutually
5744exclusive). If ``__GNUC_STDC_INLINE__`` is defined, then the ``gnu_inline``
5745function attribute can be used to get GNU inline semantics on a per function
5746basis. If ``__GNUC_GNU_INLINE__`` is defined, then the translation unit is
5747already being compiled with GNU inline semantics as the implied default. It is
5748unspecified which macro is defined in a C++ compilation.
5749
5750GNU inline semantics are the default behavior with ``-std=gnu89``,
5751``-std=c89``, ``-std=c94``, or ``-fgnu89-inline``.
5752  }];
5753}
5754
5755def SpeculativeLoadHardeningDocs : Documentation {
5756  let Category = DocCatFunction;
5757  let Content = [{
5758  This attribute can be applied to a function declaration in order to indicate
5759  that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_
5760  should be enabled for the function body. This can also be applied to a method
5761  in Objective C. This attribute will take precedence over the command line flag in
5762  the case where `-mno-speculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified.
5763
5764  Speculative Load Hardening is a best-effort mitigation against
5765  information leak attacks that make use of control flow
5766  miss-speculation - specifically miss-speculation of whether a branch
5767  is taken or not. Typically vulnerabilities enabling such attacks are
5768  classified as "Spectre variant #1". Notably, this does not attempt to
5769  mitigate against miss-speculation of branch target, classified as
5770  "Spectre variant #2" vulnerabilities.
5771
5772  When inlining, the attribute is sticky. Inlining a function that
5773  carries this attribute will cause the caller to gain the
5774  attribute. This is intended to provide a maximally conservative model
5775  where the code in a function annotated with this attribute will always
5776  (even after inlining) end up hardened.
5777  }];
5778}
5779
5780def NoSpeculativeLoadHardeningDocs : Documentation {
5781  let Category = DocCatFunction;
5782  let Content = [{
5783  This attribute can be applied to a function declaration in order to indicate
5784  that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_
5785  is *not* needed for the function body. This can also be applied to a method
5786  in Objective C. This attribute will take precedence over the command line flag in
5787  the case where `-mspeculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified.
5788
5789  Warning: This attribute may not prevent Speculative Load Hardening from being
5790  enabled for a function which inlines a function that has the
5791  'speculative_load_hardening' attribute. This is intended to provide a
5792  maximally conservative model where the code that is marked with the
5793  'speculative_load_hardening' attribute will always (even when inlined)
5794  be hardened. A user of this attribute may want to mark functions called by
5795  a function they do not want to be hardened with the 'noinline' attribute.
5796
5797  For example:
5798
5799  .. code-block:: c
5800
5801    __attribute__((speculative_load_hardening))
5802    int foo(int i) {
5803      return i;
5804    }
5805
5806    // Note: bar() may still have speculative load hardening enabled if
5807    // foo() is inlined into bar(). Mark foo() with __attribute__((noinline))
5808    // to avoid this situation.
5809    __attribute__((no_speculative_load_hardening))
5810    int bar(int i) {
5811      return foo(i);
5812    }
5813  }];
5814}
5815
5816def ObjCExternallyRetainedDocs : Documentation {
5817  let Category = DocCatVariable;
5818  let Content = [{
5819The ``objc_externally_retained`` attribute can be applied to strong local
5820variables, functions, methods, or blocks to opt into
5821`externally-retained semantics
5822<https://clang.llvm.org/docs/AutomaticReferenceCounting.html#externally-retained-variables>`_.
5823
5824When applied to the definition of a function, method, or block, every parameter
5825of the function with implicit strong retainable object pointer type is
5826considered externally-retained, and becomes ``const``. By explicitly annotating
5827a parameter with ``__strong``, you can opt back into the default
5828non-externally-retained behavior for that parameter. For instance,
5829``first_param`` is externally-retained below, but not ``second_param``:
5830
5831.. code-block:: objc
5832
5833  __attribute__((objc_externally_retained))
5834  void f(NSArray *first_param, __strong NSArray *second_param) {
5835    // ...
5836  }
5837
5838Likewise, when applied to a strong local variable, that variable becomes
5839``const`` and is considered externally-retained.
5840
5841When compiled without ``-fobjc-arc``, this attribute is ignored.
5842}]; }
5843
5844def MIGConventionDocs : Documentation {
5845  let Category = DocCatFunction;
5846  let Content = [{
5847  The Mach Interface Generator release-on-success convention dictates
5848functions that follow it to only release arguments passed to them when they
5849return "success" (a ``kern_return_t`` error code that indicates that
5850no errors have occurred). Otherwise the release is performed by the MIG client
5851that called the function. The annotation ``__attribute__((mig_server_routine))``
5852is applied in order to specify which functions are expected to follow the
5853convention. This allows the Static Analyzer to find bugs caused by violations of
5854that convention. The attribute would normally appear on the forward declaration
5855of the actual server routine in the MIG server header, but it may also be
5856added to arbitrary functions that need to follow the same convention - for
5857example, a user can add them to auxiliary functions called by the server routine
5858that have their return value of type ``kern_return_t`` unconditionally returned
5859from the routine. The attribute can be applied to C++ methods, and in this case
5860it will be automatically applied to overrides if the method is virtual. The
5861attribute can also be written using C++11 syntax: ``[[mig::server_routine]]``.
5862}];
5863}
5864
5865def MinSizeDocs : Documentation {
5866  let Category = DocCatFunction;
5867  let Content = [{
5868This function attribute indicates that optimization passes and code generator passes
5869make choices that keep the function code size as small as possible. Optimizations may
5870also sacrifice runtime performance in order to minimize the size of the generated code.
5871  }];
5872}
5873
5874def MSAllocatorDocs : Documentation {
5875  let Category = DocCatFunction;
5876  let Content = [{
5877The ``__declspec(allocator)`` attribute is applied to functions that allocate
5878memory, such as operator new in C++. When CodeView debug information is emitted
5879(enabled by ``clang -gcodeview`` or ``clang-cl /Z7``), Clang will attempt to
5880record the code offset of heap allocation call sites in the debug info. It will
5881also record the type being allocated using some local heuristics. The Visual
5882Studio debugger uses this information to `profile memory usage`_.
5883
5884.. _profile memory usage: https://docs.microsoft.com/en-us/visualstudio/profiling/memory-usage
5885
5886This attribute does not affect optimizations in any way, unlike GCC's
5887``__attribute__((malloc))``.
5888}];
5889}
5890
5891def CFGuardDocs : Documentation {
5892  let Category = DocCatFunction;
5893  let Content = [{
5894Code can indicate CFG checks are not wanted with the ``__declspec(guard(nocf))``
5895attribute. This directs the compiler to not insert any CFG checks for the entire
5896function. This approach is typically used only sparingly in specific situations
5897where the programmer has manually inserted "CFG-equivalent" protection. The
5898programmer knows that they are calling through some read-only function table
5899whose address is obtained through read-only memory references and for which the
5900index is masked to the function table limit. This approach may also be applied
5901to small wrapper functions that are not inlined and that do nothing more than
5902make a call through a function pointer. Since incorrect usage of this directive
5903can compromise the security of CFG, the programmer must be very careful using
5904the directive. Typically, this usage is limited to very small functions that
5905only call one function.
5906
5907`Control Flow Guard documentation <https://docs.microsoft.com/en-us/windows/win32/secbp/pe-metadata>`
5908}];
5909}
5910
5911def CUDADeviceBuiltinSurfaceTypeDocs : Documentation {
5912  let Category = DocCatType;
5913  let Content = [{
5914The ``device_builtin_surface_type`` attribute can be applied to a class
5915template when declaring the surface reference. A surface reference variable
5916could be accessed on the host side and, on the device side, might be translated
5917into an internal surface object, which is established through surface bind and
5918unbind runtime APIs.
5919  }];
5920}
5921
5922def CUDADeviceBuiltinTextureTypeDocs : Documentation {
5923  let Category = DocCatType;
5924  let Content = [{
5925The ``device_builtin_texture_type`` attribute can be applied to a class
5926template when declaring the texture reference. A texture reference variable
5927could be accessed on the host side and, on the device side, might be translated
5928into an internal texture object, which is established through texture bind and
5929unbind runtime APIs.
5930  }];
5931}
5932
5933def HIPManagedAttrDocs : Documentation {
5934  let Category = DocCatDecl;
5935  let Content = [{
5936The ``__managed__`` attribute can be applied to a global variable declaration in HIP.
5937A managed variable is emitted as an undefined global symbol in the device binary and is
5938registered by ``__hipRegisterManagedVariable`` in init functions. The HIP runtime allocates
5939managed memory and uses it to define the symbol when loading the device binary.
5940A managed variable can be accessed in both device and host code.
5941  }];
5942}
5943
5944def LifetimeOwnerDocs : Documentation {
5945  let Category = DocCatDecl;
5946  let Content = [{
5947.. Note:: This attribute is experimental and its effect on analysis is subject to change in
5948  a future version of clang.
5949
5950The attribute ``[[gsl::Owner(T)]]`` applies to structs and classes that own an
5951object of type ``T``:
5952
5953.. code::
5954
5955  class [[gsl::Owner(int)]] IntOwner {
5956  private:
5957    int value;
5958  public:
5959    int *getInt() { return &value; }
5960  };
5961
5962The argument ``T`` is optional and is ignored.
5963This attribute may be used by analysis tools and has no effect on code
5964generation. A ``void`` argument means that the class can own any type.
5965
5966See Pointer_ for an example.
5967}];
5968}
5969
5970def LifetimePointerDocs : Documentation {
5971  let Category = DocCatDecl;
5972  let Content = [{
5973.. Note:: This attribute is experimental and its effect on analysis is subject to change in
5974  a future version of clang.
5975
5976The attribute ``[[gsl::Pointer(T)]]`` applies to structs and classes that behave
5977like pointers to an object of type ``T``:
5978
5979.. code::
5980
5981  class [[gsl::Pointer(int)]] IntPointer {
5982  private:
5983    int *valuePointer;
5984  public:
5985    int *getInt() { return &valuePointer; }
5986  };
5987
5988The argument ``T`` is optional and is ignored.
5989This attribute may be used by analysis tools and has no effect on code
5990generation. A ``void`` argument means that the pointer can point to any type.
5991
5992Example:
5993When constructing an instance of a class annotated like this (a Pointer) from
5994an instance of a class annotated with ``[[gsl::Owner]]`` (an Owner),
5995then the analysis will consider the Pointer to point inside the Owner.
5996When the Owner's lifetime ends, it will consider the Pointer to be dangling.
5997
5998.. code-block:: c++
5999
6000  int f() {
6001    IntPointer P;
6002    if (true) {
6003      IntOwner O(7);
6004      P = IntPointer(O); // P "points into" O
6005    } // P is dangling
6006    return P.get(); // error: Using a dangling Pointer.
6007  }
6008
6009}];
6010}
6011
6012def ArmBuiltinAliasDocs : Documentation {
6013  let Category = DocCatFunction;
6014  let Content = [{
6015This attribute is used in the implementation of the ACLE intrinsics.
6016It allows the intrinsic functions to
6017be declared using the names defined in ACLE, and still be recognized
6018as clang builtins equivalent to the underlying name. For example,
6019``arm_mve.h`` declares the function ``vaddq_u32`` with
6020``__attribute__((__clang_arm_mve_alias(__builtin_arm_mve_vaddq_u32)))``,
6021and similarly, one of the type-overloaded declarations of ``vaddq``
6022will have the same attribute. This ensures that both functions are
6023recognized as that clang builtin, and in the latter case, the choice
6024of which builtin to identify the function as can be deferred until
6025after overload resolution.
6026
6027This attribute can only be used to set up the aliases for certain Arm
6028intrinsic functions; it is intended for use only inside ``arm_*.h``
6029and is not a general mechanism for declaring arbitrary aliases for
6030clang builtin functions.
6031
6032In order to avoid duplicating the attribute definitions for similar
6033purpose for other architecture, there is a general form for the
6034attribute `clang_builtin_alias`.
6035  }];
6036}
6037
6038def NoBuiltinDocs : Documentation {
6039  let Category = DocCatFunction;
6040  let Content = [{
6041The ``__attribute__((no_builtin))`` is similar to the ``-fno-builtin`` flag
6042except it is specific to the body of a function. The attribute may also be
6043applied to a virtual function but has no effect on the behavior of overriding
6044functions in a derived class.
6045
6046It accepts one or more strings corresponding to the specific names of the
6047builtins to disable (e.g. "memcpy", "memset").
6048If the attribute is used without parameters it will disable all buitins at
6049once.
6050
6051.. code-block:: c++
6052
6053  // The compiler is not allowed to add any builtin to foo's body.
6054  void foo(char* data, size_t count) __attribute__((no_builtin)) {
6055    // The compiler is not allowed to convert the loop into
6056    // `__builtin_memset(data, 0xFE, count);`.
6057    for (size_t i = 0; i < count; ++i)
6058      data[i] = 0xFE;
6059  }
6060
6061  // The compiler is not allowed to add the `memcpy` builtin to bar's body.
6062  void bar(char* data, size_t count) __attribute__((no_builtin("memcpy"))) {
6063    // The compiler is allowed to convert the loop into
6064    // `__builtin_memset(data, 0xFE, count);` but cannot generate any
6065    // `__builtin_memcpy`
6066    for (size_t i = 0; i < count; ++i)
6067      data[i] = 0xFE;
6068  }
6069  }];
6070}
6071
6072def UsingIfExistsDocs : Documentation {
6073  let Category = DocCatDecl;
6074  let Content = [{
6075The ``using_if_exists`` attribute applies to a using-declaration. It allows
6076programmers to import a declaration that potentially does not exist, instead
6077deferring any errors to the point of use. For instance:
6078
6079.. code-block:: c++
6080
6081  namespace empty_namespace {};
6082  __attribute__((using_if_exists))
6083  using empty_namespace::does_not_exist; // no error!
6084
6085  does_not_exist x; // error: use of unresolved 'using_if_exists'
6086
6087The C++ spelling of the attribte (`[[clang::using_if_exists]]`) is also
6088supported as a clang extension, since ISO C++ doesn't support attributes in this
6089position. If the entity referred to by the using-declaration is found by name
6090lookup, the attribute has no effect. This attribute is useful for libraries
6091(primarily, libc++) that wish to redeclare a set of declarations in another
6092namespace, when the availability of those declarations is difficult or
6093impossible to detect at compile time with the preprocessor.
6094  }];
6095}
6096
6097def HandleDocs : DocumentationCategory<"Handle Attributes"> {
6098  let Content = [{
6099Handles are a way to identify resources like files, sockets, and processes.
6100They are more opaque than pointers and widely used in system programming. They
6101have similar risks such as never releasing a resource associated with a handle,
6102attempting to use a handle that was already released, or trying to release a
6103handle twice. Using the annotations below it is possible to make the ownership
6104of the handles clear: whose responsibility is to release them. They can also
6105aid static analysis tools to find bugs.
6106  }];
6107}
6108
6109def AcquireHandleDocs : Documentation {
6110  let Category = HandleDocs;
6111  let Content = [{
6112If this annotation is on a function or a function type it is assumed to return
6113a new handle. In case this annotation is on an output parameter,
6114the function is assumed to fill the corresponding argument with a new
6115handle. The attribute requires a string literal argument which used to
6116identify the handle with later uses of ``use_handle`` or
6117``release_handle``.
6118
6119.. code-block:: c++
6120
6121  // Output arguments from Zircon.
6122  zx_status_t zx_socket_create(uint32_t options,
6123                               zx_handle_t __attribute__((acquire_handle("zircon"))) * out0,
6124                               zx_handle_t* out1 [[clang::acquire_handle("zircon")]]);
6125
6126
6127  // Returned handle.
6128  [[clang::acquire_handle("tag")]] int open(const char *path, int oflag, ... );
6129  int open(const char *path, int oflag, ... ) __attribute__((acquire_handle("tag")));
6130  }];
6131}
6132
6133def UseHandleDocs : Documentation {
6134  let Category = HandleDocs;
6135  let Content = [{
6136A function taking a handle by value might close the handle. If a function
6137parameter is annotated with ``use_handle(tag)`` it is assumed to not to change
6138the state of the handle. It is also assumed to require an open handle to work with.
6139The attribute requires a string literal argument to identify the handle being used.
6140
6141.. code-block:: c++
6142
6143  zx_status_t zx_port_wait(zx_handle_t handle [[clang::use_handle("zircon")]],
6144                           zx_time_t deadline,
6145                           zx_port_packet_t* packet);
6146  }];
6147}
6148
6149def ReleaseHandleDocs : Documentation {
6150  let Category = HandleDocs;
6151  let Content = [{
6152If a function parameter is annotated with ``release_handle(tag)`` it is assumed to
6153close the handle. It is also assumed to require an open handle to work with. The
6154attribute requires a string literal argument to identify the handle being released.
6155
6156.. code-block:: c++
6157
6158  zx_status_t zx_handle_close(zx_handle_t handle [[clang::release_handle("tag")]]);
6159  }];
6160}
6161
6162def DiagnoseAsBuiltinDocs : Documentation {
6163  let Category = DocCatFunction;
6164  let Content = [{
6165The ``diagnose_as_builtin`` attribute indicates that Fortify diagnostics are to
6166be applied to the declared function as if it were the function specified by the
6167attribute. The builtin function whose diagnostics are to be mimicked should be
6168given. In addition, the order in which arguments should be applied must also
6169be given.
6170
6171For example, the attribute can be used as follows.
6172
6173.. code-block:: c
6174
6175  __attribute__((diagnose_as_builtin(__builtin_memset, 3, 2, 1)))
6176  void *mymemset(int n, int c, void *s) {
6177    // ...
6178  }
6179
6180This indicates that calls to ``mymemset`` should be diagnosed as if they were
6181calls to ``__builtin_memset``. The arguments ``3, 2, 1`` indicate by index the
6182order in which arguments of ``mymemset`` should be applied to
6183``__builtin_memset``. The third argument should be applied first, then the
6184second, and then the first. Thus (when Fortify warnings are enabled) the call
6185``mymemset(n, c, s)`` will diagnose overflows as if it were the call
6186``__builtin_memset(s, c, n)``.
6187
6188For variadic functions, the variadic arguments must come in the same order as
6189they would to the builtin function, after all normal arguments. For instance,
6190to diagnose a new function as if it were `sscanf`, we can use the attribute as
6191follows.
6192
6193.. code-block:: c
6194
6195  __attribute__((diagnose_as_builtin(sscanf, 1, 2)))
6196  int mysscanf(const char *str, const char *format, ...)  {
6197    // ...
6198  }
6199
6200Then the call `mysscanf("abc def", "%4s %4s", buf1, buf2)` will be diagnosed as
6201if it were the call `sscanf("abc def", "%4s %4s", buf1, buf2)`.
6202
6203This attribute cannot be applied to non-static member functions.
6204}];
6205}
6206
6207def ArmSveVectorBitsDocs : Documentation {
6208  let Category = DocCatType;
6209  let Content = [{
6210The ``arm_sve_vector_bits(N)`` attribute is defined by the Arm C Language
6211Extensions (ACLE) for SVE. It is used to define fixed-length (VLST) variants of
6212sizeless types (VLAT).
6213
6214For example:
6215
6216.. code-block:: c
6217
6218  #include <arm_sve.h>
6219
6220  #if __ARM_FEATURE_SVE_BITS==512
6221  typedef svint32_t fixed_svint32_t __attribute__((arm_sve_vector_bits(512)));
6222  #endif
6223
6224Creates a type ``fixed_svint32_t`` that is a fixed-length variant of
6225``svint32_t`` that contains exactly 512-bits. Unlike ``svint32_t``, this type
6226can be used in globals, structs, unions, and arrays, all of which are
6227unsupported for sizeless types.
6228
6229The attribute can be attached to a single SVE vector (such as ``svint32_t``) or
6230to the SVE predicate type ``svbool_t``, this excludes tuple types such as
6231``svint32x4_t``. The behavior of the attribute is undefined unless
6232``N==__ARM_FEATURE_SVE_BITS``, the implementation defined feature macro that is
6233enabled under the ``-msve-vector-bits`` flag.
6234
6235For more information See `Arm C Language Extensions for SVE
6236<https://developer.arm.com/documentation/100987/latest>`_ for more information.
6237}];
6238}
6239
6240def ArmMveStrictPolymorphismDocs : Documentation {
6241    let Category = DocCatType;
6242    let Content = [{
6243This attribute is used in the implementation of the ACLE intrinsics for the Arm
6244MVE instruction set. It is used to define the vector types used by the MVE
6245intrinsics.
6246
6247Its effect is to modify the behavior of a vector type with respect to function
6248overloading. If a candidate function for overload resolution has a parameter
6249type with this attribute, then the selection of that candidate function will be
6250disallowed if the actual argument can only be converted via a lax vector
6251conversion. The aim is to prevent spurious ambiguity in ARM MVE polymorphic
6252intrinsics.
6253
6254.. code-block:: c++
6255
6256  void overloaded(uint16x8_t vector, uint16_t scalar);
6257  void overloaded(int32x4_t vector, int32_t scalar);
6258  uint16x8_t myVector;
6259  uint16_t myScalar;
6260
6261  // myScalar is promoted to int32_t as a side effect of the addition,
6262  // so if lax vector conversions are considered for myVector, then
6263  // the two overloads are equally good (one argument conversion
6264  // each). But if the vector has the __clang_arm_mve_strict_polymorphism
6265  // attribute, only the uint16x8_t,uint16_t overload will match.
6266  overloaded(myVector, myScalar + 1);
6267
6268However, this attribute does not prohibit lax vector conversions in contexts
6269other than overloading.
6270
6271.. code-block:: c++
6272
6273  uint16x8_t function();
6274
6275  // This is still permitted with lax vector conversion enabled, even
6276  // if the vector types have __clang_arm_mve_strict_polymorphism
6277  int32x4_t result = function();
6278
6279    }];
6280}
6281
6282def ArmCmseNSCallDocs : Documentation {
6283  let Category = DocCatType;
6284  let Content = [{
6285This attribute declares a non-secure function type. When compiling for secure
6286state, a call to such a function would switch from secure to non-secure state.
6287All non-secure function calls must happen only through a function pointer, and
6288a non-secure function type should only be used as a base type of a pointer.
6289See `ARMv8-M Security Extensions: Requirements on Development
6290Tools - Engineering Specification Documentation
6291<https://developer.arm.com/docs/ecm0359818/latest/>`_ for more information.
6292  }];
6293}
6294
6295def ArmCmseNSEntryDocs : Documentation {
6296  let Category = DocCatFunction;
6297  let Content = [{
6298This attribute declares a function that can be called from non-secure state, or
6299from secure state. Entering from and returning to non-secure state would switch
6300to and from secure state, respectively, and prevent flow of information
6301to non-secure state, except via return values. See `ARMv8-M Security Extensions:
6302Requirements on Development Tools - Engineering Specification Documentation
6303<https://developer.arm.com/docs/ecm0359818/latest/>`_ for more information.
6304  }];
6305}
6306
6307def AlwaysInlineDocs : Documentation {
6308  let Category = DocCatFunction;
6309  let Content = [{
6310Inlining heuristics are disabled and inlining is always attempted regardless of
6311optimization level.
6312
6313``[[clang::always_inline]]`` spelling can be used as a statement attribute; other
6314spellings of the attribute are not supported on statements. If a statement is
6315marked ``[[clang::always_inline]]`` and contains calls, the compiler attempts
6316to inline those calls.
6317
6318.. code-block:: c
6319
6320  int example(void) {
6321    int i;
6322    [[clang::always_inline]] foo(); // attempts to inline foo
6323    [[clang::always_inline]] i = bar(); // attempts to inline bar
6324    [[clang::always_inline]] return f(42, baz(bar())); // attempts to inline everything
6325  }
6326
6327A declaration statement, which is a statement, is not a statement that can have an
6328attribute associated with it (the attribute applies to the declaration, not the
6329statement in that case). So this use case will not work:
6330
6331.. code-block:: c
6332
6333  int example(void) {
6334    [[clang::always_inline]] int i = bar();
6335    return i;
6336  }
6337
6338This attribute does not guarantee that inline substitution actually occurs.
6339
6340<ins>Note: applying this attribute to a coroutine at the `-O0` optimization level
6341has no effect; other optimization levels may only partially inline and result in a
6342diagnostic.</ins>
6343
6344See also `the Microsoft Docs on Inline Functions`_, `the GCC Common Function
6345Attribute docs`_, and `the GCC Inline docs`_.
6346
6347.. _the Microsoft Docs on Inline Functions: https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp
6348.. _the GCC Common Function Attribute docs: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html
6349.. _the GCC Inline docs: https://gcc.gnu.org/onlinedocs/gcc/Inline.html
6350
6351}];
6352  let Heading = "always_inline, __force_inline";
6353}
6354
6355def EnforceTCBDocs : Documentation {
6356  let Category = DocCatFunction;
6357  let Content = [{
6358  The ``enforce_tcb`` attribute can be placed on functions to enforce that a
6359  trusted compute base (TCB) does not call out of the TCB. This generates a
6360  warning every time a function not marked with an ``enforce_tcb`` attribute is
6361  called from a function with the ``enforce_tcb`` attribute. A function may be a
6362  part of multiple TCBs. Invocations through function pointers are currently
6363  not checked. Builtins are considered to a part of every TCB.
6364
6365  - ``enforce_tcb(Name)`` indicates that this function is a part of the TCB named ``Name``
6366  }];
6367}
6368
6369def EnforceTCBLeafDocs : Documentation {
6370  let Category = DocCatFunction;
6371  let Content = [{
6372  The ``enforce_tcb_leaf`` attribute satisfies the requirement enforced by
6373  ``enforce_tcb`` for the marked function to be in the named TCB but does not
6374  continue to check the functions called from within the leaf function.
6375
6376  - ``enforce_tcb_leaf(Name)`` indicates that this function is a part of the TCB named ``Name``
6377  }];
6378}
6379
6380def ErrorAttrDocs : Documentation {
6381  let Category = DocCatFunction;
6382  let Heading = "error, warning";
6383  let Content = [{
6384The ``error`` and ``warning`` function attributes can be used to specify a
6385custom diagnostic to be emitted when a call to such a function is not
6386eliminated via optimizations. This can be used to create compile time
6387assertions that depend on optimizations, while providing diagnostics
6388pointing to precise locations of the call site in the source.
6389
6390.. code-block:: c++
6391
6392  __attribute__((warning("oh no"))) void dontcall();
6393  void foo() {
6394    if (someCompileTimeAssertionThatsTrue)
6395      dontcall(); // Warning
6396
6397    dontcall(); // Warning
6398
6399    if (someCompileTimeAssertionThatsFalse)
6400      dontcall(); // No Warning
6401    sizeof(dontcall()); // No Warning
6402  }
6403  }];
6404}
6405
6406def ZeroCallUsedRegsDocs : Documentation {
6407  let Category = DocCatFunction;
6408  let Content = [{
6409This attribute, when attached to a function, causes the compiler to zero a
6410subset of all call-used registers before the function returns. It's used to
6411increase program security by either mitigating `Return-Oriented Programming`_
6412(ROP) attacks or preventing information leakage through registers.
6413
6414The term "call-used" means registers which are not guaranteed to be preserved
6415unchanged for the caller by the current calling convention. This could also be
6416described as "caller-saved" or "not callee-saved".
6417
6418The `choice` parameters gives the programmer flexibility to choose the subset
6419of the call-used registers to be zeroed:
6420
6421- ``skip`` doesn't zero any call-used registers. This choice overrides any
6422  command-line arguments.
6423- ``used`` only zeros call-used registers used in the function. By ``used``, we
6424  mean a register whose contents have been set or referenced in the function.
6425- ``used-gpr`` only zeros call-used GPR registers used in the funciton.
6426- ``used-arg`` only zeros call-used registers used to pass arguments to the
6427  function.
6428- ``used-gpr-arg`` only zeros call-used GPR registers used to pass arguments to
6429  the function.
6430- ``all`` zeros all call-used registers.
6431- ``all-gpr`` zeros all call-used GPR registers.
6432- ``all-arg`` zeros all call-used registers used to pass arguments to the
6433  function.
6434- ``all-gpr-arg`` zeros all call-used GPR registers used to pass arguments to
6435  the function.
6436
6437The default for the attribute is contolled by the ``-fzero-call-used-regs``
6438flag.
6439
6440.. _Return-Oriented Programming: https://en.wikipedia.org/wiki/Return-oriented_programming
6441  }];
6442}
6443
6444def NumThreadsDocs : Documentation {
6445  let Category = DocCatFunction;
6446  let Content = [{
6447The ``numthreads`` attribute applies to HLSL shaders where explcit thread counts
6448are required. The ``X``, ``Y``, and ``Z`` values provided to the attribute
6449dictate the thread id. Total number of threads executed is ``X * Y * Z``.
6450
6451The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-numthreads
6452  }];
6453}
6454
6455def HLSLSV_ShaderTypeAttrDocs : Documentation {
6456  let Category = DocCatFunction;
6457  let Content = [{
6458The ``shader`` type attribute applies to HLSL shader entry functions to
6459identify the shader type for the entry function.
6460The syntax is:
6461
6462.. code-block:: text
6463
6464  ``[shader(string-literal)]``
6465
6466where the string literal is one of: "pixel", "vertex", "geometry", "hull",
6467"domain", "compute", "raygeneration", "intersection", "anyhit", "closesthit",
6468"miss", "callable", "mesh", "amplification". Normally the shader type is set
6469by shader target with the ``-T`` option like ``-Tps_6_1``. When compiling to a
6470library target like ``lib_6_3``, the shader type attribute can help the
6471compiler to identify the shader type. It is mostly used by Raytracing shaders
6472where shaders must be compiled into a library and linked at runtime.
6473  }];
6474}
6475
6476def ClangRandomizeLayoutDocs : Documentation {
6477  let Category = DocCatDecl;
6478  let Heading = "randomize_layout, no_randomize_layout";
6479  let Content = [{
6480The attribute ``randomize_layout``, when attached to a C structure, selects it
6481for structure layout field randomization; a compile-time hardening technique. A
6482"seed" value, is specified via the ``-frandomize-layout-seed=`` command line flag.
6483For example:
6484
6485.. code-block:: bash
6486
6487  SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
6488  make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
6489
6490You can also supply the seed in a file with ``-frandomize-layout-seed-file=``.
6491For example:
6492
6493.. code-block:: bash
6494
6495  od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
6496  make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
6497
6498The randomization is deterministic based for a given seed, so the entire
6499program should be compiled with the same seed, but keep the seed safe
6500otherwise.
6501
6502The attribute ``no_randomize_layout``, when attached to a C structure,
6503instructs the compiler that this structure should not have its field layout
6504randomized.
6505  }];
6506}
6507
6508def HLSLSV_GroupIndexDocs : Documentation {
6509  let Category = DocCatFunction;
6510  let Content = [{
6511The ``SV_GroupIndex`` semantic, when applied to an input parameter, specifies a
6512data binding to map the group index to the specified parameter. This attribute
6513is only supported in compute shaders.
6514
6515The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-groupindex
6516  }];
6517}
6518
6519def AnnotateTypeDocs : Documentation {
6520  let Category = DocCatType;
6521  let Heading = "annotate_type";
6522  let Content = [{
6523This attribute is used to add annotations to types, typically for use by static
6524analysis tools that are not integrated into the core Clang compiler (e.g.,
6525Clang-Tidy checks or out-of-tree Clang-based tools). It is a counterpart to the
6526`annotate` attribute, which serves the same purpose, but for declarations.
6527
6528The attribute takes a mandatory string literal argument specifying the
6529annotation category and an arbitrary number of optional arguments that provide
6530additional information specific to the annotation category. The optional
6531arguments must be constant expressions of arbitrary type.
6532
6533For example:
6534
6535.. code-block:: c++
6536
6537  int* [[clang::annotate("category1", "foo", 1)]] f(int[[clang::annotate("category2")]] *);
6538
6539The attribute does not have any effect on the semantics of the type system,
6540neither type checking rules, nor runtime semantics. In particular:
6541
6542- ``std::is_same<T, T [[clang::annotate_type("foo")]]>`` is true for all types
6543  ``T``.
6544
6545- It is not permissible for overloaded functions or template specializations
6546  to differ merely by an ``annotate_type`` attribute.
6547
6548- The presence of an ``annotate_type`` attribute will not affect name
6549  mangling.
6550  }];
6551}
6552
6553def WeakDocs : Documentation {
6554  let Category = DocCatDecl;
6555  let Content = [{
6556
6557In supported output formats the ``weak`` attribute can be used to
6558specify that a variable or function should be emitted as a symbol with
6559``weak`` (if a definition) or ``extern_weak`` (if a declaration of an
6560external symbol) `linkage
6561<https://llvm.org/docs/LangRef.html#linkage-types>`_.
6562
6563If there is a non-weak definition of the symbol the linker will select
6564that over the weak. They must have same type and alignment (variables
6565must also have the same size), but may have a different value.
6566
6567If there are multiple weak definitions of same symbol, but no non-weak
6568definition, they should have same type, size, alignment and value, the
6569linker will select one of them (see also selectany_ attribute).
6570
6571If the ``weak`` attribute is applied to a ``const`` qualified variable
6572definition that variable is no longer consider a compiletime constant
6573as its value can change during linking (or dynamic linking). This
6574means that it can e.g no longer be part of an initializer expression.
6575
6576.. code-block:: c
6577
6578  const int ANSWER __attribute__ ((weak)) = 42;
6579
6580  /* This function may be replaced link-time */
6581  __attribute__ ((weak)) void debug_log(const char *msg)
6582  {
6583      fprintf(stderr, "DEBUG: %s\n", msg);
6584  }
6585
6586  int main(int argc, const char **argv)
6587  {
6588      debug_log ("Starting up...");
6589
6590      /* This may print something else than "6 * 7 = 42",
6591         if there is a non-weak definition of "ANSWER" in
6592	 an object linked in */
6593      printf("6 * 7 = %d\n", ANSWER);
6594
6595      return 0;
6596   }
6597
6598If an external declaration is marked weak and that symbol does not
6599exist during linking (possibly dynamic) the address of the symbol will
6600evaluate to NULL.
6601
6602.. code-block:: c
6603
6604  void may_not_exist(void) __attribute__ ((weak));
6605
6606  int main(int argc, const char **argv)
6607  {
6608      if (may_not_exist) {
6609          may_not_exist();
6610      } else {
6611          printf("Function did not exist\n");
6612      }
6613      return 0;
6614  }
6615  }];
6616}
6617
6618def FunctionReturnThunksDocs : Documentation {
6619  let Category = DocCatFunction;
6620  let Content = [{
6621The attribute ``function_return`` can replace return instructions with jumps to
6622target-specific symbols. This attribute supports 2 possible values,
6623corresponding to the values supported by the ``-mfunction-return=`` command
6624line flag:
6625
6626* ``__attribute__((function_return("keep")))`` to disable related transforms.
6627  This is useful for undoing global setting from ``-mfunction-return=`` locally
6628  for individual functions.
6629* ``__attribute__((function_return("thunk-extern")))`` to replace returns with
6630  jumps, while NOT emitting the thunk.
6631
6632The values ``thunk`` and ``thunk-inline`` from GCC are not supported.
6633
6634The symbol used for ``thunk-extern`` is target specific:
6635* X86: ``__x86_return_thunk``
6636
6637As such, this function attribute is currently only supported on X86 targets.
6638  }];
6639}
6640