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