1/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\
2|* *|
3|* Clang attribute documentation *|
4|* *|
5|* Automatically generated file, do not edit! *|
6|* From: Attr.td *|
7|* *|
8\*===----------------------------------------------------------------------===*/
9
10
11static const char AttrDoc_AArch64SVEPcs[] = R"reST(On AArch64 targets, this attribute changes the calling convention of a
12function to preserve additional Scalable Vector registers and Scalable
13Predicate registers relative to the default calling convention used for
14AArch64.
15
16This means it is more efficient to call such functions from code that performs
17extensive scalable vector and scalable predicate calculations, because fewer
18live SVE registers need to be saved. This property makes it well-suited for SVE
19math library functions, which are typically leaf functions that require a small
20number of registers.
21
22However, using this attribute also means that it is more expensive to call
23a function that adheres to the default calling convention from within such
24a function. Therefore, it is recommended that this attribute is only used
25for leaf functions.
26
27For more information, see the documentation for `aarch64_sve_pcs` in the
28ARM C Language Extension (ACLE) documentation.
29
30.. _`aarch64_sve_pcs`: https://github.com/ARM-software/acle/blob/main/main/acle.md#scalable-vector-extension-procedure-call-standard-attribute)reST";
31
32static const char AttrDoc_AArch64VectorPcs[] = R"reST(On AArch64 targets, this attribute changes the calling convention of a
33function to preserve additional floating-point and Advanced SIMD registers
34relative to the default calling convention used for AArch64.
35
36This means it is more efficient to call such functions from code that performs
37extensive floating-point and vector calculations, because fewer live SIMD and FP
38registers need to be saved. This property makes it well-suited for e.g.
39floating-point or vector math library functions, which are typically leaf
40functions that require a small number of registers.
41
42However, using this attribute also means that it is more expensive to call
43a function that adheres to the default calling convention from within such
44a function. Therefore, it is recommended that this attribute is only used
45for leaf functions.
46
47For more information, see the documentation for `aarch64_vector_pcs`_ on
48the Arm Developer website.
49
50.. _`aarch64_vector_pcs`: https://developer.arm.com/products/software-development-tools/hpc/arm-compiler-for-hpc/vector-function-abi)reST";
51
52static const char AttrDoc_AMDGPUFlatWorkGroupSize[] = R"reST(The flat work-group size is the number of work-items in the work-group size
53specified when the kernel is dispatched. It is the product of the sizes of the
54x, y, and z dimension of the work-group.
55
56Clang supports the
57``__attribute__((amdgpu_flat_work_group_size(<min>, <max>)))`` attribute for the
58AMDGPU target. This attribute may be attached to a kernel function definition
59and is an optimization hint.
60
61``<min>`` parameter specifies the minimum flat work-group size, and ``<max>``
62parameter specifies the maximum flat work-group size (must be greater than
63``<min>``) to which all dispatches of the kernel will conform. Passing ``0, 0``
64as ``<min>, <max>`` implies the default behavior (``128, 256``).
65
66If specified, the AMDGPU target backend might be able to produce better machine
67code for barriers and perform scratch promotion by estimating available group
68segment size.
69
70An error will be given if:
71 - Specified values violate subtarget specifications;
72 - Specified values are not compatible with values provided through other
73 attributes.)reST";
74
75static const char AttrDoc_AMDGPUMaxNumWorkGroups[] = R"reST(This attribute specifies the max number of work groups when the kernel
76is dispatched.
77
78Clang supports the
79``__attribute__((amdgpu_max_num_work_groups(<x>, <y>, <z>)))`` or
80``[[clang::amdgpu_max_num_work_groups(<x>, <y>, <z>)]]`` attribute for the
81AMDGPU target. This attribute may be attached to HIP or OpenCL kernel function
82definitions and is an optimization hint.
83
84The ``<x>`` parameter specifies the maximum number of work groups in the x dimension.
85Similarly ``<y>`` and ``<z>`` are for the y and z dimensions respectively.
86Each of the three values must be greater than 0 when provided. The ``<x>`` parameter
87is required, while ``<y>`` and ``<z>`` are optional with default value of 1.
88
89If specified, the AMDGPU target backend might be able to produce better machine
90code.
91
92An error will be given if:
93 - Specified values violate subtarget specifications;
94 - Specified values are not compatible with values provided through other
95 attributes.)reST";
96
97static const char AttrDoc_AMDGPUNumSGPR[] = R"reST(Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and
98``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU
99target. These attributes may be attached to a kernel function definition and are
100an optimization hint.
101
102If these attributes are specified, then the AMDGPU target backend will attempt
103to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
104number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
105allocation requirements or constraints of the subtarget. Passing ``0`` as
106``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits).
107
108These attributes can be used to test the AMDGPU target backend. It is
109recommended that the ``amdgpu_waves_per_eu`` attribute be used to control
110resources such as SGPRs and VGPRs since it is aware of the limits for different
111subtargets.
112
113An error will be given if:
114 - Specified values violate subtarget specifications;
115 - Specified values are not compatible with values provided through other
116 attributes;
117 - The AMDGPU target backend is unable to create machine code that can meet the
118 request.)reST";
119
120static const char AttrDoc_AMDGPUNumVGPR[] = R"reST(Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and
121``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU
122target. These attributes may be attached to a kernel function definition and are
123an optimization hint.
124
125If these attributes are specified, then the AMDGPU target backend will attempt
126to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
127number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
128allocation requirements or constraints of the subtarget. Passing ``0`` as
129``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits).
130
131These attributes can be used to test the AMDGPU target backend. It is
132recommended that the ``amdgpu_waves_per_eu`` attribute be used to control
133resources such as SGPRs and VGPRs since it is aware of the limits for different
134subtargets.
135
136An error will be given if:
137 - Specified values violate subtarget specifications;
138 - Specified values are not compatible with values provided through other
139 attributes;
140 - The AMDGPU target backend is unable to create machine code that can meet the
141 request.)reST";
142
143static const char AttrDoc_AMDGPUWavesPerEU[] = R"reST(A compute unit (CU) is responsible for executing the wavefronts of a work-group.
144It is composed of one or more execution units (EU), which are responsible for
145executing the wavefronts. An EU can have enough resources to maintain the state
146of more than one executing wavefront. This allows an EU to hide latency by
147switching between wavefronts in a similar way to symmetric multithreading on a
148CPU. In order to allow the state for multiple wavefronts to fit on an EU, the
149resources used by a single wavefront have to be limited. For example, the number
150of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding,
151but can result in having to spill some register state to memory.
152
153Clang supports the ``__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))``
154attribute for the AMDGPU target. This attribute may be attached to a kernel
155function definition and is an optimization hint.
156
157``<min>`` parameter specifies the requested minimum number of waves per EU, and
158*optional* ``<max>`` parameter specifies the requested maximum number of waves
159per EU (must be greater than ``<min>`` if specified). If ``<max>`` is omitted,
160then there is no restriction on the maximum number of waves per EU other than
161the one dictated by the hardware for which the kernel is compiled. Passing
162``0, 0`` as ``<min>, <max>`` implies the default behavior (no limits).
163
164If specified, this attribute allows an advanced developer to tune the number of
165wavefronts that are capable of fitting within the resources of an EU. The AMDGPU
166target backend can use this information to limit resources, such as number of
167SGPRs, number of VGPRs, size of available group and private memory segments, in
168such a way that guarantees that at least ``<min>`` wavefronts and at most
169``<max>`` wavefronts are able to fit within the resources of an EU. Requesting
170more wavefronts can hide memory latency but limits available registers which
171can result in spilling. Requesting fewer wavefronts can help reduce cache
172thrashing, but can reduce memory latency hiding.
173
174This attribute controls the machine code generated by the AMDGPU target backend
175to ensure it is capable of meeting the requested values. However, when the
176kernel is executed, there may be other reasons that prevent meeting the request,
177for example, there may be wavefronts from other kernels executing on the EU.
178
179An error will be given if:
180 - Specified values violate subtarget specifications;
181 - Specified values are not compatible with values provided through other
182 attributes;
183
184The AMDGPU target backend will emit a warning whenever it is unable to
185create machine code that meets the request.)reST";
186
187static const char AttrDoc_ARMInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on
188ARM targets. This attribute may be attached to a function definition and
189instructs the backend to generate appropriate function entry/exit code so that
190it can be used directly as an interrupt service routine.
191
192The parameter passed to the interrupt attribute is optional, but if
193provided it must be a string literal with one of the following values: "IRQ",
194"FIQ", "SWI", "ABORT", "UNDEF".
195
196The semantics are as follows:
197
198- If the function is AAPCS, Clang instructs the backend to realign the stack to
199 8 bytes on entry. This is a general requirement of the AAPCS at public
200 interfaces, but may not hold when an exception is taken. Doing this allows
201 other AAPCS functions to be called.
202- If the CPU is M-class this is all that needs to be done since the architecture
203 itself is designed in such a way that functions obeying the normal AAPCS ABI
204 constraints are valid exception handlers.
205- If the CPU is not M-class, the prologue and epilogue are modified to save all
206 non-banked registers that are used, so that upon return the user-mode state
207 will not be corrupted. Note that to avoid unnecessary overhead, only
208 general-purpose (integer) registers are saved in this way. If VFP operations
209 are needed, that state must be saved manually.
210
211 Specifically, interrupt kinds other than "FIQ" will save all core registers
212 except "lr" and "sp". "FIQ" interrupts will save r0-r7.
213- If the CPU is not M-class, the return instruction is changed to one of the
214 canonical sequences permitted by the architecture for exception return. Where
215 possible the function itself will make the necessary "lr" adjustments so that
216 the "preferred return address" is selected.
217
218 Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
219 handler, where the offset from "lr" to the preferred return address depends on
220 the execution state of the code which generated the exception. In this case
221 a sequence equivalent to "movs pc, lr" will be used.)reST";
222
223static const char AttrDoc_ARMInterruptSaveFP[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt_save_fp("TYPE")))``
224on ARM targets. This attribute behaves the same way as the ARM interrupt
225attribute, except the general purpose floating point registers are also saved,
226along with FPEXC and FPSCR. Note, even on M-class CPUs, where the floating
227point context can be automatically saved depending on the FPCCR, the general
228purpose floating point registers will be saved.)reST";
229
230static const char AttrDoc_ARMSaveFP[] = R"reST()reST";
231
232static const char AttrDoc_AVRInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt))`` attribute on
233AVR targets. This attribute may be attached to a function definition and instructs
234the backend to generate appropriate function entry/exit code so that it can be used
235directly as an interrupt service routine.
236
237On the AVR, the hardware globally disables interrupts when an interrupt is executed.
238The first instruction of an interrupt handler declared with this attribute is a SEI
239instruction to re-enable interrupts. See also the signal attribute that
240does not insert a SEI instruction.)reST";
241
242static const char AttrDoc_AVRSignal[] = R"reST(Clang supports the GNU style ``__attribute__((signal))`` attribute on
243AVR targets. This attribute may be attached to a function definition and instructs
244the backend to generate appropriate function entry/exit code so that it can be used
245directly as an interrupt service routine.
246
247Interrupt handler functions defined with the signal attribute do not re-enable interrupts.)reST";
248
249static const char AttrDoc_AbiTag[] = R"reST(The ``abi_tag`` attribute can be applied to a function, variable, class or
250inline namespace declaration to modify the mangled name of the entity. It gives
251the ability to distinguish between different versions of the same entity but
252with different ABI versions supported. For example, a newer version of a class
253could have a different set of data members and thus have a different size. Using
254the ``abi_tag`` attribute, it is possible to have different mangled names for
255a global variable of the class type. Therefore, the old code could keep using
256the old mangled name and the new code will use the new mangled name with tags.)reST";
257
258static const char AttrDoc_AcquireCapability[] = R"reST(Marks a function as acquiring a capability.)reST";
259
260static const char AttrDoc_AcquireHandle[] = R"reST(If this annotation is on a function or a function type it is assumed to return
261a new handle. In case this annotation is on an output parameter,
262the function is assumed to fill the corresponding argument with a new
263handle. The attribute requires a string literal argument which used to
264identify the handle with later uses of ``use_handle`` or
265``release_handle``.
266
267.. code-block:: c++
268
269 // Output arguments from Zircon.
270 zx_status_t zx_socket_create(uint32_t options,
271 zx_handle_t __attribute__((acquire_handle("zircon"))) * out0,
272 zx_handle_t* out1 [[clang::acquire_handle("zircon")]]);
273
274
275 // Returned handle.
276 [[clang::acquire_handle("tag")]] int open(const char *path, int oflag, ... );
277 int open(const char *path, int oflag, ... ) __attribute__((acquire_handle("tag")));)reST";
278
279static const char AttrDoc_AcquiredAfter[] = R"reST(No documentation.)reST";
280
281static const char AttrDoc_AcquiredBefore[] = R"reST(No documentation.)reST";
282
283static const char AttrDoc_AddressSpace[] = R"reST(.. Note:: This attribute is mainly intended to be used by target headers
284 provided by the toolchain. End users should prefer the documented, named
285 address space annotations for their platform, such as the
286 `OpenCL address spaces`_, ``__global__``, ``__local__``, or something else.
287
288The ``address_space`` attribute functions as a type qualifier that allows the
289programmer to specify the address space for a pointer or reference type.
290Qualified pointer types are considered distinct types for the purposes of
291overload resolution. The attribute takes a single, non-negative integer
292constant expression identifying the address space. For example:
293
294.. code-block:: c
295
296 int * __attribute__((address_space(1))) ptr;
297
298 void foo(__attribute__((address_space(2))) float *buf);
299
300
301Only one address space qualifier may be applied to a given pointer or reference
302type. Where address spaces are allowed (e.g., variables, parameters, return
303types) and what values are valid depends on the target and language mode.
304
305The meaning of each value is defined by the target; multiple address spaces are
306used in environments such as OpenCL, CUDA, HIP, and other GPU programming
307models to distinguish global, local, constant, and private memory. See for
308example the address spaces defined in the `NVPTX Usage Guide`_ and the
309`AMDGPU Usage Guide`_.
310
311.. _`NVPTX Usage Guide`: https://llvm.org/docs/NVPTXUsage.html#address-spaces
312.. _`AMDGPU Usage Guide`: https://llvm.org/docs/AMDGPUUsage.html#address-spaces
313
314Address spaces may partially overlap or be entirely distinct. The compiler may
315reject attempts to convert between distinct, incompatible address spaces.
316Pointer width may vary between different address spaces, so some explicit casts
317may truncate.
318
319For more information, refer to `ISO TR18037`_, which covers embedded C language
320extensions. Section 5 covers named address spaces.
321
322.. _`ISO TR18037`: https://standards.iso.org/ittf/PubliclyAvailableStandards/c051126_ISO_IEC_TR_18037_2008.zip)reST";
323
324static const char AttrDoc_Alias[] = R"reST(No documentation.)reST";
325
326static const char AttrDoc_AlignMac68k[] = R"reST()reST";
327
328static const char AttrDoc_AlignNatural[] = R"reST()reST";
329
330static const char AttrDoc_AlignValue[] = R"reST(The align_value attribute can be added to the typedef of a pointer type or the
331declaration of a variable of pointer or reference type. It specifies that the
332pointer will point to, or the reference will bind to, only objects with at
333least the provided alignment. This alignment value must be some positive power
334of 2.
335
336 .. code-block:: c
337
338 typedef double * aligned_double_ptr __attribute__((align_value(64)));
339 void foo(double & x __attribute__((align_value(128))),
340 aligned_double_ptr y) { ... }
341
342If the pointer value does not have the specified alignment at runtime, the
343behavior of the program is undefined.)reST";
344
345static const char AttrDoc_Aligned[] = R"reST(No documentation.)reST";
346
347static const char AttrDoc_AllocAlign[] = R"reST(Use ``__attribute__((alloc_align(<alignment>))`` on a function
348declaration to specify that the return value of the function (which must be a
349pointer type) is at least as aligned as the value of the indicated parameter. The
350parameter is given by its index in the list of formal parameters; the first
351parameter has index 1 unless the function is a C++ non-static member function,
352in which case the first parameter has index 2 to account for the implicit ``this``
353parameter.
354
355.. code-block:: c++
356
357 // The returned pointer has the alignment specified by the first parameter.
358 void *a(size_t align) __attribute__((alloc_align(1)));
359
360 // The returned pointer has the alignment specified by the second parameter.
361 void *b(void *v, size_t align) __attribute__((alloc_align(2)));
362
363 // The returned pointer has the alignment specified by the second visible
364 // parameter, however it must be adjusted for the implicit 'this' parameter.
365 void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3)));
366
367Note that this attribute merely informs the compiler that a function always
368returns a sufficiently aligned pointer. It does not cause the compiler to
369emit code to enforce that alignment. The behavior is undefined if the returned
370pointer is not sufficiently aligned.)reST";
371
372static const char AttrDoc_AllocSize[] = R"reST(The ``alloc_size`` attribute can be placed on functions that return pointers in
373order to hint to the compiler how many bytes of memory will be available at the
374returned pointer. ``alloc_size`` takes one or two arguments.
375
376- ``alloc_size(N)`` implies that argument number N equals the number of
377 available bytes at the returned pointer.
378- ``alloc_size(N, M)`` implies that the product of argument number N and
379 argument number M equals the number of available bytes at the returned
380 pointer.
381
382Argument numbers are 1-based.
383
384An example of how to use ``alloc_size``
385
386.. code-block:: c
387
388 void *my_malloc(int a) __attribute__((alloc_size(1)));
389 void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2)));
390
391 int main() {
392 void *const p = my_malloc(100);
393 assert(__builtin_object_size(p, 0) == 100);
394 void *const a = my_calloc(20, 5);
395 assert(__builtin_object_size(a, 0) == 100);
396 }
397
398When ``-Walloc-size`` is enabled, this attribute allows the compiler to
399diagnose cases when the allocated memory is insufficient for the size of the
400type the returned pointer is cast to.
401
402.. code-block:: c
403
404 void *my_malloc(int a) __attribute__((alloc_size(1)));
405 void consumer_func(int *);
406
407 int main() {
408 int *ptr = my_malloc(sizeof(int)); // no warning
409 int *w = my_malloc(1); // warning: allocation of insufficient size '1' for type 'int' with size '4'
410 consumer_func(my_malloc(1)); // warning: allocation of insufficient size '1' for type 'int' with size '4'
411 }
412
413.. Note:: This attribute works differently in clang than it does in GCC.
414 Specifically, clang will only trace ``const`` pointers (as above); we give up
415 on pointers that are not marked as ``const``. In the vast majority of cases,
416 this is unimportant, because LLVM has support for the ``alloc_size``
417 attribute. However, this may cause mildly unintuitive behavior when used with
418 other attributes, such as ``enable_if``.)reST";
419
420static const char AttrDoc_Allocating[] = R"reST(Declares that a function potentially allocates heap memory, and prevents any potential inference
421of ``nonallocating`` by the compiler.)reST";
422
423static const char AttrDoc_AlwaysDestroy[] = R"reST(The ``always_destroy`` attribute specifies that a variable with static or thread
424storage duration should have its exit-time destructor run. This attribute is the
425default unless clang was invoked with -fno-c++-static-destructors.
426
427If a variable is explicitly declared with this attribute, Clang will silence
428otherwise applicable ``-Wexit-time-destructors`` warnings.)reST";
429
430static const char AttrDoc_AlwaysInline[] = R"reST(Inlining heuristics are disabled and inlining is always attempted regardless of
431optimization level.
432
433``[[clang::always_inline]]`` spelling can be used as a statement attribute; other
434spellings of the attribute are not supported on statements. If a statement is
435marked ``[[clang::always_inline]]`` and contains calls, the compiler attempts
436to inline those calls.
437
438.. code-block:: c
439
440 int example(void) {
441 int i;
442 [[clang::always_inline]] foo(); // attempts to inline foo
443 [[clang::always_inline]] i = bar(); // attempts to inline bar
444 [[clang::always_inline]] return f(42, baz(bar())); // attempts to inline everything
445 }
446
447A declaration statement, which is a statement, is not a statement that can have an
448attribute associated with it (the attribute applies to the declaration, not the
449statement in that case). So this use case will not work:
450
451.. code-block:: c
452
453 int example(void) {
454 [[clang::always_inline]] int i = bar();
455 return i;
456 }
457
458This attribute does not guarantee that inline substitution actually occurs.
459
460<ins>Note: applying this attribute to a coroutine at the `-O0` optimization level
461has no effect; other optimization levels may only partially inline and result in a
462diagnostic.</ins>
463
464See also `the Microsoft Docs on Inline Functions`_, `the GCC Common Function
465Attribute docs`_, and `the GCC Inline docs`_.
466
467.. _the Microsoft Docs on Inline Functions: https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp
468.. _the GCC Common Function Attribute docs: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html
469.. _the GCC Inline docs: https://gcc.gnu.org/onlinedocs/gcc/Inline.html)reST";
470
471static const char AttrDoc_AnalyzerNoReturn[] = R"reST(No documentation.)reST";
472
473static const char AttrDoc_Annotate[] = R"reST(No documentation.)reST";
474
475static const char AttrDoc_AnnotateType[] = R"reST(This attribute is used to add annotations to types, typically for use by static
476analysis tools that are not integrated into the core Clang compiler (e.g.,
477Clang-Tidy checks or out-of-tree Clang-based tools). It is a counterpart to the
478`annotate` attribute, which serves the same purpose, but for declarations.
479
480The attribute takes a mandatory string literal argument specifying the
481annotation category and an arbitrary number of optional arguments that provide
482additional information specific to the annotation category. The optional
483arguments must be constant expressions of arbitrary type.
484
485For example:
486
487.. code-block:: c++
488
489 int* [[clang::annotate_type("category1", "foo", 1)]] f(int[[clang::annotate_type("category2")]] *);
490
491The attribute does not have any effect on the semantics of the type system,
492neither type checking rules, nor runtime semantics. In particular:
493
494- ``std::is_same<T, T [[clang::annotate_type("foo")]]>`` is true for all types
495 ``T``.
496
497- It is not permissible for overloaded functions or template specializations
498 to differ merely by an ``annotate_type`` attribute.
499
500- The presence of an ``annotate_type`` attribute will not affect name
501 mangling.)reST";
502
503static const char AttrDoc_AnyX86Interrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt))`` attribute on X86
504targets. This attribute may be attached to a function definition and instructs
505the backend to generate appropriate function entry/exit code so that it can be
506used directly as an interrupt service routine.
507
508Interrupt handlers have access to the stack frame pushed onto the stack by the processor,
509and return using the ``IRET`` instruction. All registers in an interrupt handler are callee-saved.
510Exception handlers also have access to the error code pushed onto the stack by the processor,
511when applicable.
512
513An interrupt handler must take the following arguments:
514
515 .. code-block:: c
516
517 __attribute__ ((interrupt))
518 void f (struct stack_frame *frame) {
519 ...
520 }
521
522 Where ``struct stack_frame`` is a suitable struct matching the stack frame pushed by the
523 processor.
524
525An exception handler must take the following arguments:
526
527 .. code-block:: c
528
529 __attribute__ ((interrupt))
530 void g (struct stack_frame *frame, unsigned long code) {
531 ...
532 }
533
534 On 32-bit targets, the ``code`` argument should be of type ``unsigned int``.
535
536Exception handlers should only be used when an error code is pushed by the processor.
537Using the incorrect handler type will crash the system.
538
539Interrupt and exception handlers cannot be called by other functions and must have return type ``void``.
540
541Interrupt and exception handlers should only call functions with the 'no_caller_saved_registers'
542attribute, or should be compiled with the '-mgeneral-regs-only' flag to avoid saving unused
543non-GPR registers.)reST";
544
545static const char AttrDoc_AnyX86NoCallerSavedRegisters[] = R"reST(Use this attribute to indicate that the specified function has no
546caller-saved registers. That is, all registers are callee-saved except for
547registers used for passing parameters to the function or returning parameters
548from the function.
549The compiler saves and restores any modified registers that were not used for
550passing or returning arguments to the function.
551
552The user can call functions specified with the 'no_caller_saved_registers'
553attribute from an interrupt handler without saving and restoring all
554call-clobbered registers.
555
556Functions specified with the 'no_caller_saved_registers' attribute should only
557call other functions with the 'no_caller_saved_registers' attribute, or should be
558compiled with the '-mgeneral-regs-only' flag to avoid saving unused non-GPR registers.
559
560Note that 'no_caller_saved_registers' attribute is not a calling convention.
561In fact, it only overrides the decision of which registers should be saved by
562the caller, but not how the parameters are passed from the caller to the callee.
563
564For example:
565
566 .. code-block:: c
567
568 __attribute__ ((no_caller_saved_registers, fastcall))
569 void f (int arg1, int arg2) {
570 ...
571 }
572
573 In this case parameters 'arg1' and 'arg2' will be passed in registers.
574 In this case, on 32-bit x86 targets, the function 'f' will use ECX and EDX as
575 register parameters. However, it will not assume any scratch registers and
576 should save and restore any modified registers except for ECX and EDX.)reST";
577
578static const char AttrDoc_AnyX86NoCfCheck[] = R"reST(Jump Oriented Programming attacks rely on tampering with addresses used by
579indirect call / jmp, e.g. redirect control-flow to non-programmer
580intended bytes in the binary.
581X86 Supports Indirect Branch Tracking (IBT) as part of Control-Flow
582Enforcement Technology (CET). IBT instruments ENDBR instructions used to
583specify valid targets of indirect call / jmp.
584The ``nocf_check`` attribute has two roles:
5851. Appertains to a function - do not add ENDBR instruction at the beginning of
586the function.
5872. Appertains to a function pointer - do not track the target function of this
588pointer (by adding nocf_check prefix to the indirect-call instruction).)reST";
589
590static const char AttrDoc_ArcWeakrefUnavailable[] = R"reST(No documentation.)reST";
591
592static const char AttrDoc_ArgumentWithTypeTag[] = R"reST(Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
593type_tag_idx)))`` on a function declaration to specify that the function
594accepts a type tag that determines the type of some other argument.
595
596This attribute is primarily useful for checking arguments of variadic functions
597(``pointer_with_type_tag`` can be used in most non-variadic cases).
598
599In the attribute prototype above:
600 * ``arg_kind`` is an identifier that should be used when annotating all
601 applicable type tags.
602 * ``arg_idx`` provides the position of a function argument. The expected type of
603 this function argument will be determined by the function argument specified
604 by ``type_tag_idx``. In the code example below, "3" means that the type of the
605 function's third argument will be determined by ``type_tag_idx``.
606 * ``type_tag_idx`` provides the position of a function argument. This function
607 argument will be a type tag. The type tag will determine the expected type of
608 the argument specified by ``arg_idx``. In the code example below, "2" means
609 that the type tag associated with the function's second argument should agree
610 with the type of the argument specified by ``arg_idx``.
611
612For example:
613
614.. code-block:: c++
615
616 int fcntl(int fd, int cmd, ...)
617 __attribute__(( argument_with_type_tag(fcntl,3,2) ));
618 // The function's second argument will be a type tag; this type tag will
619 // determine the expected type of the function's third argument.)reST";
620
621static const char AttrDoc_ArmAgnostic[] = R"reST(The ``__arm_agnostic`` keyword applies to prototyped function types and
622affects the function's calling convention for a given state S. This
623attribute allows the user to describe a function that preserves S, without
624requiring the function to share S with its callers and without making
625the assumption that S exists.
626
627If a function has the ``__arm_agnostic(S)`` attribute and calls a function
628without this attribute, then the function's object code will contain code
629to preserve state S. Otherwise, the function's object code will be the same
630as if it did not have the attribute.
631
632The attribute takes string arguments to describe state S. The supported
633states are:
634
635* ``"sme_za_state"`` for state enabled by PSTATE.ZA, such as ZA and ZT0.
636
637The attribute ``__arm_agnostic("sme_za_state")`` cannot be used in conjunction
638with ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` or
639``__arm_preserves(S)`` where state S describes state enabled by PSTATE.ZA,
640such as "za" or "zt0".)reST";
641
642static const char AttrDoc_ArmBuiltinAlias[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics.
643It allows the intrinsic functions to
644be declared using the names defined in ACLE, and still be recognized
645as clang builtins equivalent to the underlying name. For example,
646``arm_mve.h`` declares the function ``vaddq_u32`` with
647``__attribute__((__clang_arm_mve_alias(__builtin_arm_mve_vaddq_u32)))``,
648and similarly, one of the type-overloaded declarations of ``vaddq``
649will have the same attribute. This ensures that both functions are
650recognized as that clang builtin, and in the latter case, the choice
651of which builtin to identify the function as can be deferred until
652after overload resolution.
653
654This attribute can only be used to set up the aliases for certain Arm
655intrinsic functions; it is intended for use only inside ``arm_*.h``
656and is not a general mechanism for declaring arbitrary aliases for
657clang builtin functions.
658
659In order to avoid duplicating the attribute definitions for similar
660purpose for other architecture, there is a general form for the
661attribute `clang_builtin_alias`.)reST";
662
663static const char AttrDoc_ArmIn[] = R"reST(The ``__arm_in`` keyword applies to prototyped function types and specifies
664that the function shares a given state S with its caller. For ``__arm_in``, the
665function takes the state S as input and returns with the state S unchanged.
666
667The attribute takes string arguments to instruct the compiler which state
668is shared. The supported states for S are:
669
670* ``"za"`` for Matrix Storage (requires SME)
671
672The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
673``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
674
675static const char AttrDoc_ArmInOut[] = R"reST(The ``__arm_inout`` keyword applies to prototyped function types and specifies
676that the function shares a given state S with its caller. For ``__arm_inout``,
677the function takes the state S as input and returns new state for S.
678
679The attribute takes string arguments to instruct the compiler which state
680is shared. The supported states for S are:
681
682* ``"za"`` for Matrix Storage (requires SME)
683
684The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
685``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
686
687static const char AttrDoc_ArmLocallyStreaming[] = R"reST(The ``__arm_locally_streaming`` keyword applies to function declarations
688and specifies that all the statements in the function are executed in
689streaming mode. This means that:
690
691* the function requires that the target processor implements the Scalable Matrix
692 Extension (SME).
693
694* the program automatically puts the machine into streaming mode before
695 executing the statements and automatically restores the previous mode
696 afterwards.
697
698Clang manages PSTATE.SM automatically; it is not the source code's
699responsibility to do this. For example, Clang will emit code to enable
700streaming mode at the start of the function, and disable streaming mode
701at the end of the function.)reST";
702
703static const char AttrDoc_ArmMveStrictPolymorphism[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics for the Arm
704MVE instruction set. It is used to define the vector types used by the MVE
705intrinsics.
706
707Its effect is to modify the behavior of a vector type with respect to function
708overloading. If a candidate function for overload resolution has a parameter
709type with this attribute, then the selection of that candidate function will be
710disallowed if the actual argument can only be converted via a lax vector
711conversion. The aim is to prevent spurious ambiguity in ARM MVE polymorphic
712intrinsics.
713
714.. code-block:: c++
715
716 void overloaded(uint16x8_t vector, uint16_t scalar);
717 void overloaded(int32x4_t vector, int32_t scalar);
718 uint16x8_t myVector;
719 uint16_t myScalar;
720
721 // myScalar is promoted to int32_t as a side effect of the addition,
722 // so if lax vector conversions are considered for myVector, then
723 // the two overloads are equally good (one argument conversion
724 // each). But if the vector has the __clang_arm_mve_strict_polymorphism
725 // attribute, only the uint16x8_t,uint16_t overload will match.
726 overloaded(myVector, myScalar + 1);
727
728However, this attribute does not prohibit lax vector conversions in contexts
729other than overloading.
730
731.. code-block:: c++
732
733 uint16x8_t function();
734
735 // This is still permitted with lax vector conversion enabled, even
736 // if the vector types have __clang_arm_mve_strict_polymorphism
737 int32x4_t result = function();)reST";
738
739static const char AttrDoc_ArmNew[] = R"reST(The ``__arm_new`` keyword applies to function declarations and specifies
740that the function will create a new scope for state S.
741
742The attribute takes string arguments to instruct the compiler for which state
743to create new scope. The supported states for S are:
744
745* ``"za"`` for Matrix Storage (requires SME)
746
747For state ``"za"``, this means that:
748
749* the function requires that the target processor implements the Scalable Matrix
750 Extension (SME).
751
752* the function will commit any lazily saved ZA data.
753
754* the function will create a new ZA context and enable PSTATE.ZA.
755
756* the function will disable PSTATE.ZA (by setting it to 0) before returning.
757
758For ``__arm_new("za")`` functions Clang will set up the ZA context automatically
759on entry to the function and disable it before returning. For example, if ZA is
760in a dormant state Clang will generate the code to commit a lazy-save and set up
761a new ZA state before executing user code.)reST";
762
763static const char AttrDoc_ArmOut[] = R"reST(The ``__arm_out`` keyword applies to prototyped function types and specifies
764that the function shares a given state S with its caller. For ``__arm_out``,
765the function ignores the incoming state for S and returns new state for S.
766
767The attribute takes string arguments to instruct the compiler which state
768is shared. The supported states for S are:
769
770* ``"za"`` for Matrix Storage (requires SME)
771
772The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
773``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
774
775static const char AttrDoc_ArmPreserves[] = R"reST(The ``__arm_preserves`` keyword applies to prototyped function types and
776specifies that the function does not read a given state S and returns
777with state S unchanged.
778
779The attribute takes string arguments to instruct the compiler which state
780is shared. The supported states for S are:
781
782* ``"za"`` for Matrix Storage (requires SME)
783
784The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
785``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
786
787static const char AttrDoc_ArmStreaming[] = R"reST(The ``__arm_streaming`` keyword applies to prototyped function types and specifies
788that the function has a "streaming interface". This means that:
789
790* the function requires that the processor implements the Scalable Matrix
791 Extension (SME).
792
793* the function must be entered in streaming mode (that is, with PSTATE.SM
794 set to 1)
795
796* the function must return in streaming mode
797
798Clang manages PSTATE.SM automatically; it is not the source code's
799responsibility to do this. For example, if a non-streaming
800function calls an ``__arm_streaming`` function, Clang generates code
801that switches into streaming mode before calling the function and
802switches back to non-streaming mode on return.)reST";
803
804static const char AttrDoc_ArmStreamingCompatible[] = R"reST(The ``__arm_streaming_compatible`` keyword applies to prototyped function types and
805specifies that the function has a "streaming compatible interface". This
806means that:
807
808* the function may be entered in either non-streaming mode (PSTATE.SM=0) or
809 in streaming mode (PSTATE.SM=1).
810
811* the function must return in the same mode as it was entered.
812
813* the code executed in the function is compatible with either mode.
814
815Clang manages PSTATE.SM automatically; it is not the source code's
816responsibility to do this. Clang will ensure that the generated code in
817streaming-compatible functions is valid in either mode (PSTATE.SM=0 or
818PSTATE.SM=1). For example, if an ``__arm_streaming_compatible`` function calls a
819non-streaming function, Clang generates code to temporarily switch out of streaming
820mode before calling the function and switch back to streaming-mode on return if
821``PSTATE.SM`` is ``1`` on entry of the caller. If ``PSTATE.SM`` is ``0`` on
822entry to the ``__arm_streaming_compatible`` function, the call will be executed
823without changing modes.)reST";
824
825static const char AttrDoc_Artificial[] = R"reST(The ``artificial`` attribute can be applied to an inline function. If such a
826function is inlined, the attribute indicates that debuggers should associate
827the resulting instructions with the call site, rather than with the
828corresponding line within the inlined callee.)reST";
829
830static const char AttrDoc_AsmLabel[] = R"reST(This attribute can be used on a function or variable to specify its symbol name.
831
832On some targets, all C symbols are prefixed by default with a single character,
833typically ``_``. This was done historically to distinguish them from symbols
834used by other languages. (This prefix is also added to the standard Itanium
835C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true
836symbol name for a C++ variable declared as ``int cppvar;`` would be
837``__Z6cppvar``; note the two underscores.) This prefix is *not* added to the
838symbol names specified by the ``__asm`` attribute; programmers wishing to match
839a C symbol name must compensate for this.
840
841For example, consider the following C code:
842
843.. code-block:: c
844
845 int var1 __asm("altvar") = 1; // "altvar" in symbol table.
846 int var2 = 1; // "_var2" in symbol table.
847
848 void func1(void) __asm("altfunc");
849 void func1(void) {} // "altfunc" in symbol table.
850 void func2(void) {} // "_func2" in symbol table.
851
852Clang's implementation of this attribute is compatible with GCC's, `documented here <https://gcc.gnu.org/onlinedocs/gcc/Asm-Labels.html>`_.
853
854While it is possible to use this attribute to name a special symbol used
855internally by the compiler, such as an LLVM intrinsic, this is neither
856recommended nor supported and may cause the compiler to crash or miscompile.
857Users who wish to gain access to intrinsic behavior are strongly encouraged to
858request new builtin functions.)reST";
859
860static const char AttrDoc_AssertCapability[] = R"reST(Marks a function that dynamically tests whether a capability is held, and halts
861the program if it is not held.)reST";
862
863static const char AttrDoc_AssumeAligned[] = R"reST(Use ``__attribute__((assume_aligned(<alignment>[,<offset>]))`` on a function
864declaration to specify that the return value of the function (which must be a
865pointer type) has the specified offset, in bytes, from an address with the
866specified alignment. The offset is taken to be zero if omitted.
867
868.. code-block:: c++
869
870 // The returned pointer value has 32-byte alignment.
871 void *a() __attribute__((assume_aligned (32)));
872
873 // The returned pointer value is 4 bytes greater than an address having
874 // 32-byte alignment.
875 void *b() __attribute__((assume_aligned (32, 4)));
876
877Note that this attribute provides information to the compiler regarding a
878condition that the code already ensures is true. It does not cause the compiler
879to enforce the provided alignment assumption.)reST";
880
881static const char AttrDoc_Atomic[] = R"reST(The ``atomic`` attribute can be applied to *compound statements* to override or
882further specify the default atomic code-generation behavior, especially on
883targets such as AMDGPU. You can annotate compound statements with options
884to modify how atomic instructions inside that statement are emitted at the IR
885level.
886
887For details, see the documentation for `@atomic
888<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-controlling-atomic-code-generation>`_)reST";
889
890static const char AttrDoc_Availability[] = R"reST(The ``availability`` attribute can be placed on declarations to describe the
891lifecycle of that declaration relative to operating system versions. Consider
892the function declaration for a hypothetical function ``f``:
893
894.. code-block:: c++
895
896 void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
897
898The availability attribute states that ``f`` was introduced in macOS 10.4,
899deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information
900is used by Clang to determine when it is safe to use ``f``: for example, if
901Clang is instructed to compile code for macOS 10.5, a call to ``f()``
902succeeds. If Clang is instructed to compile code for macOS 10.6, the call
903succeeds but Clang emits a warning specifying that the function is deprecated.
904Finally, if Clang is instructed to compile code for macOS 10.7, the call
905fails because ``f()`` is no longer available.
906
907Clang is instructed to compile code for a minimum deployment version using
908the ``-target`` or ``-mtargetos`` command line arguments. For example,
909macOS 10.7 would be specified as ``-target x86_64-apple-macos10.7`` or
910``-mtargetos=macos10.7``. Variants like Mac Catalyst are specified as
911``-target arm64-apple-ios15.0-macabi`` or ``-mtargetos=ios15.0-macabi``
912
913The availability attribute is a comma-separated list starting with the
914platform name and then including clauses specifying important milestones in the
915declaration's lifetime (in any order) along with additional information. Those
916clauses can be:
917
918introduced=\ *version*
919 The first version in which this declaration was introduced.
920
921deprecated=\ *version*
922 The first version in which this declaration was deprecated, meaning that
923 users should migrate away from this API.
924
925obsoleted=\ *version*
926 The first version in which this declaration was obsoleted, meaning that it
927 was removed completely and can no longer be used.
928
929unavailable
930 This declaration is never available on this platform.
931
932message=\ *string-literal*
933 Additional message text that Clang will provide when emitting a warning or
934 error about use of a deprecated or obsoleted declaration. Useful to direct
935 users to replacement APIs.
936
937replacement=\ *string-literal*
938 Additional message text that Clang will use to provide Fix-It when emitting
939 a warning about use of a deprecated declaration. The Fix-It will replace
940 the deprecated declaration with the new declaration specified.
941
942environment=\ *identifier*
943 Target environment in which this declaration is available. If present,
944 the availability attribute applies only to targets with the same platform
945 and environment. The parameter is currently supported only in HLSL.
946
947Multiple availability attributes can be placed on a declaration, which may
948correspond to different platforms. For most platforms, the availability
949attribute with the platform corresponding to the target platform will be used;
950any others will be ignored. However, the availability for ``watchOS`` and
951``tvOS`` can be implicitly inferred from an ``iOS`` availability attribute.
952Any explicit availability attributes for those platforms are still preferred over
953the implicitly inferred availability attributes. If no availability attribute
954specifies availability for the current target platform, the availability
955attributes are ignored. Supported platforms are:
956
957``iOS``
958``macOS``
959``tvOS``
960``watchOS``
961``iOSApplicationExtension``
962``macOSApplicationExtension``
963``tvOSApplicationExtension``
964``watchOSApplicationExtension``
965``macCatalyst``
966``macCatalystApplicationExtension``
967``visionOS``
968``visionOSApplicationExtension``
969``driverkit``
970``swift``
971``android``
972``fuchsia``
973``ohos``
974``zos``
975``ShaderModel``
976
977Some platforms have alias names:
978
979``ios``
980``macos``
981``macosx (deprecated)``
982``tvos``
983``watchos``
984``ios_app_extension``
985``macos_app_extension``
986``macosx_app_extension (deprecated)``
987``tvos_app_extension``
988``watchos_app_extension``
989``maccatalyst``
990``maccatalyst_app_extension``
991``visionos``
992``visionos_app_extension``
993``shadermodel``
994
995Supported environment names for the ShaderModel platform:
996
997``pixel``
998``vertex``
999``geometry``
1000``hull``
1001``domain``
1002``compute``
1003``raygeneration``
1004``intersection``
1005``anyhit``
1006``closesthit``
1007``miss``
1008``callable``
1009``mesh``
1010``amplification``
1011``library``
1012
1013A declaration can typically be used even when deploying back to a platform
1014version prior to when the declaration was introduced. When this happens, the
1015declaration is `weakly linked
1016<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
1017as if the ``weak_import`` attribute were added to the declaration. A
1018weakly-linked declaration may or may not be present a run-time, and a program
1019can determine whether the declaration is present by checking whether the
1020address of that declaration is non-NULL.
1021
1022The flag ``strict`` disallows using API when deploying back to a
1023platform version prior to when the declaration was introduced. An
1024attempt to use such API before its introduction causes a hard error.
1025Weakly-linking is almost always a better API choice, since it allows
1026users to query availability at runtime.
1027
1028If there are multiple declarations of the same entity, the availability
1029attributes must either match on a per-platform basis or later
1030declarations must not have availability attributes for that
1031platform. For example:
1032
1033.. code-block:: c
1034
1035 void g(void) __attribute__((availability(macos,introduced=10.4)));
1036 void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches
1037 void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
1038 void g(void); // okay, inherits both macos and ios availability from above.
1039 void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch
1040
1041When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
1042
1043.. code-block:: objc
1044
1045 @interface A
1046 - (id)method __attribute__((availability(macos,introduced=10.4)));
1047 - (id)method2 __attribute__((availability(macos,introduced=10.4)));
1048 @end
1049
1050 @interface B : A
1051 - (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later
1052 - (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4
1053 @end
1054
1055Starting with the macOS 10.12 SDK, the ``API_AVAILABLE`` macro from
1056``<os/availability.h>`` can simplify the spelling:
1057
1058.. code-block:: objc
1059
1060 @interface A
1061 - (id)method API_AVAILABLE(macos(10.11)));
1062 - (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0));
1063 @end
1064
1065Availability attributes can also be applied using a ``#pragma clang attribute``.
1066Any explicit availability attribute whose platform corresponds to the target
1067platform is applied to a declaration regardless of the availability attributes
1068specified in the pragma. For example, in the code below,
1069``hasExplicitAvailabilityAttribute`` will use the ``macOS`` availability
1070attribute that is specified with the declaration, whereas
1071``getsThePragmaAvailabilityAttribute`` will use the ``macOS`` availability
1072attribute that is applied by the pragma.
1073
1074.. code-block:: c
1075
1076 #pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function)
1077 void getsThePragmaAvailabilityAttribute(void);
1078 void hasExplicitAvailabilityAttribute(void) __attribute__((availability(macos,introduced=10.4)));
1079 #pragma clang attribute pop
1080
1081For platforms like ``watchOS`` and ``tvOS``, whose availability attributes can
1082be implicitly inferred from an ``iOS`` availability attribute, the logic is
1083slightly more complex. The explicit and the pragma-applied availability
1084attributes whose platform corresponds to the target platform are applied as
1085described in the previous paragraph. However, the implicitly inferred attributes
1086are applied to a declaration only when there is no explicit or pragma-applied
1087availability attribute whose platform corresponds to the target platform. For
1088example, the function below will receive the ``tvOS`` availability from the
1089pragma rather than using the inferred ``iOS`` availability from the declaration:
1090
1091.. code-block:: c
1092
1093 #pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function)
1094 void getsThePragmaTVOSAvailabilityAttribute(void) __attribute__((availability(iOS,introduced=11.0)));
1095 #pragma clang attribute pop
1096
1097The compiler is also able to apply implicitly inferred attributes from a pragma
1098as well. For example, when targeting ``tvOS``, the function below will receive
1099a ``tvOS`` availability attribute that is implicitly inferred from the ``iOS``
1100availability attribute applied by the pragma:
1101
1102.. code-block:: c
1103
1104 #pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function)
1105 void infersTVOSAvailabilityFromPragma(void);
1106 #pragma clang attribute pop
1107
1108The implicit attributes that are inferred from explicitly specified attributes
1109whose platform corresponds to the target platform are applied to the declaration
1110even if there is an availability attribute that can be inferred from a pragma.
1111For example, the function below will receive the ``tvOS, introduced=11.0``
1112availability that is inferred from the attribute on the declaration rather than
1113inferring availability from the pragma:
1114
1115.. code-block:: c
1116
1117 #pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function)
1118 void infersTVOSAvailabilityFromAttributeNextToDeclaration(void)
1119 __attribute__((availability(iOS,introduced=11.0)));
1120 #pragma clang attribute pop
1121
1122Also see the documentation for `@available
1123<http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-available>`_)reST";
1124
1125static const char AttrDoc_AvailableOnlyInDefaultEvalMethod[] = R"reST(No documentation.)reST";
1126
1127static const char AttrDoc_BPFFastCall[] = R"reST(Functions annotated with this attribute are likely to be inlined by BPF JIT.
1128It is assumed that inlined implementation uses less caller saved registers,
1129than a regular function.
1130Specifically, the following registers are likely to be preserved:
1131- ``R0`` if function return value is ``void``;
1132- ``R2-R5` if function takes 1 argument;
1133- ``R3-R5` if function takes 2 arguments;
1134- ``R4-R5` if function takes 3 arguments;
1135- ``R5`` if function takes 4 arguments;
1136
1137For such functions Clang generates code pattern that allows BPF JIT
1138to recognize and remove unnecessary spills and fills of the preserved
1139registers.)reST";
1140
1141static const char AttrDoc_BPFPreserveAccessIndex[] = R"reST(Clang supports the ``__attribute__((preserve_access_index))``
1142attribute for the BPF target. This attribute may be attached to a
1143struct or union declaration, where if -g is specified, it enables
1144preserving struct or union member access debuginfo indices of this
1145struct or union, similar to clang ``__builtin_preserve_access_index()``.)reST";
1146
1147static const char AttrDoc_BPFPreserveStaticOffset[] = R"reST(Clang supports the ``__attribute__((preserve_static_offset))``
1148attribute for the BPF target. This attribute may be attached to a
1149struct or union declaration. Reading or writing fields of types having
1150such annotation is guaranteed to generate LDX/ST/STX instruction with
1151offset corresponding to the field.
1152
1153For example:
1154
1155.. code-block:: c
1156
1157 struct foo {
1158 int a;
1159 int b;
1160 };
1161
1162 struct bar {
1163 int a;
1164 struct foo b;
1165 } __attribute__((preserve_static_offset));
1166
1167 void buz(struct bar *g) {
1168 g->b.a = 42;
1169 }
1170
1171The assignment to ``g``'s field would produce an ST instruction with
1172offset 8: ``*(u32)(r1 + 8) = 42;``.
1173
1174Without this attribute generated instructions might be different,
1175depending on optimizations behavior. E.g. the example above could be
1176rewritten as ``r1 += 8; *(u32)(r1 + 0) = 42;``.)reST";
1177
1178static const char AttrDoc_BTFDeclTag[] = R"reST(Clang supports the ``__attribute__((btf_decl_tag("ARGUMENT")))`` attribute for
1179all targets. This attribute may be attached to a struct/union, struct/union
1180field, function, function parameter, variable or typedef declaration. If -g is
1181specified, the ``ARGUMENT`` info will be preserved in IR and be emitted to
1182dwarf. For BPF targets, the ``ARGUMENT`` info will be emitted to .BTF ELF
1183section too.)reST";
1184
1185static const char AttrDoc_BTFTypeTag[] = R"reST(Clang supports the ``__attribute__((btf_type_tag("ARGUMENT")))`` attribute for
1186all targets. It only has effect when ``-g`` is specified on the command line and
1187is currently silently ignored when not applied to a pointer type (note: this
1188scenario may be diagnosed in the future).
1189
1190The ``ARGUMENT`` string will be preserved in IR and emitted to DWARF for the
1191types used in variable declarations, function declarations, or typedef
1192declarations.
1193
1194For BPF targets, the ``ARGUMENT`` string will also be emitted to .BTF ELF
1195section.)reST";
1196
1197static const char AttrDoc_Blocking[] = R"reST(Declares that a function potentially blocks, and prevents any potential inference of ``nonblocking``
1198by the compiler.)reST";
1199
1200static const char AttrDoc_Blocks[] = R"reST(No documentation.)reST";
1201
1202static const char AttrDoc_Builtin[] = R"reST()reST";
1203
1204static const char AttrDoc_BuiltinAlias[] = R"reST(This attribute is used in the implementation of the C intrinsics.
1205It allows the C intrinsic functions to be declared using the names defined
1206in target builtins, and still be recognized as clang builtins equivalent to the
1207underlying name. For example, ``riscv_vector.h`` declares the function ``vadd``
1208with ``__attribute__((clang_builtin_alias(__builtin_rvv_vadd_vv_i8m1)))``.
1209This ensures that both functions are recognized as that clang builtin,
1210and in the latter case, the choice of which builtin to identify the
1211function as can be deferred until after overload resolution.
1212
1213This attribute can only be used to set up the aliases for certain ARM/RISC-V
1214C intrinsic functions; it is intended for use only inside ``arm_*.h`` and
1215``riscv_*.h`` and is not a general mechanism for declaring arbitrary aliases
1216for clang builtin functions.)reST";
1217
1218static const char AttrDoc_C11NoReturn[] = R"reST(A function declared as ``_Noreturn`` shall not return to its caller. The
1219compiler will generate a diagnostic for a function declared as ``_Noreturn``
1220that appears to be capable of returning to its caller. Despite being a type
1221specifier, the ``_Noreturn`` attribute cannot be specified on a function
1222pointer type.)reST";
1223
1224static const char AttrDoc_CDecl[] = R"reST(No documentation.)reST";
1225
1226static const char AttrDoc_CFAuditedTransfer[] = R"reST(No documentation.)reST";
1227
1228static const char AttrDoc_CFConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1229(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1230convention (e.g. functions starting with "get" are assumed to return at
1231``+0``).
1232
1233It can be overridden using a family of the following attributes. In
1234Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
1235a function communicates that the object is returned at ``+1``, and the caller
1236is responsible for freeing it.
1237Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
1238specifies that the object is returned at ``+0`` and the ownership remains with
1239the callee.
1240The annotation ``__attribute__((ns_consumes_self))`` specifies that
1241the Objective-C method call consumes the reference to ``self``, e.g. by
1242attaching it to a supplied parameter.
1243Additionally, parameters can have an annotation
1244``__attribute__((ns_consumed))``, which specifies that passing an owned object
1245as that parameter effectively transfers the ownership, and the caller is no
1246longer responsible for it.
1247These attributes affect code generation when interacting with ARC code, and
1248they are used by the Clang Static Analyzer.
1249
1250In C programs using CoreFoundation, a similar set of attributes:
1251``__attribute__((cf_returns_not_retained))``,
1252``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
1253have the same respective semantics when applied to CoreFoundation objects.
1254These attributes affect code generation when interacting with ARC code, and
1255they are used by the Clang Static Analyzer.
1256
1257Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1258the same attribute family is present:
1259``__attribute__((os_returns_not_retained))``,
1260``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
1261with the same respective semantics.
1262Similar to ``__attribute__((ns_consumes_self))``,
1263``__attribute__((os_consumes_this))`` specifies that the method call consumes
1264the reference to "this" (e.g., when attaching it to a different object supplied
1265as a parameter).
1266Out parameters (parameters the function is meant to write into,
1267either via pointers-to-pointers or references-to-pointers)
1268may be annotated with ``__attribute__((os_returns_retained))``
1269or ``__attribute__((os_returns_not_retained))`` which specifies that the object
1270written into the out parameter should (or respectively should not) be released
1271after use.
1272Since often out parameters may or may not be written depending on the exit
1273code of the function,
1274annotations ``__attribute__((os_returns_retained_on_zero))``
1275and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
1276an out parameter at ``+1`` is written if and only if the function returns a zero
1277(respectively non-zero) error code.
1278Observe that return-code-dependent out parameter annotations are only
1279available for retained out parameters, as non-retained object do not have to be
1280released by the callee.
1281These attributes are only used by the Clang Static Analyzer.
1282
1283The family of attributes ``X_returns_X_retained`` can be added to functions,
1284C++ methods, and Objective-C methods and properties.
1285Attributes ``X_consumed`` can be added to parameters of methods, functions,
1286and Objective-C methods.)reST";
1287
1288static const char AttrDoc_CFGuard[] = R"reST(Code can indicate CFG checks are not wanted with the ``__declspec(guard(nocf))``
1289attribute. This directs the compiler to not insert any CFG checks for the entire
1290function. This approach is typically used only sparingly in specific situations
1291where the programmer has manually inserted "CFG-equivalent" protection. The
1292programmer knows that they are calling through some read-only function table
1293whose address is obtained through read-only memory references and for which the
1294index is masked to the function table limit. This approach may also be applied
1295to small wrapper functions that are not inlined and that do nothing more than
1296make a call through a function pointer. Since incorrect usage of this directive
1297can compromise the security of CFG, the programmer must be very careful using
1298the directive. Typically, this usage is limited to very small functions that
1299only call one function.
1300
1301`Control Flow Guard documentation <https://docs.microsoft.com/en-us/windows/win32/secbp/pe-metadata>`)reST";
1302
1303static const char AttrDoc_CFICanonicalJumpTable[] = R"reST(Use ``__attribute__((cfi_canonical_jump_table))`` on a function declaration to
1304make the function's CFI jump table canonical. See :ref:`the CFI documentation
1305<cfi-canonical-jump-tables>` for more details.)reST";
1306
1307static const char AttrDoc_CFISalt[] = R"reST(The ``cfi_salt`` attribute specifies a string literal that is used as a salt
1308for Control-Flow Integrity (CFI) checks to distinguish between functions with
1309the same type signature. This attribute can be applied to function declarations,
1310function definitions, and function pointer typedefs.
1311
1312The attribute prevents function pointers from being replaced with pointers to
1313functions that have a compatible type, which can be a CFI bypass vector.
1314
1315**Syntax:**
1316
1317* GNU-style: ``__attribute__((cfi_salt("<salt_string>")))``
1318* C++11-style: ``[[clang::cfi_salt("<salt_string>")]]``
1319
1320**Usage:**
1321
1322The attribute takes a single string literal argument that serves as the salt.
1323Functions or function types with different salt values will have different CFI
1324hashes, even if they have identical type signatures.
1325
1326**Motivation:**
1327
1328In large codebases like the Linux kernel, there are often hundreds of functions
1329with identical type signatures that are called indirectly:
1330
1331.. code-block::
1332
1333 1662 functions with void (*)(void)
1334 1179 functions with int (*)(void)
1335 ...
1336
1337By salting the CFI hashes, you can make CFI more robust by ensuring that
1338functions intended for different purposes have distinct CFI identities.
1339
1340**Type Compatibility:**
1341
1342* Functions with different salt values are considered to have incompatible types
1343* Function pointers with different salt values cannot be assigned to each other
1344* All declarations of the same function must use the same salt value
1345
1346**Example:**
1347
1348.. code-block:: c
1349
1350 // Header file - define convenience macros
1351 #define __cfi_salt(s) __attribute__((cfi_salt(s)))
1352
1353 // Typedef for regular function pointers
1354 typedef int (*fptr_t)(void);
1355
1356 // Typedef for salted function pointers
1357 typedef int (*fptr_salted_t)(void) __cfi_salt("pepper");
1358
1359 struct widget_ops {
1360 fptr_t init; // Regular CFI
1361 fptr_salted_t exec; // Salted CFI
1362 fptr_t cleanup; // Regular CFI
1363 };
1364
1365 // Function implementations
1366 static int widget_init(void) { return 0; }
1367 static int widget_exec(void) __cfi_salt("pepper") { return 1; }
1368 static int widget_cleanup(void) { return 0; }
1369
1370 static struct widget_ops ops = {
1371 .init = widget_init, // OK - compatible types
1372 .exec = widget_exec, // OK - both use "pepper" salt
1373 .cleanup = widget_cleanup // OK - compatible types
1374 };
1375
1376 // Using C++11 attribute syntax
1377 void secure_callback(void) [[clang::cfi_salt("secure")]];
1378
1379 // This would cause a compilation error:
1380 // fptr_t bad_ptr = widget_exec; // Error: incompatible types
1381
1382**Notes:**
1383
1384* The salt string can contain non-NULL ASCII characters, including spaces and
1385 quotes
1386* This attribute only applies to function types; using it on non-function
1387 types will generate a warning
1388* All declarations and definitions of the same function must use identical
1389 salt values
1390* The attribute affects type compatibility during compilation and CFI hash
1391 generation during code generation)reST";
1392
1393static const char AttrDoc_CFIUncheckedCallee[] = R"reST(``cfi_unchecked_callee`` is a function type attribute which prevents the compiler from instrumenting
1394`Control Flow Integrity <https://clang.llvm.org/docs/ControlFlowIntegrity.html>`_ checks on indirect
1395function calls. This also includes control flow checks added by
1396`-fsanitize=function <https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#available-checks>`.
1397Specifically, the attribute has the following semantics:
1398
13991. Indirect calls to a function type with this attribute will not be instrumented with CFI. That is,
1400 the indirect call will not be checked. Note that this only changes the behavior for indirect calls
1401 on pointers to function types having this attribute. It does not prevent all indirect function calls
1402 for a given type from being checked.
14032. All direct references to a function whose type has this attribute will always reference the
1404 function definition rather than an entry in the CFI jump table.
14053. When a pointer to a function with this attribute is implicitly cast to a pointer to a function
1406 without this attribute, the compiler will give a warning saying this attribute is discarded. This
1407 warning can be silenced with an explicit cast. Note an explicit cast just disables the warning, so
1408 direct references to a function with a ``cfi_unchecked_callee`` attribute will still reference the
1409 function definition rather than the CFI jump table.
1410
1411.. code-block:: c
1412
1413 #define CFI_UNCHECKED_CALLEE __attribute__((cfi_unchecked_callee))
1414
1415 void no_cfi() CFI_UNCHECKED_CALLEE {}
1416
1417 void (*with_cfi)() = no_cfi; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1418 // `with_cfi` also points to the actual definition of `no_cfi` rather than
1419 // its jump table entry.
1420
1421 void invoke(void (CFI_UNCHECKED_CALLEE *func)()) {
1422 func(); // CFI will not instrument this indirect call.
1423
1424 void (*func2)() = func; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1425
1426 func2(); // CFI will instrument this indirect call. Users should be careful however because if this
1427 // references a function with type `cfi_unchecked_callee`, then the CFI check may incorrectly
1428 // fail because the reference will be to the function definition rather than the CFI jump
1429 // table entry.
1430 }
1431
1432This attribute can only be applied on functions or member functions. This attribute can be a good
1433alternative to ``no_sanitize("cfi")`` if you only want to disable innstrumentation for specific indirect
1434calls rather than applying ``no_sanitize("cfi")`` on the whole function containing indirect call. Note
1435that ``cfi_unchecked_attribute`` is a type attribute doesn't disable CFI instrumentation on a function
1436body.)reST";
1437
1438static const char AttrDoc_CFReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1439(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1440convention (e.g. functions starting with "get" are assumed to return at
1441``+0``).
1442
1443It can be overridden using a family of the following attributes. In
1444Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
1445a function communicates that the object is returned at ``+1``, and the caller
1446is responsible for freeing it.
1447Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
1448specifies that the object is returned at ``+0`` and the ownership remains with
1449the callee.
1450The annotation ``__attribute__((ns_consumes_self))`` specifies that
1451the Objective-C method call consumes the reference to ``self``, e.g. by
1452attaching it to a supplied parameter.
1453Additionally, parameters can have an annotation
1454``__attribute__((ns_consumed))``, which specifies that passing an owned object
1455as that parameter effectively transfers the ownership, and the caller is no
1456longer responsible for it.
1457These attributes affect code generation when interacting with ARC code, and
1458they are used by the Clang Static Analyzer.
1459
1460In C programs using CoreFoundation, a similar set of attributes:
1461``__attribute__((cf_returns_not_retained))``,
1462``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
1463have the same respective semantics when applied to CoreFoundation objects.
1464These attributes affect code generation when interacting with ARC code, and
1465they are used by the Clang Static Analyzer.
1466
1467Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1468the same attribute family is present:
1469``__attribute__((os_returns_not_retained))``,
1470``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
1471with the same respective semantics.
1472Similar to ``__attribute__((ns_consumes_self))``,
1473``__attribute__((os_consumes_this))`` specifies that the method call consumes
1474the reference to "this" (e.g., when attaching it to a different object supplied
1475as a parameter).
1476Out parameters (parameters the function is meant to write into,
1477either via pointers-to-pointers or references-to-pointers)
1478may be annotated with ``__attribute__((os_returns_retained))``
1479or ``__attribute__((os_returns_not_retained))`` which specifies that the object
1480written into the out parameter should (or respectively should not) be released
1481after use.
1482Since often out parameters may or may not be written depending on the exit
1483code of the function,
1484annotations ``__attribute__((os_returns_retained_on_zero))``
1485and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
1486an out parameter at ``+1`` is written if and only if the function returns a zero
1487(respectively non-zero) error code.
1488Observe that return-code-dependent out parameter annotations are only
1489available for retained out parameters, as non-retained object do not have to be
1490released by the callee.
1491These attributes are only used by the Clang Static Analyzer.
1492
1493The family of attributes ``X_returns_X_retained`` can be added to functions,
1494C++ methods, and Objective-C methods and properties.
1495Attributes ``X_consumed`` can be added to parameters of methods, functions,
1496and Objective-C methods.)reST";
1497
1498static const char AttrDoc_CFReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1499(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1500convention (e.g. functions starting with "get" are assumed to return at
1501``+0``).
1502
1503It can be overridden using a family of the following attributes. In
1504Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
1505a function communicates that the object is returned at ``+1``, and the caller
1506is responsible for freeing it.
1507Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
1508specifies that the object is returned at ``+0`` and the ownership remains with
1509the callee.
1510The annotation ``__attribute__((ns_consumes_self))`` specifies that
1511the Objective-C method call consumes the reference to ``self``, e.g. by
1512attaching it to a supplied parameter.
1513Additionally, parameters can have an annotation
1514``__attribute__((ns_consumed))``, which specifies that passing an owned object
1515as that parameter effectively transfers the ownership, and the caller is no
1516longer responsible for it.
1517These attributes affect code generation when interacting with ARC code, and
1518they are used by the Clang Static Analyzer.
1519
1520In C programs using CoreFoundation, a similar set of attributes:
1521``__attribute__((cf_returns_not_retained))``,
1522``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
1523have the same respective semantics when applied to CoreFoundation objects.
1524These attributes affect code generation when interacting with ARC code, and
1525they are used by the Clang Static Analyzer.
1526
1527Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1528the same attribute family is present:
1529``__attribute__((os_returns_not_retained))``,
1530``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
1531with the same respective semantics.
1532Similar to ``__attribute__((ns_consumes_self))``,
1533``__attribute__((os_consumes_this))`` specifies that the method call consumes
1534the reference to "this" (e.g., when attaching it to a different object supplied
1535as a parameter).
1536Out parameters (parameters the function is meant to write into,
1537either via pointers-to-pointers or references-to-pointers)
1538may be annotated with ``__attribute__((os_returns_retained))``
1539or ``__attribute__((os_returns_not_retained))`` which specifies that the object
1540written into the out parameter should (or respectively should not) be released
1541after use.
1542Since often out parameters may or may not be written depending on the exit
1543code of the function,
1544annotations ``__attribute__((os_returns_retained_on_zero))``
1545and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
1546an out parameter at ``+1`` is written if and only if the function returns a zero
1547(respectively non-zero) error code.
1548Observe that return-code-dependent out parameter annotations are only
1549available for retained out parameters, as non-retained object do not have to be
1550released by the callee.
1551These attributes are only used by the Clang Static Analyzer.
1552
1553The family of attributes ``X_returns_X_retained`` can be added to functions,
1554C++ methods, and Objective-C methods and properties.
1555Attributes ``X_consumed`` can be added to parameters of methods, functions,
1556and Objective-C methods.)reST";
1557
1558static const char AttrDoc_CFUnknownTransfer[] = R"reST(No documentation.)reST";
1559
1560static const char AttrDoc_CPUDispatch[] = R"reST(The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and
1561resolve multiversioned functions. This form of multiversioning provides a
1562mechanism for declaring versions across translation units and manually
1563specifying the resolved function list. A specified CPU defines a set of minimum
1564features that are required for the function to be called. The result of this is
1565that future processors execute the most restrictive version of the function the
1566new processor can execute.
1567
1568In addition, unlike the ICC implementation of this feature, the selection of the
1569version does not consider the manufacturer or microarchitecture of the processor.
1570It tests solely the list of features that are both supported by the specified
1571processor and present in the compiler-rt library. This can be surprising at times,
1572as the runtime processor may be from a completely different manufacturer, as long
1573as it supports the same feature set.
1574
1575This can additionally be surprising, as some processors are indistringuishable from
1576others based on the list of testable features. When this happens, the variant
1577is selected in an unspecified manner.
1578
1579Function versions are defined with ``cpu_specific``, which takes one or more CPU
1580names as a parameter. For example:
1581
1582.. code-block:: c
1583
1584 // Declares and defines the ivybridge version of single_cpu.
1585 __attribute__((cpu_specific(ivybridge)))
1586 void single_cpu(void){}
1587
1588 // Declares and defines the atom version of single_cpu.
1589 __attribute__((cpu_specific(atom)))
1590 void single_cpu(void){}
1591
1592 // Declares and defines both the ivybridge and atom version of multi_cpu.
1593 __attribute__((cpu_specific(ivybridge, atom)))
1594 void multi_cpu(void){}
1595
1596A dispatching (or resolving) function can be declared anywhere in a project's
1597source code with ``cpu_dispatch``. This attribute takes one or more CPU names
1598as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch``
1599are not expected to be defined, only declared. If such a marked function has a
1600definition, any side effects of the function are ignored; trivial function
1601bodies are permissible for ICC compatibility.
1602
1603.. code-block:: c
1604
1605 // Creates a resolver for single_cpu above.
1606 __attribute__((cpu_dispatch(ivybridge, atom)))
1607 void single_cpu(void){}
1608
1609 // Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1610 // translation unit.
1611 __attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1612 void multi_cpu(void){}
1613
1614Note that it is possible to have a resolving function that dispatches based on
1615more or fewer options than are present in the program. Specifying fewer will
1616result in the omitted options not being considered during resolution. Specifying
1617a version for resolution that isn't defined in the program will result in a
1618linking failure.
1619
1620It is also possible to specify a CPU name of ``generic`` which will be resolved
1621if the executing processor doesn't satisfy the features required in the CPU
1622name. The behavior of a program executing on a processor that doesn't satisfy
1623any option of a multiversioned function is undefined.)reST";
1624
1625static const char AttrDoc_CPUSpecific[] = R"reST(The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and
1626resolve multiversioned functions. This form of multiversioning provides a
1627mechanism for declaring versions across translation units and manually
1628specifying the resolved function list. A specified CPU defines a set of minimum
1629features that are required for the function to be called. The result of this is
1630that future processors execute the most restrictive version of the function the
1631new processor can execute.
1632
1633In addition, unlike the ICC implementation of this feature, the selection of the
1634version does not consider the manufacturer or microarchitecture of the processor.
1635It tests solely the list of features that are both supported by the specified
1636processor and present in the compiler-rt library. This can be surprising at times,
1637as the runtime processor may be from a completely different manufacturer, as long
1638as it supports the same feature set.
1639
1640This can additionally be surprising, as some processors are indistringuishable from
1641others based on the list of testable features. When this happens, the variant
1642is selected in an unspecified manner.
1643
1644Function versions are defined with ``cpu_specific``, which takes one or more CPU
1645names as a parameter. For example:
1646
1647.. code-block:: c
1648
1649 // Declares and defines the ivybridge version of single_cpu.
1650 __attribute__((cpu_specific(ivybridge)))
1651 void single_cpu(void){}
1652
1653 // Declares and defines the atom version of single_cpu.
1654 __attribute__((cpu_specific(atom)))
1655 void single_cpu(void){}
1656
1657 // Declares and defines both the ivybridge and atom version of multi_cpu.
1658 __attribute__((cpu_specific(ivybridge, atom)))
1659 void multi_cpu(void){}
1660
1661A dispatching (or resolving) function can be declared anywhere in a project's
1662source code with ``cpu_dispatch``. This attribute takes one or more CPU names
1663as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch``
1664are not expected to be defined, only declared. If such a marked function has a
1665definition, any side effects of the function are ignored; trivial function
1666bodies are permissible for ICC compatibility.
1667
1668.. code-block:: c
1669
1670 // Creates a resolver for single_cpu above.
1671 __attribute__((cpu_dispatch(ivybridge, atom)))
1672 void single_cpu(void){}
1673
1674 // Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1675 // translation unit.
1676 __attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1677 void multi_cpu(void){}
1678
1679Note that it is possible to have a resolving function that dispatches based on
1680more or fewer options than are present in the program. Specifying fewer will
1681result in the omitted options not being considered during resolution. Specifying
1682a version for resolution that isn't defined in the program will result in a
1683linking failure.
1684
1685It is also possible to specify a CPU name of ``generic`` which will be resolved
1686if the executing processor doesn't satisfy the features required in the CPU
1687name. The behavior of a program executing on a processor that doesn't satisfy
1688any option of a multiversioned function is undefined.)reST";
1689
1690static const char AttrDoc_CUDAClusterDims[] = R"reST(In CUDA/HIP programming, the ``cluster_dims`` attribute, conventionally exposed as the
1691``__cluster_dims__`` macro, can be applied to a kernel function to set the dimensions of a
1692thread block cluster, which is an optional level of hierarchy and made up of thread blocks.
1693``__cluster_dims__`` defines the cluster size as ``(X, Y, Z)``, where each value is the number
1694of thread blocks in that dimension. The ``cluster_dims`` and `no_cluster`` attributes are
1695mutually exclusive.
1696
1697.. code::
1698
1699 __global__ __cluster_dims__(2, 1, 1) void kernel(...) {
1700 ...
1701 })reST";
1702
1703static const char AttrDoc_CUDAConstant[] = R"reST(No documentation.)reST";
1704
1705static const char AttrDoc_CUDADevice[] = R"reST(No documentation.)reST";
1706
1707static const char AttrDoc_CUDADeviceBuiltinSurfaceType[] = R"reST(The ``device_builtin_surface_type`` attribute can be applied to a class
1708template when declaring the surface reference. A surface reference variable
1709could be accessed on the host side and, on the device side, might be translated
1710into an internal surface object, which is established through surface bind and
1711unbind runtime APIs.)reST";
1712
1713static const char AttrDoc_CUDADeviceBuiltinTextureType[] = R"reST(The ``device_builtin_texture_type`` attribute can be applied to a class
1714template when declaring the texture reference. A texture reference variable
1715could be accessed on the host side and, on the device side, might be translated
1716into an internal texture object, which is established through texture bind and
1717unbind runtime APIs.)reST";
1718
1719static const char AttrDoc_CUDAGlobal[] = R"reST(No documentation.)reST";
1720
1721static const char AttrDoc_CUDAGridConstant[] = R"reST(The ``__grid_constant__`` attribute can be applied to a ``const``-qualified kernel
1722function argument and allows compiler to take the address of that argument without
1723making a copy. The argument applies to sm_70 or newer GPUs, during compilation
1724with CUDA-11.7(PTX 7.7) or newer, and is ignored otherwise.)reST";
1725
1726static const char AttrDoc_CUDAHost[] = R"reST(No documentation.)reST";
1727
1728static const char AttrDoc_CUDAInvalidTarget[] = R"reST()reST";
1729
1730static const char AttrDoc_CUDALaunchBounds[] = R"reST(No documentation.)reST";
1731
1732static const char AttrDoc_CUDANoCluster[] = R"reST(In CUDA/HIP programming, a kernel function can still be launched with the cluster feature enabled
1733at runtime, even without being annotated with ``__cluster_dims__``. The LLVM/Clang-exclusive
1734``no_cluster`` attribute, conventionally exposed as the ``__no_cluster__`` macro, can be applied to
1735a kernel function to explicitly indicate that the cluster feature will not be enabled either at
1736compile time or at kernel launch time. This allows the compiler to apply certain optimizations
1737without assuming that clustering could be enabled at runtime. It is undefined behavior to launch a
1738kernel annotated with ``__no_cluster__`` if the cluster feature is enabled at runtime.
1739The ``cluster_dims`` and ``no_cluster`` attributes are mutually exclusive.
1740
1741.. code::
1742
1743 __global__ __no_cluster__ void kernel(...) {
1744 ...
1745 })reST";
1746
1747static const char AttrDoc_CUDAShared[] = R"reST(No documentation.)reST";
1748
1749static const char AttrDoc_CXX11NoReturn[] = R"reST(A function declared as ``[[noreturn]]`` shall not return to its caller. The
1750compiler will generate a diagnostic for a function declared as ``[[noreturn]]``
1751that appears to be capable of returning to its caller.
1752
1753The ``[[_Noreturn]]`` spelling is deprecated and only exists to ease code
1754migration for code using ``[[noreturn]]`` after including ``<stdnoreturn.h>``.)reST";
1755
1756static const char AttrDoc_CXXAssume[] = R"reST(The ``assume`` attribute is used to indicate to the optimizer that a
1757certain condition is assumed to be true at a certain point in the
1758program. If this condition is violated at runtime, the behavior is
1759undefined. ``assume`` can only be applied to a null statement.
1760
1761Different optimisers are likely to react differently to the presence of
1762this attribute; in some cases, adding ``assume`` may affect performance
1763negatively. It should be used with parsimony and care.
1764
1765Example:
1766
1767.. code-block:: c++
1768
1769 int f(int x, int y) {
1770 [[assume(x == 27)]];
1771 [[assume(x == y)]];
1772 return y + 1; // May be optimised to `return 28`.
1773 })reST";
1774
1775static const char AttrDoc_CallableWhen[] = R"reST(Use ``__attribute__((callable_when(...)))`` to indicate what states a method
1776may be called in. Valid states are unconsumed, consumed, or unknown. Each
1777argument to this attribute must be a quoted string. E.g.:
1778
1779``__attribute__((callable_when("unconsumed", "unknown")))``)reST";
1780
1781static const char AttrDoc_Callback[] = R"reST(The ``callback`` attribute specifies that the annotated function may invoke the
1782specified callback zero or more times. The callback, as well as the passed
1783arguments, are identified by their parameter name or position (starting with
17841!) in the annotated function. The first position in the attribute identifies
1785the callback callee, the following positions declare describe its arguments.
1786The callback callee is required to be callable with the number, and order, of
1787the specified arguments. The index ``0``, or the identifier ``this``, is used to
1788represent an implicit "this" pointer in class methods. If there is no implicit
1789"this" pointer it shall not be referenced. The index '-1', or the name "__",
1790represents an unknown callback callee argument. This can be a value which is
1791not present in the declared parameter list, or one that is, but is potentially
1792inspected, captured, or modified. Parameter names and indices can be mixed in
1793the callback attribute.
1794
1795The ``callback`` attribute, which is directly translated to ``callback``
1796metadata <http://llvm.org/docs/LangRef.html#callback-metadata>, make the
1797connection between the call to the annotated function and the callback callee.
1798This can enable interprocedural optimizations which were otherwise impossible.
1799If a function parameter is mentioned in the ``callback`` attribute, through its
1800position, it is undefined if that parameter is used for anything other than the
1801actual callback. Inspected, captured, or modified parameters shall not be
1802listed in the ``callback`` metadata.
1803
1804Example encodings for the callback performed by ``pthread_create`` are shown
1805below. The explicit attribute annotation indicates that the third parameter
1806(``start_routine``) is called zero or more times by the ``pthread_create`` function,
1807and that the fourth parameter (``arg``) is passed along. Note that the callback
1808behavior of ``pthread_create`` is automatically recognized by Clang. In addition,
1809the declarations of ``__kmpc_fork_teams`` and ``__kmpc_fork_call``, generated for
1810``#pragma omp target teams`` and ``#pragma omp parallel``, respectively, are also
1811automatically recognized as broker functions. Further functions might be added
1812in the future.
1813
1814 .. code-block:: c
1815
1816 __attribute__((callback (start_routine, arg)))
1817 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1818 void *(*start_routine) (void *), void *arg);
1819
1820 __attribute__((callback (3, 4)))
1821 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1822 void *(*start_routine) (void *), void *arg);)reST";
1823
1824static const char AttrDoc_CalledOnce[] = R"reST(The ``called_once`` attribute specifies that the annotated function or method
1825parameter is invoked exactly once on all execution paths. It only applies
1826to parameters with function-like types, i.e. function pointers or blocks. This
1827concept is particularly useful for asynchronous programs.
1828
1829Clang implements a check for ``called_once`` parameters,
1830``-Wcalled-once-parameter``. It is on by default and finds the following
1831violations:
1832
1833* Parameter is not called at all.
1834
1835* Parameter is called more than once.
1836
1837* Parameter is not called on one of the execution paths.
1838
1839In the latter case, Clang pinpoints the path where parameter is not invoked
1840by showing the control-flow statement where the path diverges.
1841
1842.. code-block:: objc
1843
1844 void fooWithCallback(void (^callback)(void) __attribute__((called_once))) {
1845 if (somePredicate()) {
1846 ...
1847 callback();
1848 } else {
1849 callback(); // OK: callback is called on every path
1850 }
1851 }
1852
1853 void barWithCallback(void (^callback)(void) __attribute__((called_once))) {
1854 if (somePredicate()) {
1855 ...
1856 callback(); // note: previous call is here
1857 }
1858 callback(); // warning: callback is called twice
1859 }
1860
1861 void foobarWithCallback(void (^callback)(void) __attribute__((called_once))) {
1862 if (somePredicate()) { // warning: callback is not called when condition is false
1863 ...
1864 callback();
1865 }
1866 }
1867
1868This attribute is useful for API developers who want to double-check if they
1869implemented their method correctly.)reST";
1870
1871static const char AttrDoc_Capability[] = R"reST(No documentation.)reST";
1872
1873static const char AttrDoc_CapturedRecord[] = R"reST()reST";
1874
1875static const char AttrDoc_CarriesDependency[] = R"reST(The ``carries_dependency`` attribute specifies dependency propagation into and
1876out of functions.
1877
1878When specified on a function or Objective-C method, the ``carries_dependency``
1879attribute means that the return value carries a dependency out of the function,
1880so that the implementation need not constrain ordering upon return from that
1881function. Implementations of the function and its caller may choose to preserve
1882dependencies instead of emitting memory ordering instructions such as fences.
1883
1884Note, this attribute does not change the meaning of the program, but may result
1885in generation of more efficient code.)reST";
1886
1887static const char AttrDoc_Cleanup[] = R"reST(This attribute allows a function to be run when a local variable goes out of
1888scope. The attribute takes the identifier of a function with a parameter type
1889that is a pointer to the type with the attribute.
1890
1891.. code-block:: c
1892
1893 static void foo (int *) { ... }
1894 static void bar (int *) { ... }
1895 void baz (void) {
1896 int x __attribute__((cleanup(foo)));
1897 {
1898 int y __attribute__((cleanup(bar)));
1899 }
1900 }
1901
1902The above example will result in a call to ``bar`` being passed the address of
1903``y`` when ``y`` goes out of scope, then a call to ``foo`` being passed the
1904address of ``x`` when ``x`` goes out of scope. If two or more variables share
1905the same scope, their ``cleanup`` callbacks are invoked in the reverse order
1906the variables were declared in. It is not possible to check the return value
1907(if any) of these ``cleanup`` callback functions.)reST";
1908
1909static const char AttrDoc_ClspvLibclcBuiltin[] = R"reST(Attribute used by `clspv`_ (OpenCL-C to Vulkan SPIR-V compiler) to identify functions coming from `libclc`_ (OpenCL-C builtin library).
1910
1911.. code-block:: c
1912
1913 void __attribute__((clspv_libclc_builtin)) libclc_builtin() {}
1914
1915.. _`clspv`: https://github.com/google/clspv
1916.. _`libclc`: https://libclc.llvm.org)reST";
1917
1918static const char AttrDoc_CmseNSCall[] = R"reST(This attribute declares a non-secure function type. When compiling for secure
1919state, a call to such a function would switch from secure to non-secure state.
1920All non-secure function calls must happen only through a function pointer, and
1921a non-secure function type should only be used as a base type of a pointer.
1922See `ARMv8-M Security Extensions: Requirements on Development
1923Tools - Engineering Specification Documentation
1924<https://developer.arm.com/docs/ecm0359818/latest/>`_ for more information.)reST";
1925
1926static const char AttrDoc_CmseNSEntry[] = R"reST(This attribute declares a function that can be called from non-secure state, or
1927from secure state. Entering from and returning to non-secure state would switch
1928to and from secure state, respectively, and prevent flow of information
1929to non-secure state, except via return values. See `ARMv8-M Security Extensions:
1930Requirements on Development Tools - Engineering Specification Documentation
1931<https://developer.arm.com/docs/ecm0359818/latest/>`_ for more information.)reST";
1932
1933static const char AttrDoc_CodeAlign[] = R"reST(The ``clang::code_align(N)`` attribute applies to a loop and specifies the byte
1934alignment for a loop. The attribute accepts a positive integer constant
1935initialization expression indicating the number of bytes for the minimum
1936alignment boundary. Its value must be a power of 2, between 1 and 4096
1937(inclusive).
1938
1939.. code-block:: c++
1940
1941 void foo() {
1942 int var = 0;
1943 [[clang::code_align(16)]] for (int i = 0; i < 10; ++i) var++;
1944 }
1945
1946 void Array(int *array, size_t n) {
1947 [[clang::code_align(64)]] for (int i = 0; i < n; ++i) array[i] = 0;
1948 }
1949
1950 void count () {
1951 int a1[10], int i = 0;
1952 [[clang::code_align(32)]] while (i < 10) { a1[i] += 3; }
1953 }
1954
1955 void check() {
1956 int a = 10;
1957 [[clang::code_align(8)]] do {
1958 a = a + 1;
1959 } while (a < 20);
1960 }
1961
1962 template<int A>
1963 void func() {
1964 [[clang::code_align(A)]] for(;;) { }
1965 })reST";
1966
1967static const char AttrDoc_CodeModel[] = R"reST(The ``model`` attribute allows overriding the translation unit's
1968code model (specified by ``-mcmodel``) for a specific global variable.
1969
1970On LoongArch, allowed values are "normal", "medium", "extreme".
1971
1972On x86-64, allowed values are ``"small"`` and ``"large"``. ``"small"`` is
1973roughly equivalent to ``-mcmodel=small``, meaning the global is considered
1974"small" placed closer to the ``.text`` section relative to "large" globals, and
1975to prefer using 32-bit relocations to access the global. ``"large"`` is roughly
1976equivalent to ``-mcmodel=large``, meaning the global is considered "large" and
1977placed further from the ``.text`` section relative to "small" globals, and
197864-bit relocations must be used to access the global.)reST";
1979
1980static const char AttrDoc_CodeSeg[] = R"reST(The ``__declspec(code_seg)`` attribute enables the placement of code into separate
1981named segments that can be paged or locked in memory individually. This attribute
1982is used to control the placement of instantiated templates and compiler-generated
1983code. See the documentation for `__declspec(code_seg)`_ on MSDN.
1984
1985.. _`__declspec(code_seg)`: http://msdn.microsoft.com/en-us/library/dn636922.aspx)reST";
1986
1987static const char AttrDoc_Cold[] = R"reST(``__attribute__((cold))`` marks a function as cold, as a manual alternative to PGO hotness data.
1988If PGO data is available, the profile count based hotness overrides the ``__attribute__((cold))`` annotation (unlike ``__attribute__((hot))``).)reST";
1989
1990static const char AttrDoc_Common[] = R"reST(No documentation.)reST";
1991
1992static const char AttrDoc_Const[] = R"reST(No documentation.)reST";
1993
1994static const char AttrDoc_ConstInit[] = R"reST(This attribute specifies that the variable to which it is attached is intended
1995to have a `constant initializer <http://en.cppreference.com/w/cpp/language/constant_initialization>`_
1996according to the rules of [basic.start.static]. The variable is required to
1997have static or thread storage duration. If the initialization of the variable
1998is not a constant initializer an error will be produced. This attribute may
1999only be used in C++; the ``constinit`` spelling is only accepted in C++20
2000onwards.
2001
2002Note that in C++03 strict constant expression checking is not done. Instead
2003the attribute reports if Clang can emit the variable as a constant, even if it's
2004not technically a 'constant initializer'. This behavior is non-portable.
2005
2006Static storage duration variables with constant initializers avoid hard-to-find
2007bugs caused by the indeterminate order of dynamic initialization. They can also
2008be safely used during dynamic initialization across translation units.
2009
2010This attribute acts as a compile time assertion that the requirements
2011for constant initialization have been met. Since these requirements change
2012between dialects and have subtle pitfalls it's important to fail fast instead
2013of silently falling back on dynamic initialization.
2014
2015The first use of the attribute on a variable must be part of, or precede, the
2016initializing declaration of the variable. C++20 requires the ``constinit``
2017spelling of the attribute to be present on the initializing declaration if it
2018is used anywhere. The other spellings can be specified on a forward declaration
2019and omitted on a later initializing declaration.
2020
2021.. code-block:: c++
2022
2023 // -std=c++14
2024 #define SAFE_STATIC [[clang::require_constant_initialization]]
2025 struct T {
2026 constexpr T(int) {}
2027 ~T(); // non-trivial
2028 };
2029 SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor.
2030 SAFE_STATIC T y = 42; // error: variable does not have a constant initializer
2031 // copy initialization is not a constant expression on a non-literal type.)reST";
2032
2033static const char AttrDoc_Constructor[] = R"reST(The ``constructor`` attribute causes the function to be called before entering
2034``main()``, and the ``destructor`` attribute causes the function to be called
2035after returning from ``main()`` or when the ``exit()`` function has been
2036called. Note, ``quick_exit()``, ``_Exit()``, and ``abort()`` prevent a function
2037marked ``destructor`` from being called.
2038
2039The constructor or destructor function should not accept any arguments and its
2040return type should be ``void``.
2041
2042The attributes accept an optional argument used to specify the priority order
2043in which to execute constructor and destructor functions. The priority is
2044given as an integer constant expression between 101 and 65535 (inclusive).
2045Priorities outside of that range are reserved for use by the implementation. A
2046lower value indicates a higher priority of initialization. Note that only the
2047relative ordering of values is important. For example:
2048
2049.. code-block:: c++
2050
2051 __attribute__((constructor(200))) void foo(void);
2052 __attribute__((constructor(101))) void bar(void);
2053
2054``bar()`` will be called before ``foo()``, and both will be called before
2055``main()``. If no argument is given to the ``constructor`` or ``destructor``
2056attribute, they default to the value ``65535``.)reST";
2057
2058static const char AttrDoc_Consumable[] = R"reST(Each ``class`` that uses any of the typestate annotations must first be marked
2059using the ``consumable`` attribute. Failure to do so will result in a warning.
2060
2061This attribute accepts a single parameter that must be one of the following:
2062``unknown``, ``consumed``, or ``unconsumed``.)reST";
2063
2064static const char AttrDoc_ConsumableAutoCast[] = R"reST(No documentation.)reST";
2065
2066static const char AttrDoc_ConsumableSetOnRead[] = R"reST(No documentation.)reST";
2067
2068static const char AttrDoc_Convergent[] = R"reST(The ``convergent`` attribute can be placed on a function declaration. It is
2069translated into the LLVM ``convergent`` attribute, which indicates that the call
2070instructions of a function with this attribute cannot be made control-dependent
2071on any additional values.
2072
2073This attribute is different from ``noduplicate`` because it allows duplicating
2074function calls if it can be proved that the duplicated function calls are
2075not made control-dependent on any additional values, e.g., unrolling a loop
2076executed by all work items.
2077
2078Sample usage:
2079
2080.. code-block:: c
2081
2082 void convfunc(void) __attribute__((convergent));
2083 // Setting it as a C++11 attribute is also valid in a C++ program.
2084 // void convfunc(void) [[clang::convergent]];)reST";
2085
2086static const char AttrDoc_CoroAwaitElidable[] = R"reST(The ``[[clang::coro_await_elidable]]`` is a class attribute which can be
2087applied to a coroutine return type. It provides a hint to the compiler to apply
2088Heap Allocation Elision more aggressively.
2089
2090When a coroutine function returns such a type, a direct call expression therein
2091that returns a prvalue of a type attributed ``[[clang::coro_await_elidable]]``
2092is said to be under a safe elide context if one of the following is true:
2093- it is the immediate right-hand side operand to a co_await expression.
2094- it is an argument to a ``[[clang::coro_await_elidable_argument]]`` parameter
2095or parameter pack of another direct call expression under a safe elide context.
2096
2097Do note that the safe elide context applies only to the call expression itself,
2098and the context does not transitively include any of its subexpressions unless
2099exceptional rules of ``[[clang::coro_await_elidable_argument]]`` apply.
2100
2101The compiler performs heap allocation elision on call expressions under a safe
2102elide context, if the callee is a coroutine.
2103
2104Example:
2105
2106.. code-block:: c++
2107
2108 class [[clang::coro_await_elidable]] Task { ... };
2109
2110 Task foo();
2111 Task bar() {
2112 co_await foo(); // foo()'s coroutine frame on this line is elidable
2113 auto t = foo(); // foo()'s coroutine frame on this line is NOT elidable
2114 co_await t;
2115 }
2116
2117Such elision replaces the heap allocated activation frame of the callee coroutine
2118with a local variable within the enclosing braces in the caller's stack frame.
2119The local variable, like other variables in coroutines, may be collected into the
2120coroutine frame, which may be allocated on the heap. The behavior is undefined
2121if the caller coroutine is destroyed earlier than the callee coroutine.)reST";
2122
2123static const char AttrDoc_CoroAwaitElidableArgument[] = R"reST(The ``[[clang::coro_await_elidable_argument]]`` is a function parameter attribute.
2124It works in conjunction with ``[[clang::coro_await_elidable]]`` to propagate a
2125safe elide context to a parameter or parameter pack if the function is called
2126under a safe elide context.
2127
2128This is sometimes necessary on utility functions used to compose or modify the
2129behavior of a callee coroutine.
2130
2131Example:
2132
2133.. code-block:: c++
2134
2135 template <typename T>
2136 class [[clang::coro_await_elidable]] Task { ... };
2137
2138 template <typename... T>
2139 class [[clang::coro_await_elidable]] WhenAll { ... };
2140
2141 // `when_all` is a utility function that composes coroutines. It does not
2142 // need to be a coroutine to propagate.
2143 template <typename... T>
2144 WhenAll<T...> when_all([[clang::coro_await_elidable_argument]] Task<T> tasks...);
2145
2146 Task<int> foo();
2147 Task<int> bar();
2148 Task<void> example1() {
2149 // `when_all``, `foo``, and `bar` are all elide safe because `when_all` is
2150 // under a safe elide context and, thanks to the [[clang::coro_await_elidable_argument]]
2151 // attribute, such context is propagated to foo and bar.
2152 co_await when_all(foo(), bar());
2153 }
2154
2155 Task<void> example2() {
2156 // `when_all` and `bar` are elide safe. `foo` is not elide safe.
2157 auto f = foo();
2158 co_await when_all(f, bar());
2159 }
2160
2161
2162 Task<void> example3() {
2163 // None of the calls are elide safe.
2164 auto t = when_all(foo(), bar());
2165 co_await t;
2166 })reST";
2167
2168static const char AttrDoc_CoroDisableLifetimeBound[] = R"reST(The ``[[clang::coro_lifetimebound]]`` is a class attribute which can be applied
2169to a coroutine return type (`coro_return_type, coro_wrapper`_) (i.e.
2170it should also be annotated with ``[[clang::coro_return_type]]``).
2171
2172All parameters of a function are considered to be lifetime bound if the function returns a
2173coroutine return type (CRT) annotated with ``[[clang::coro_lifetimebound]]``.
2174This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2175with ``[[clang::coro_disable_lifetimebound]]`` function attribute .
2176See documentation of `lifetimebound`_ for details about lifetime bound analysis.
2177
2178
2179Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2180
2181For example,
2182
2183.. code-block:: c++
2184
2185 task<int> coro(const int& a) { co_return a + 1; }
2186 task<int> dangling_refs(int a) {
2187 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2188 auto foo = coro(1);
2189 // `coro` captures reference to local variable `a` which is destroyed after the return.
2190 return coro(a);
2191 }
2192
2193Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2194which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2195``[[clang::coro_lifetimebound]]``, then lifetime bound analysis would detect capturing reference to
2196temporaries or return address of a local variable.
2197
2198Both coroutines and coroutine wrappers are part of this analysis.
2199
2200.. code-block:: c++
2201
2202 template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2203 using promise_type = some_promise_type;
2204 };
2205
2206 Task<int> coro(const int& a) { co_return a + 1; }
2207 [[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2208 return a > b ? coro(a) : coro(b);
2209 }
2210 Task<int> temporary_reference() {
2211 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2212
2213 int a = 1;
2214 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2215
2216 co_return co_await coro(1); // fine.
2217 }
2218 [[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2219 return coro(a); // warning: returning address of stack variable `a`.
2220 }
2221
2222This analysis can be disabled for all calls to a particular function by annotating the function
2223with function attribute ``[[clang::coro_disable_lifetimebound]]``.
2224For example, this could be useful for coroutine wrappers which accept reference parameters
2225but do not pass them to the underlying coroutine or pass them by value.
2226
2227.. code-block:: c++
2228
2229 Task<int> coro(int a) { co_return a + 1; }
2230 [[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2231 return coro(a + 1);
2232 }
2233 void use() {
2234 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2235 })reST";
2236
2237static const char AttrDoc_CoroLifetimeBound[] = R"reST(The ``[[clang::coro_lifetimebound]]`` is a class attribute which can be applied
2238to a coroutine return type (`coro_return_type, coro_wrapper`_) (i.e.
2239it should also be annotated with ``[[clang::coro_return_type]]``).
2240
2241All parameters of a function are considered to be lifetime bound if the function returns a
2242coroutine return type (CRT) annotated with ``[[clang::coro_lifetimebound]]``.
2243This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2244with ``[[clang::coro_disable_lifetimebound]]`` function attribute .
2245See documentation of `lifetimebound`_ for details about lifetime bound analysis.
2246
2247
2248Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2249
2250For example,
2251
2252.. code-block:: c++
2253
2254 task<int> coro(const int& a) { co_return a + 1; }
2255 task<int> dangling_refs(int a) {
2256 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2257 auto foo = coro(1);
2258 // `coro` captures reference to local variable `a` which is destroyed after the return.
2259 return coro(a);
2260 }
2261
2262Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2263which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2264``[[clang::coro_lifetimebound]]``, then lifetime bound analysis would detect capturing reference to
2265temporaries or return address of a local variable.
2266
2267Both coroutines and coroutine wrappers are part of this analysis.
2268
2269.. code-block:: c++
2270
2271 template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2272 using promise_type = some_promise_type;
2273 };
2274
2275 Task<int> coro(const int& a) { co_return a + 1; }
2276 [[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2277 return a > b ? coro(a) : coro(b);
2278 }
2279 Task<int> temporary_reference() {
2280 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2281
2282 int a = 1;
2283 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2284
2285 co_return co_await coro(1); // fine.
2286 }
2287 [[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2288 return coro(a); // warning: returning address of stack variable `a`.
2289 }
2290
2291This analysis can be disabled for all calls to a particular function by annotating the function
2292with function attribute ``[[clang::coro_disable_lifetimebound]]``.
2293For example, this could be useful for coroutine wrappers which accept reference parameters
2294but do not pass them to the underlying coroutine or pass them by value.
2295
2296.. code-block:: c++
2297
2298 Task<int> coro(int a) { co_return a + 1; }
2299 [[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2300 return coro(a + 1);
2301 }
2302 void use() {
2303 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2304 })reST";
2305
2306static const char AttrDoc_CoroOnlyDestroyWhenComplete[] = R"reST(The `coro_only_destroy_when_complete` attribute should be marked on a C++ class. The coroutines
2307whose return type is marked with the attribute are assumed to be destroyed only after the coroutine has
2308reached the final suspend point.
2309
2310This is helpful for the optimizers to reduce the size of the destroy function for the coroutines.
2311
2312For example,
2313
2314.. code-block:: c++
2315
2316 A foo() {
2317 dtor d;
2318 co_await something();
2319 dtor d1;
2320 co_await something();
2321 dtor d2;
2322 co_return 43;
2323 }
2324
2325The compiler may generate the following pseudocode:
2326
2327.. code-block:: c++
2328
2329 void foo.destroy(foo.Frame *frame) {
2330 switch(frame->suspend_index()) {
2331 case 1:
2332 frame->d.~dtor();
2333 break;
2334 case 2:
2335 frame->d.~dtor();
2336 frame->d1.~dtor();
2337 break;
2338 case 3:
2339 frame->d.~dtor();
2340 frame->d1.~dtor();
2341 frame->d2.~dtor();
2342 break;
2343 default: // coroutine completed or haven't started
2344 break;
2345 }
2346
2347 frame->promise.~promise_type();
2348 delete frame;
2349 }
2350
2351The `foo.destroy()` function's purpose is to release all of the resources
2352initialized for the coroutine when it is destroyed in a suspended state.
2353However, if the coroutine is only ever destroyed at the final suspend state,
2354the rest of the conditions are superfluous.
2355
2356The user can use the `coro_only_destroy_when_complete` attributo suppress
2357generation of the other destruction cases, optimizing the above `foo.destroy` to:
2358
2359.. code-block:: c++
2360
2361 void foo.destroy(foo.Frame *frame) {
2362 frame->promise.~promise_type();
2363 delete frame;
2364 })reST";
2365
2366static const char AttrDoc_CoroReturnType[] = R"reST(The ``[[clang::coro_return_type]]`` attribute is used to help static analyzers to recognize
2367coroutines from the function signatures.
2368
2369The ``coro_return_type`` attribute should be marked on a C++ class to mark it as
2370a **coroutine return type (CRT)**.
2371
2372A function ``R func(P1, .., PN)`` has a coroutine return type (CRT) ``R`` if ``R``
2373is marked by ``[[clang::coro_return_type]]`` and ``R`` has a promise type associated to it
2374(i.e., std::coroutine_traits<R, P1, .., PN>::promise_type is a valid promise type).
2375
2376If the return type of a function is a ``CRT`` then the function must be a coroutine.
2377Otherwise the program is invalid. It is allowed for a non-coroutine to return a ``CRT``
2378if the function is marked with ``[[clang::coro_wrapper]]``.
2379
2380The ``[[clang::coro_wrapper]]`` attribute should be marked on a C++ function to mark it as
2381a **coroutine wrapper**. A coroutine wrapper is a function which returns a ``CRT``,
2382is not a coroutine itself and is marked with ``[[clang::coro_wrapper]]``.
2383
2384Clang will enforce that all functions that return a ``CRT`` are either coroutines or marked
2385with ``[[clang::coro_wrapper]]``. Clang will enforce this with an error.
2386
2387From a language perspective, it is not possible to differentiate between a coroutine and a
2388function returning a CRT by merely looking at the function signature.
2389
2390Coroutine wrappers, in particular, are susceptible to capturing
2391references to temporaries and other lifetime issues. This allows to avoid such lifetime
2392issues with coroutine wrappers.
2393
2394For example,
2395
2396.. code-block:: c++
2397
2398 // This is a CRT.
2399 template <typename T> struct [[clang::coro_return_type]] Task {
2400 using promise_type = some_promise_type;
2401 };
2402
2403 Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2404 Task<int> foo() { return increment(1); } // Error. foo is not a coroutine.
2405
2406 // Fine for a coroutine wrapper to return a CRT.
2407 [[clang::coro_wrapper]] Task<int> foo() { return increment(1); }
2408
2409 void bar() {
2410 // Invalid. This intantiates a function which returns a CRT but is not marked as
2411 // a coroutine wrapper.
2412 std::function<Task<int>(int)> f = increment;
2413 }
2414
2415Note: ``a_promise_type::get_return_object`` is exempted from this analysis as it is a necessary
2416implementation detail of any coroutine library.)reST";
2417
2418static const char AttrDoc_CoroWrapper[] = R"reST(The ``[[clang::coro_return_type]]`` attribute is used to help static analyzers to recognize
2419coroutines from the function signatures.
2420
2421The ``coro_return_type`` attribute should be marked on a C++ class to mark it as
2422a **coroutine return type (CRT)**.
2423
2424A function ``R func(P1, .., PN)`` has a coroutine return type (CRT) ``R`` if ``R``
2425is marked by ``[[clang::coro_return_type]]`` and ``R`` has a promise type associated to it
2426(i.e., std::coroutine_traits<R, P1, .., PN>::promise_type is a valid promise type).
2427
2428If the return type of a function is a ``CRT`` then the function must be a coroutine.
2429Otherwise the program is invalid. It is allowed for a non-coroutine to return a ``CRT``
2430if the function is marked with ``[[clang::coro_wrapper]]``.
2431
2432The ``[[clang::coro_wrapper]]`` attribute should be marked on a C++ function to mark it as
2433a **coroutine wrapper**. A coroutine wrapper is a function which returns a ``CRT``,
2434is not a coroutine itself and is marked with ``[[clang::coro_wrapper]]``.
2435
2436Clang will enforce that all functions that return a ``CRT`` are either coroutines or marked
2437with ``[[clang::coro_wrapper]]``. Clang will enforce this with an error.
2438
2439From a language perspective, it is not possible to differentiate between a coroutine and a
2440function returning a CRT by merely looking at the function signature.
2441
2442Coroutine wrappers, in particular, are susceptible to capturing
2443references to temporaries and other lifetime issues. This allows to avoid such lifetime
2444issues with coroutine wrappers.
2445
2446For example,
2447
2448.. code-block:: c++
2449
2450 // This is a CRT.
2451 template <typename T> struct [[clang::coro_return_type]] Task {
2452 using promise_type = some_promise_type;
2453 };
2454
2455 Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2456 Task<int> foo() { return increment(1); } // Error. foo is not a coroutine.
2457
2458 // Fine for a coroutine wrapper to return a CRT.
2459 [[clang::coro_wrapper]] Task<int> foo() { return increment(1); }
2460
2461 void bar() {
2462 // Invalid. This intantiates a function which returns a CRT but is not marked as
2463 // a coroutine wrapper.
2464 std::function<Task<int>(int)> f = increment;
2465 }
2466
2467Note: ``a_promise_type::get_return_object`` is exempted from this analysis as it is a necessary
2468implementation detail of any coroutine library.)reST";
2469
2470static const char AttrDoc_CountedBy[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
2471structure in C. The argument for the attribute is the name of a field member
2472holding the count of elements in the flexible array. This information can be
2473used to improve the results of the array bound sanitizer and the
2474``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
2475within the same non-anonymous, enclosing struct as the flexible array member.
2476
2477This example specifies that the flexible array member ``array`` has the number
2478of elements allocated for it in ``count``:
2479
2480.. code-block:: c
2481
2482 struct bar;
2483
2484 struct foo {
2485 size_t count;
2486 char other;
2487 struct bar *array[] __attribute__((counted_by(count)));
2488 };
2489
2490This establishes a relationship between ``array`` and ``count``. Specifically,
2491``array`` must have at least ``count`` number of elements available. It's the
2492user's responsibility to ensure that this relationship is maintained through
2493changes to the structure.
2494
2495In the following example, the allocated array erroneously has fewer elements
2496than what's specified by ``p->count``. This would result in an out-of-bounds
2497access not being detected.
2498
2499.. code-block:: c
2500
2501 #define SIZE_INCR 42
2502
2503 struct foo *p;
2504
2505 void foo_alloc(size_t count) {
2506 p = malloc(MAX(sizeof(struct foo),
2507 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2508 p->count = count + SIZE_INCR;
2509 }
2510
2511The next example updates ``p->count``, but breaks the relationship requirement
2512that ``p->array`` must have at least ``p->count`` number of elements available:
2513
2514.. code-block:: c
2515
2516 #define SIZE_INCR 42
2517
2518 struct foo *p;
2519
2520 void foo_alloc(size_t count) {
2521 p = malloc(MAX(sizeof(struct foo),
2522 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2523 p->count = count;
2524 }
2525
2526 void use_foo(int index, int val) {
2527 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
2528 p->array[index] = val; /* The sanitizer can't properly check this access. */
2529 }
2530
2531In this example, an update to ``p->count`` maintains the relationship
2532requirement:
2533
2534.. code-block:: c
2535
2536 void use_foo(int index, int val) {
2537 if (p->count == 0)
2538 return;
2539 --p->count;
2540 p->array[index] = val;
2541 })reST";
2542
2543static const char AttrDoc_CountedByOrNull[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
2544structure in C. The argument for the attribute is the name of a field member
2545holding the count of elements in the flexible array. This information can be
2546used to improve the results of the array bound sanitizer and the
2547``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
2548within the same non-anonymous, enclosing struct as the flexible array member.
2549
2550This example specifies that the flexible array member ``array`` has the number
2551of elements allocated for it in ``count``:
2552
2553.. code-block:: c
2554
2555 struct bar;
2556
2557 struct foo {
2558 size_t count;
2559 char other;
2560 struct bar *array[] __attribute__((counted_by(count)));
2561 };
2562
2563This establishes a relationship between ``array`` and ``count``. Specifically,
2564``array`` must have at least ``count`` number of elements available. It's the
2565user's responsibility to ensure that this relationship is maintained through
2566changes to the structure.
2567
2568In the following example, the allocated array erroneously has fewer elements
2569than what's specified by ``p->count``. This would result in an out-of-bounds
2570access not being detected.
2571
2572.. code-block:: c
2573
2574 #define SIZE_INCR 42
2575
2576 struct foo *p;
2577
2578 void foo_alloc(size_t count) {
2579 p = malloc(MAX(sizeof(struct foo),
2580 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2581 p->count = count + SIZE_INCR;
2582 }
2583
2584The next example updates ``p->count``, but breaks the relationship requirement
2585that ``p->array`` must have at least ``p->count`` number of elements available:
2586
2587.. code-block:: c
2588
2589 #define SIZE_INCR 42
2590
2591 struct foo *p;
2592
2593 void foo_alloc(size_t count) {
2594 p = malloc(MAX(sizeof(struct foo),
2595 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2596 p->count = count;
2597 }
2598
2599 void use_foo(int index, int val) {
2600 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
2601 p->array[index] = val; /* The sanitizer can't properly check this access. */
2602 }
2603
2604In this example, an update to ``p->count`` maintains the relationship
2605requirement:
2606
2607.. code-block:: c
2608
2609 void use_foo(int index, int val) {
2610 if (p->count == 0)
2611 return;
2612 --p->count;
2613 p->array[index] = val;
2614 })reST";
2615
2616static const char AttrDoc_DLLExport[] = R"reST(The ``__declspec(dllexport)`` attribute declares a variable, function, or
2617Objective-C interface to be exported from the module. It is available under the
2618``-fdeclspec`` flag for compatibility with various compilers. The primary use
2619is for COFF object files which explicitly specify what interfaces are available
2620for external use. See the dllexport_ documentation on MSDN for more
2621information.
2622
2623.. _dllexport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2624
2625static const char AttrDoc_DLLExportOnDecl[] = R"reST()reST";
2626
2627static const char AttrDoc_DLLExportStaticLocal[] = R"reST()reST";
2628
2629static const char AttrDoc_DLLImport[] = R"reST(The ``__declspec(dllimport)`` attribute declares a variable, function, or
2630Objective-C interface to be imported from an external module. It is available
2631under the ``-fdeclspec`` flag for compatibility with various compilers. The
2632primary use is for COFF object files which explicitly specify what interfaces
2633are imported from external modules. See the dllimport_ documentation on MSDN
2634for more information.
2635
2636Note that a dllimport function may still be inlined, if its definition is
2637available and it doesn't reference any non-dllimport functions or global
2638variables.
2639
2640.. _dllimport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2641
2642static const char AttrDoc_DLLImportStaticLocal[] = R"reST()reST";
2643
2644static const char AttrDoc_Deprecated[] = R"reST(The ``deprecated`` attribute can be applied to a function, a variable, or a
2645type. This is useful when identifying functions, variables, or types that are
2646expected to be removed in a future version of a program.
2647
2648Consider the function declaration for a hypothetical function ``f``:
2649
2650.. code-block:: c++
2651
2652 void f(void) __attribute__((deprecated("message", "replacement")));
2653
2654When spelled as ``__attribute__((deprecated))``, the deprecated attribute can have
2655two optional string arguments. The first one is the message to display when
2656emitting the warning; the second one enables the compiler to provide a Fix-It
2657to replace the deprecated name with a new name. Otherwise, when spelled as
2658``[[gnu::deprecated]]`` or ``[[deprecated]]``, the attribute can have one optional
2659string argument which is the message to display when emitting the warning.)reST";
2660
2661static const char AttrDoc_Destructor[] = R"reST(The ``constructor`` attribute causes the function to be called before entering
2662``main()``, and the ``destructor`` attribute causes the function to be called
2663after returning from ``main()`` or when the ``exit()`` function has been
2664called. Note, ``quick_exit()``, ``_Exit()``, and ``abort()`` prevent a function
2665marked ``destructor`` from being called.
2666
2667The constructor or destructor function should not accept any arguments and its
2668return type should be ``void``.
2669
2670The attributes accept an optional argument used to specify the priority order
2671in which to execute constructor and destructor functions. The priority is
2672given as an integer constant expression between 101 and 65535 (inclusive).
2673Priorities outside of that range are reserved for use by the implementation. A
2674lower value indicates a higher priority of initialization. Note that only the
2675relative ordering of values is important. For example:
2676
2677.. code-block:: c++
2678
2679 __attribute__((constructor(200))) void foo(void);
2680 __attribute__((constructor(101))) void bar(void);
2681
2682``bar()`` will be called before ``foo()``, and both will be called before
2683``main()``. If no argument is given to the ``constructor`` or ``destructor``
2684attribute, they default to the value ``65535``.)reST";
2685
2686static const char AttrDoc_DeviceKernel[] = R"reST(These attributes specify that the function represents a kernel for device offloading.
2687The specific semantics depend on the offloading language, target, and attribute spelling.
2688Here is a code example using the attribute to mark a function as a kernel:
2689
2690.. code-block:: c++
2691
2692 [[clang::device_kernel]] int foo(int x) { return ++x; })reST";
2693
2694static const char AttrDoc_DiagnoseAsBuiltin[] = R"reST(The ``diagnose_as_builtin`` attribute indicates that Fortify diagnostics are to
2695be applied to the declared function as if it were the function specified by the
2696attribute. The builtin function whose diagnostics are to be mimicked should be
2697given. In addition, the order in which arguments should be applied must also
2698be given.
2699
2700For example, the attribute can be used as follows.
2701
2702.. code-block:: c
2703
2704 __attribute__((diagnose_as_builtin(__builtin_memset, 3, 2, 1)))
2705 void *mymemset(int n, int c, void *s) {
2706 // ...
2707 }
2708
2709This indicates that calls to ``mymemset`` should be diagnosed as if they were
2710calls to ``__builtin_memset``. The arguments ``3, 2, 1`` indicate by index the
2711order in which arguments of ``mymemset`` should be applied to
2712``__builtin_memset``. The third argument should be applied first, then the
2713second, and then the first. Thus (when Fortify warnings are enabled) the call
2714``mymemset(n, c, s)`` will diagnose overflows as if it were the call
2715``__builtin_memset(s, c, n)``.
2716
2717For variadic functions, the variadic arguments must come in the same order as
2718they would to the builtin function, after all normal arguments. For instance,
2719to diagnose a new function as if it were `sscanf`, we can use the attribute as
2720follows.
2721
2722.. code-block:: c
2723
2724 __attribute__((diagnose_as_builtin(sscanf, 1, 2)))
2725 int mysscanf(const char *str, const char *format, ...) {
2726 // ...
2727 }
2728
2729Then the call `mysscanf("abc def", "%4s %4s", buf1, buf2)` will be diagnosed as
2730if it were the call `sscanf("abc def", "%4s %4s", buf1, buf2)`.
2731
2732This attribute cannot be applied to non-static member functions.)reST";
2733
2734static const char AttrDoc_DiagnoseIf[] = R"reST(The ``diagnose_if`` attribute can be placed on function declarations to emit
2735warnings or errors at compile-time if calls to the attributed function meet
2736certain user-defined criteria. For example:
2737
2738.. code-block:: c
2739
2740 int abs(int a)
2741 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning")));
2742 int must_abs(int a)
2743 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error")));
2744
2745 int val = abs(1); // warning: Redundant abs call
2746 int val2 = must_abs(1); // error: Redundant abs call
2747 int val3 = abs(val);
2748 int val4 = must_abs(val); // Because run-time checks are not emitted for
2749 // diagnose_if attributes, this executes without
2750 // issue.
2751
2752
2753``diagnose_if`` is closely related to ``enable_if``, with a few key differences:
2754
2755* Overload resolution is not aware of ``diagnose_if`` attributes: they're
2756 considered only after we select the best candidate from a given candidate set.
2757* Function declarations that differ only in their ``diagnose_if`` attributes are
2758 considered to be redeclarations of the same function (not overloads).
2759* If the condition provided to ``diagnose_if`` cannot be evaluated, no
2760 diagnostic will be emitted.
2761
2762Otherwise, ``diagnose_if`` is essentially the logical negation of ``enable_if``.
2763
2764As a result of bullet number two, ``diagnose_if`` attributes will stack on the
2765same function. For example:
2766
2767.. code-block:: c
2768
2769 int foo() __attribute__((diagnose_if(1, "diag1", "warning")));
2770 int foo() __attribute__((diagnose_if(1, "diag2", "warning")));
2771
2772 int bar = foo(); // warning: diag1
2773 // warning: diag2
2774 int (*fooptr)(void) = foo; // warning: diag1
2775 // warning: diag2
2776
2777 constexpr int supportsAPILevel(int N) { return N < 5; }
2778 int baz(int a)
2779 __attribute__((diagnose_if(!supportsAPILevel(10),
2780 "Upgrade to API level 10 to use baz", "error")));
2781 int baz(int a)
2782 __attribute__((diagnose_if(!a, "0 is not recommended.", "warning")));
2783
2784 int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz
2785 int v = baz(0); // error: Upgrade to API level 10 to use baz
2786
2787Query for this feature with ``__has_attribute(diagnose_if)``.)reST";
2788
2789static const char AttrDoc_DisableSanitizerInstrumentation[] = R"reST(Use the ``disable_sanitizer_instrumentation`` attribute on a function,
2790Objective-C method, or global variable, to specify that no sanitizer
2791instrumentation should be applied.
2792
2793This is not the same as ``__attribute__((no_sanitize(...)))``, which depending
2794on the tool may still insert instrumentation to prevent false positive reports.)reST";
2795
2796static const char AttrDoc_DisableTailCalls[] = R"reST(The ``disable_tail_calls`` attribute instructs the backend to not perform tail
2797call optimization inside the marked function.
2798
2799For example:
2800
2801 .. code-block:: c
2802
2803 int callee(int);
2804
2805 int foo(int a) __attribute__((disable_tail_calls)) {
2806 return callee(a); // This call is not tail-call optimized.
2807 }
2808
2809Marking virtual functions as ``disable_tail_calls`` is legal.
2810
2811 .. code-block:: c++
2812
2813 int callee(int);
2814
2815 class Base {
2816 public:
2817 [[clang::disable_tail_calls]] virtual int foo1() {
2818 return callee(); // This call is not tail-call optimized.
2819 }
2820 };
2821
2822 class Derived1 : public Base {
2823 public:
2824 int foo1() override {
2825 return callee(); // This call is tail-call optimized.
2826 }
2827 };)reST";
2828
2829static const char AttrDoc_EmptyBases[] = R"reST(The empty_bases attribute permits the compiler to utilize the
2830empty-base-optimization more frequently.
2831This attribute only applies to struct, class, and union types.
2832It is only supported when using the Microsoft C++ ABI.)reST";
2833
2834static const char AttrDoc_EnableIf[] = R"reST(.. Note:: Some features of this attribute are experimental. The meaning of
2835 multiple enable_if attributes on a single declaration is subject to change in
2836 a future version of clang. Also, the ABI is not standardized and the name
2837 mangling may change in future versions. To avoid that, use asm labels.
2838
2839The ``enable_if`` attribute can be placed on function declarations to control
2840which overload is selected based on the values of the function's arguments.
2841When combined with the ``overloadable`` attribute, this feature is also
2842available in C.
2843
2844.. code-block:: c++
2845
2846 int isdigit(int c);
2847 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")));
2848
2849 void foo(char c) {
2850 isdigit(c);
2851 isdigit(10);
2852 isdigit(-10); // results in a compile-time error.
2853 }
2854
2855The enable_if attribute takes two arguments, the first is an expression written
2856in terms of the function parameters, the second is a string explaining why this
2857overload candidate could not be selected to be displayed in diagnostics. The
2858expression is part of the function signature for the purposes of determining
2859whether it is a redeclaration (following the rules used when determining
2860whether a C++ template specialization is ODR-equivalent), but is not part of
2861the type.
2862
2863The enable_if expression is evaluated as if it were the body of a
2864bool-returning constexpr function declared with the arguments of the function
2865it is being applied to, then called with the parameters at the call site. If the
2866result is false or could not be determined through constant expression
2867evaluation, then this overload will not be chosen and the provided string may
2868be used in a diagnostic if the compile fails as a result.
2869
2870Because the enable_if expression is an unevaluated context, there are no global
2871state changes, nor the ability to pass information from the enable_if
2872expression to the function body. For example, suppose we want calls to
2873strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
2874strbuf) only if the size of strbuf can be determined:
2875
2876.. code-block:: c++
2877
2878 __attribute__((always_inline))
2879 static inline size_t strnlen(const char *s, size_t maxlen)
2880 __attribute__((overloadable))
2881 __attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
2882 "chosen when the buffer size is known but 'maxlen' is not")))
2883 {
2884 return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
2885 }
2886
2887Multiple enable_if attributes may be applied to a single declaration. In this
2888case, the enable_if expressions are evaluated from left to right in the
2889following manner. First, the candidates whose enable_if expressions evaluate to
2890false or cannot be evaluated are discarded. If the remaining candidates do not
2891share ODR-equivalent enable_if expressions, the overload resolution is
2892ambiguous. Otherwise, enable_if overload resolution continues with the next
2893enable_if attribute on the candidates that have not been discarded and have
2894remaining enable_if attributes. In this way, we pick the most specific
2895overload out of a number of viable overloads using enable_if.
2896
2897.. code-block:: c++
2898
2899 void f() __attribute__((enable_if(true, ""))); // #1
2900 void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2
2901
2902 void g(int i, int j) __attribute__((enable_if(i, ""))); // #1
2903 void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2
2904
2905In this example, a call to f() is always resolved to #2, as the first enable_if
2906expression is ODR-equivalent for both declarations, but #1 does not have another
2907enable_if expression to continue evaluating, so the next round of evaluation has
2908only a single candidate. In a call to g(1, 1), the call is ambiguous even though
2909#2 has more enable_if attributes, because the first enable_if expressions are
2910not ODR-equivalent.
2911
2912Query for this feature with ``__has_attribute(enable_if)``.
2913
2914Note that functions with one or more ``enable_if`` attributes may not have
2915their address taken, unless all of the conditions specified by said
2916``enable_if`` are constants that evaluate to ``true``. For example:
2917
2918.. code-block:: c
2919
2920 const int TrueConstant = 1;
2921 const int FalseConstant = 0;
2922 int f(int a) __attribute__((enable_if(a > 0, "")));
2923 int g(int a) __attribute__((enable_if(a == 0 || a != 0, "")));
2924 int h(int a) __attribute__((enable_if(1, "")));
2925 int i(int a) __attribute__((enable_if(TrueConstant, "")));
2926 int j(int a) __attribute__((enable_if(FalseConstant, "")));
2927
2928 void fn() {
2929 int (*ptr)(int);
2930 ptr = &f; // error: 'a > 0' is not always true
2931 ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant
2932 ptr = &h; // OK: 1 is a truthy constant
2933 ptr = &i; // OK: 'TrueConstant' is a truthy constant
2934 ptr = &j; // error: 'FalseConstant' is a constant, but not truthy
2935 }
2936
2937Because ``enable_if`` evaluation happens during overload resolution,
2938``enable_if`` may give unintuitive results when used with templates, depending
2939on when overloads are resolved. In the example below, clang will emit a
2940diagnostic about no viable overloads for ``foo`` in ``bar``, but not in ``baz``:
2941
2942.. code-block:: c++
2943
2944 double foo(int i) __attribute__((enable_if(i > 0, "")));
2945 void *foo(int i) __attribute__((enable_if(i <= 0, "")));
2946 template <int I>
2947 auto bar() { return foo(I); }
2948
2949 template <typename T>
2950 auto baz() { return foo(T::number); }
2951
2952 struct WithNumber { constexpr static int number = 1; };
2953 void callThem() {
2954 bar<sizeof(WithNumber)>();
2955 baz<WithNumber>();
2956 }
2957
2958This is because, in ``bar``, ``foo`` is resolved prior to template
2959instantiation, so the value for ``I`` isn't known (thus, both ``enable_if``
2960conditions for ``foo`` fail). However, in ``baz``, ``foo`` is resolved during
2961template instantiation, so the value for ``T::number`` is known.)reST";
2962
2963static const char AttrDoc_EnforceTCB[] = R"reST(The ``enforce_tcb`` attribute can be placed on functions to enforce that a
2964 trusted compute base (TCB) does not call out of the TCB. This generates a
2965 warning every time a function not marked with an ``enforce_tcb`` attribute is
2966 called from a function with the ``enforce_tcb`` attribute. A function may be a
2967 part of multiple TCBs. Invocations through function pointers are currently
2968 not checked. Builtins are considered to a part of every TCB.
2969
2970 - ``enforce_tcb(Name)`` indicates that this function is a part of the TCB named ``Name``)reST";
2971
2972static const char AttrDoc_EnforceTCBLeaf[] = R"reST(The ``enforce_tcb_leaf`` attribute satisfies the requirement enforced by
2973 ``enforce_tcb`` for the marked function to be in the named TCB but does not
2974 continue to check the functions called from within the leaf function.
2975
2976 - ``enforce_tcb_leaf(Name)`` indicates that this function is a part of the TCB named ``Name``)reST";
2977
2978static const char AttrDoc_EnumExtensibility[] = R"reST(Attribute ``enum_extensibility`` is used to distinguish between enum definitions
2979that are extensible and those that are not. The attribute can take either
2980``closed`` or ``open`` as an argument. ``closed`` indicates a variable of the
2981enum type takes a value that corresponds to one of the enumerators listed in the
2982enum definition or, when the enum is annotated with ``flag_enum``, a value that
2983can be constructed using values corresponding to the enumerators. ``open``
2984indicates a variable of the enum type can take any values allowed by the
2985standard and instructs clang to be more lenient when issuing warnings.
2986
2987.. code-block:: c
2988
2989 enum __attribute__((enum_extensibility(closed))) ClosedEnum {
2990 A0, A1
2991 };
2992
2993 enum __attribute__((enum_extensibility(open))) OpenEnum {
2994 B0, B1
2995 };
2996
2997 enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum {
2998 C0 = 1 << 0, C1 = 1 << 1
2999 };
3000
3001 enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum {
3002 D0 = 1 << 0, D1 = 1 << 1
3003 };
3004
3005 void foo1() {
3006 enum ClosedEnum ce;
3007 enum OpenEnum oe;
3008 enum ClosedFlagEnum cfe;
3009 enum OpenFlagEnum ofe;
3010
3011 ce = A1; // no warnings
3012 ce = 100; // warning issued
3013 oe = B1; // no warnings
3014 oe = 100; // no warnings
3015 cfe = C0 | C1; // no warnings
3016 cfe = C0 | C1 | 4; // warning issued
3017 ofe = D0 | D1; // no warnings
3018 ofe = D0 | D1 | 4; // no warnings
3019 })reST";
3020
3021static const char AttrDoc_Error[] = R"reST(The ``error`` and ``warning`` function attributes can be used to specify a
3022custom diagnostic to be emitted when a call to such a function is not
3023eliminated via optimizations. This can be used to create compile time
3024assertions that depend on optimizations, while providing diagnostics
3025pointing to precise locations of the call site in the source.
3026
3027.. code-block:: c++
3028
3029 __attribute__((warning("oh no"))) void dontcall();
3030 void foo() {
3031 if (someCompileTimeAssertionThatsTrue)
3032 dontcall(); // Warning
3033
3034 dontcall(); // Warning
3035
3036 if (someCompileTimeAssertionThatsFalse)
3037 dontcall(); // No Warning
3038 sizeof(dontcall()); // No Warning
3039 }
3040
3041When the call occurs through inlined functions, the
3042``-fdiagnostics-show-inlining-chain`` option can be used to show the
3043inlining chain that led to the call. This helps identify which call site
3044triggered the diagnostic when the attributed function is called from
3045multiple locations through inline functions.
3046
3047When enabled, this option automatically uses debug info for accurate source
3048locations if available (``-gline-directives-only`` (implicitly enabled at
3049``-g1``) or higher), or falls back to a heuristic based on metadata tracking.
3050When falling back, a note is emitted suggesting ``-gline-directives-only`` for
3051more accurate locations.)reST";
3052
3053static const char AttrDoc_ExcludeFromExplicitInstantiation[] = R"reST(The ``exclude_from_explicit_instantiation`` attribute opts-out a member of a
3054class template from being part of explicit template instantiations of that
3055class template. This means that an explicit instantiation will not instantiate
3056members of the class template marked with the attribute, but also that code
3057where an extern template declaration of the enclosing class template is visible
3058will not take for granted that an external instantiation of the class template
3059would provide those members (which would otherwise be a link error, since the
3060explicit instantiation won't provide those members). For example, let's say we
3061don't want the ``data()`` method to be part of libc++'s ABI. To make sure it
3062is not exported from the dylib, we give it hidden visibility:
3063
3064 .. code-block:: c++
3065
3066 // in <string>
3067 template <class CharT>
3068 class basic_string {
3069 public:
3070 __attribute__((__visibility__("hidden")))
3071 const value_type* data() const noexcept { ... }
3072 };
3073
3074 template class basic_string<char>;
3075
3076Since an explicit template instantiation declaration for ``basic_string<char>``
3077is provided, the compiler is free to assume that ``basic_string<char>::data()``
3078will be provided by another translation unit, and it is free to produce an
3079external call to this function. However, since ``data()`` has hidden visibility
3080and the explicit template instantiation is provided in a shared library (as
3081opposed to simply another translation unit), ``basic_string<char>::data()``
3082won't be found and a link error will ensue. This happens because the compiler
3083assumes that ``basic_string<char>::data()`` is part of the explicit template
3084instantiation declaration, when it really isn't. To tell the compiler that
3085``data()`` is not part of the explicit template instantiation declaration, the
3086``exclude_from_explicit_instantiation`` attribute can be used:
3087
3088 .. code-block:: c++
3089
3090 // in <string>
3091 template <class CharT>
3092 class basic_string {
3093 public:
3094 __attribute__((__visibility__("hidden")))
3095 __attribute__((exclude_from_explicit_instantiation))
3096 const value_type* data() const noexcept { ... }
3097 };
3098
3099 template class basic_string<char>;
3100
3101Now, the compiler won't assume that ``basic_string<char>::data()`` is provided
3102externally despite there being an explicit template instantiation declaration:
3103the compiler will implicitly instantiate ``basic_string<char>::data()`` in the
3104TUs where it is used.
3105
3106This attribute can be used on static and non-static member functions of class
3107templates, static data members of class templates and member classes of class
3108templates.
3109
3110**Interaction with __declspec(dllexport/dllimport)**
3111
3112For a DLL platform (i.e., Windows), this attribute also means "this member will
3113never be exported or imported". Despite its name, this semantics applies to
3114implicit instantiations and non-template entities as well.
3115
3116 .. code-block:: c++
3117
3118 // in <exception>
3119 class __declspec(dllimport) nested_exception {
3120 ...
3121 public:
3122 __attribute__((exclude_from_explicit_instantiation))
3123 exception_ptr nested_ptr() const noexcept { ... }
3124 };
3125
3126In this case, ``nested_exception::nested_ptr`` will never be attempted to be
3127imported.)reST";
3128
3129static const char AttrDoc_ExplicitInit[] = R"reST(The ``clang::require_explicit_initialization`` attribute indicates that a
3130field of an aggregate must be initialized explicitly by the user when an object
3131of the aggregate type is constructed. The attribute supports both C and C++,
3132but its usage is invalid on non-aggregates.
3133
3134Note that this attribute is *not* a memory safety feature, and is *not* intended
3135to guard against use of uninitialized memory.
3136
3137Rather, it is intended for use in "parameter-objects", used to simulate,
3138for example, the passing of named parameters.
3139Except inside unevaluated contexts, the attribute generates a warning when
3140explicit initializers for such variables are not provided (this occurs
3141regardless of whether any in-class field initializers exist):
3142
3143.. code-block:: c++
3144
3145 struct Buffer {
3146 void *address [[clang::require_explicit_initialization]];
3147 size_t length [[clang::require_explicit_initialization]] = 0;
3148 };
3149
3150 struct ArrayIOParams {
3151 size_t count [[clang::require_explicit_initialization]];
3152 size_t element_size [[clang::require_explicit_initialization]];
3153 int flags = 0;
3154 };
3155
3156 size_t ReadArray(FILE *file, struct Buffer buffer,
3157 struct ArrayIOParams params);
3158
3159 int main() {
3160 unsigned int buf[512];
3161 ReadArray(stdin, {
3162 buf
3163 // warning: field 'length' is not explicitly initialized
3164 }, {
3165 .count = sizeof(buf) / sizeof(*buf),
3166 // warning: field 'element_size' is not explicitly initialized
3167 // (Note that a missing initializer for 'flags' is not diagnosed, because
3168 // the field is not marked as requiring explicit initialization.)
3169 });
3170 })reST";
3171
3172static const char AttrDoc_ExtVectorType[] = R"reST(The ``ext_vector_type(N)`` attribute specifies that a type is a vector with N
3173elements, directly mapping to an LLVM vector type. Originally from OpenCL, it
3174allows element access the array subscript operator ``[]``, ``sN`` where N is
3175a hexadecimal value, or ``x, y, z, w`` for graphics-style indexing.
3176This attribute enables efficient SIMD operations and is usable in
3177general-purpose code.
3178
3179.. code-block:: c++
3180
3181 template <typename T, uint32_t N>
3182 constexpr T simd_reduce(T [[clang::ext_vector_type(N)]] v) {
3183 static_assert((N & (N - 1)) == 0, "N must be a power of two");
3184 if constexpr (N == 1)
3185 return v[0];
3186 else
3187 return simd_reduce<T, N / 2>(v.hi + v.lo);
3188 }
3189
3190The vector type also supports swizzling up to sixteen elements. This can be done
3191using the object accessors. The OpenCL documentation lists all of the accepted
3192values.
3193
3194.. code-block:: c++
3195
3196 using f16_x16 = _Float16 __attribute__((ext_vector_type(16)));
3197
3198 f16_x16 reverse(f16_x16 v) { return v.sfedcba9876543210; }
3199
3200See the OpenCL documentation for some more complete examples.)reST";
3201
3202static const char AttrDoc_ExternalSourceSymbol[] = R"reST(The ``external_source_symbol`` attribute specifies that a declaration originates
3203from an external source and describes the nature of that source.
3204
3205The fact that Clang is capable of recognizing declarations that were defined
3206externally can be used to provide better tooling support for mixed-language
3207projects or projects that rely on auto-generated code. For instance, an IDE that
3208uses Clang and that supports mixed-language projects can use this attribute to
3209provide a correct 'jump-to-definition' feature. For a concrete example,
3210consider a protocol that's defined in a Swift file:
3211
3212.. code-block:: swift
3213
3214 @objc public protocol SwiftProtocol {
3215 func method()
3216 }
3217
3218This protocol can be used from Objective-C code by including a header file that
3219was generated by the Swift compiler. The declarations in that header can use
3220the ``external_source_symbol`` attribute to make Clang aware of the fact
3221that ``SwiftProtocol`` actually originates from a Swift module:
3222
3223.. code-block:: objc
3224
3225 __attribute__((external_source_symbol(language="Swift",defined_in="module")))
3226 @protocol SwiftProtocol
3227 @required
3228 - (void) method;
3229 @end
3230
3231Consequently, when 'jump-to-definition' is performed at a location that
3232references ``SwiftProtocol``, the IDE can jump to the original definition in
3233the Swift source file rather than jumping to the Objective-C declaration in the
3234auto-generated header file.
3235
3236The ``external_source_symbol`` attribute is a comma-separated list that includes
3237clauses that describe the origin and the nature of the particular declaration.
3238Those clauses can be:
3239
3240language=\ *string-literal*
3241 The name of the source language in which this declaration was defined.
3242
3243defined_in=\ *string-literal*
3244 The name of the source container in which the declaration was defined. The
3245 exact definition of source container is language-specific, e.g. Swift's
3246 source containers are modules, so ``defined_in`` should specify the Swift
3247 module name.
3248
3249USR=\ *string-literal*
3250 String that specifies a unified symbol resolution (USR) value for this
3251 declaration. USR string uniquely identifies this particular declaration, and
3252 is typically used when constructing an index of a codebase.
3253 The USR value in this attribute is expected to be generated by an external
3254 compiler that compiled the native declaration using its original source
3255 language. The exact format of the USR string and its other attributes
3256 are determined by the specification of this declaration's source language.
3257 When not specified, Clang's indexer will use the Clang USR for this symbol.
3258 User can query to see if Clang supports the use of the ``USR`` clause in
3259 the ``external_source_symbol`` attribute with
3260 ``__has_attribute(external_source_symbol) >= 20230206``.
3261
3262generated_declaration
3263 This declaration was automatically generated by some tool.
3264
3265The clauses can be specified in any order. The clauses that are listed above are
3266all optional, but the attribute has to have at least one clause.)reST";
3267
3268static const char AttrDoc_FallThrough[] = R"reST(The ``fallthrough`` (or ``clang::fallthrough``) attribute is used
3269to annotate intentional fall-through
3270between switch labels. It can only be applied to a null statement placed at a
3271point of execution between any statement and the next switch label. It is
3272common to mark these places with a specific comment, but this attribute is
3273meant to replace comments with a more strict annotation, which can be checked
3274by the compiler. This attribute doesn't change semantics of the code and can
3275be used wherever an intended fall-through occurs. It is designed to mimic
3276control-flow statements like ``break;``, so it can be placed in most places
3277where ``break;`` can, but only if there are no statements on the execution path
3278between it and the next switch label.
3279
3280By default, Clang does not warn on unannotated fallthrough from one ``switch``
3281case to another. Diagnostics on fallthrough without a corresponding annotation
3282can be enabled with the ``-Wimplicit-fallthrough`` argument.
3283
3284Here is an example:
3285
3286.. code-block:: c++
3287
3288 // compile with -Wimplicit-fallthrough
3289 switch (n) {
3290 case 22:
3291 case 33: // no warning: no statements between case labels
3292 f();
3293 case 44: // warning: unannotated fall-through
3294 g();
3295 [[clang::fallthrough]];
3296 case 55: // no warning
3297 if (x) {
3298 h();
3299 break;
3300 }
3301 else {
3302 i();
3303 [[clang::fallthrough]];
3304 }
3305 case 66: // no warning
3306 p();
3307 [[clang::fallthrough]]; // warning: fallthrough annotation does not
3308 // directly precede case label
3309 q();
3310 case 77: // warning: unannotated fall-through
3311 r();
3312 })reST";
3313
3314static const char AttrDoc_FastCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
3315function to use ECX and EDX as register parameters and clear parameters off of
3316the stack on return. This convention does not support variadic calls or
3317unprototyped functions in C, and has no effect on x86_64 targets. This calling
3318convention is supported primarily for compatibility with existing code. Users
3319seeking register parameters should use the ``regparm`` attribute, which does
3320not require callee-cleanup. See the documentation for `__fastcall`_ on MSDN.
3321
3322.. _`__fastcall`: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx)reST";
3323
3324static const char AttrDoc_Final[] = R"reST()reST";
3325
3326static const char AttrDoc_FlagEnum[] = R"reST(This attribute can be added to an enumerator to signal to the compiler that it
3327is intended to be used as a flag type. This will cause the compiler to assume
3328that the range of the type includes all of the values that you can get by
3329manipulating bits of the enumerator when issuing warnings.)reST";
3330
3331static const char AttrDoc_Flatten[] = R"reST(The ``flatten`` attribute causes calls within the attributed function to
3332be inlined unless it is impossible to do so, for example if the body of the
3333callee is unavailable or if the callee has the ``noinline`` attribute.)reST";
3334
3335static const char AttrDoc_Format[] = R"reST(Clang supports the ``format`` attribute, which indicates that the function
3336accepts (among other possibilities) a ``printf`` or ``scanf``-like format string
3337and corresponding arguments or a ``va_list`` that contains these arguments.
3338
3339Please see `GCC documentation about format attribute
3340<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details
3341about attribute syntax.
3342
3343Clang implements two kinds of checks with this attribute.
3344
3345#. Clang checks that the function with the ``format`` attribute is called with
3346 a format string that uses format specifiers that are allowed, and that
3347 arguments match the format string. This is the ``-Wformat`` warning, it is
3348 on by default.
3349
3350#. Clang checks that the format string argument is a literal string. This is
3351 the ``-Wformat-nonliteral`` warning, it is off by default.
3352
3353 Clang implements this mostly the same way as GCC, but there is a difference
3354 for functions that accept a ``va_list`` argument (for example, ``vprintf``).
3355 GCC does not emit ``-Wformat-nonliteral`` warning for calls to such
3356 functions. Clang does not warn if the format string comes from a function
3357 parameter, where the function is annotated with a compatible attribute,
3358 otherwise it warns. For example:
3359
3360 .. code-block:: c
3361
3362 __attribute__((__format__ (__scanf__, 1, 3)))
3363 void foo(const char* s, char *buf, ...) {
3364 va_list ap;
3365 va_start(ap, buf);
3366
3367 vprintf(s, ap); // warning: format string is not a string literal
3368 }
3369
3370 In this case we warn because ``s`` contains a format string for a
3371 ``scanf``-like function, but it is passed to a ``printf``-like function.
3372
3373 If the attribute is removed, clang still warns, because the format string is
3374 not a string literal.
3375
3376 Another example:
3377
3378 .. code-block:: c
3379
3380 __attribute__((__format__ (__printf__, 1, 3)))
3381 void foo(const char* s, char *buf, ...) {
3382 va_list ap;
3383 va_start(ap, buf);
3384
3385 vprintf(s, ap); // warning
3386 }
3387
3388 In this case Clang does not warn because the format string ``s`` and
3389 the corresponding arguments are annotated. If the arguments are
3390 incorrect, the caller of ``foo`` will receive a warning.
3391
3392As an extension to GCC's behavior, Clang accepts the ``format`` attribute on
3393non-variadic functions. Clang checks non-variadic format functions for the same
3394classes of issues that can be found on variadic functions, as controlled by the
3395same warning flags, except that the types of formatted arguments is forced by
3396the function signature. For example:
3397
3398.. code-block:: c
3399
3400 __attribute__((__format__(__printf__, 1, 2)))
3401 void fmt(const char *s, const char *a, int b);
3402
3403 void bar(void) {
3404 fmt("%s %i", "hello", 123); // OK
3405 fmt("%i %g", "hello", 123); // warning: arguments don't match format
3406 extern const char *fmt;
3407 fmt(fmt, "hello", 123); // warning: format string is not a string literal
3408 }
3409
3410When using the format attribute on a variadic function, the first data parameter
3411_must_ be the index of the ellipsis in the parameter list. Clang will generate
3412a diagnostic otherwise, as it wouldn't be possible to forward that argument list
3413to `printf`-family functions. For instance, this is an error:
3414
3415.. code-block:: c
3416
3417 __attribute__((__format__(__printf__, 1, 2)))
3418 void fmt(const char *s, int b, ...);
3419 // ^ error: format attribute parameter 3 is out of bounds
3420 // (must be __printf__, 1, 3)
3421
3422Using the ``format`` attribute on a non-variadic function emits a GCC
3423compatibility diagnostic.)reST";
3424
3425static const char AttrDoc_FormatArg[] = R"reST(No documentation.)reST";
3426
3427static const char AttrDoc_FormatMatches[] = R"reST(The ``format`` attribute is the basis for the enforcement of diagnostics in the
3428``-Wformat`` family, but it only handles the case where the format string is
3429passed along with the arguments it is going to format. It cannot handle the case
3430where the format string and the format arguments are passed separately from each
3431other. For instance:
3432
3433.. code-block:: c
3434
3435 static const char *first_name;
3436 static double todays_temperature;
3437 static int wind_speed;
3438
3439 void say_hi(const char *fmt) {
3440 printf(fmt, first_name, todays_temperature);
3441 // ^ warning: format string is not a string literal
3442 printf(fmt, first_name, wind_speed);
3443 // ^ warning: format string is not a string literal
3444 }
3445
3446 int main() {
3447 say_hi("hello %s, it is %g degrees outside");
3448 say_hi("hello %s, it is %d degrees outside!");
3449 // ^ no diagnostic, but %d cannot format doubles
3450 }
3451
3452In this example, ``fmt`` is expected to format a ``const char *`` and a
3453``double``, but these values are not passed to ``say_hi``. Without the
3454``format`` attribute (which cannot apply in this case), the -Wformat-nonliteral
3455diagnostic unnecessarily triggers in the body of ``say_hi``, and incorrect
3456``say_hi`` call sites do not trigger a diagnostic.
3457
3458To complement the ``format`` attribute, Clang also defines the
3459``format_matches`` attribute. Its syntax is similar to the ``format``
3460attribute's, but instead of taking the index of the first formatted value
3461argument, it takes a C string literal with the expected specifiers:
3462
3463.. code-block:: c
3464
3465 static const char *first_name;
3466 static double todays_temperature;
3467 static int wind_speed;
3468
3469 __attribute__((__format_matches__(printf, 1, "%s %g")))
3470 void say_hi(const char *fmt) {
3471 printf(fmt, first_name, todays_temperature); // no dignostic
3472 printf(fmt, first_name, wind_speed); // warning: format specifies type 'int' but the argument has type 'double'
3473 }
3474
3475 int main() {
3476 say_hi("hello %s, it is %g degrees outside");
3477 say_hi("it is %g degrees outside, have a good day %s!");
3478 // warning: format specifies 'double' where 'const char *' is required
3479 // warning: format specifies 'const char *' where 'double' is required
3480 }
3481
3482The third argument to ``format_matches`` is expected to evaluate to a **C string
3483literal** even when the format string would normally be a different type for the
3484given flavor, like a ``CFStringRef`` or a ``NSString *``.
3485
3486The only requirement on the format string literal is that it has specifiers
3487that are compatible with the arguments that will be used. It can contain
3488arbitrary non-format characters. For instance, for the purposes of compile-time
3489validation, ``"%s scored %g%% on her test"`` and ``"%s%g"`` are interchangeable
3490as the format string argument. As a means of self-documentation, users may
3491prefer the former when it provides a useful example of an expected format
3492string.
3493
3494In the implementation of a function with the ``format_matches`` attribute,
3495format verification works as if the format string was identical to the one
3496specified in the attribute.
3497
3498.. code-block:: c
3499
3500 __attribute__((__format_matches__(printf, 1, "%s %g")))
3501 void say_hi(const char *fmt) {
3502 printf(fmt, "person", 546);
3503 // ^ warning: format specifies type 'double' but the
3504 // argument has type 'int'
3505 // note: format string is defined here:
3506 // __attribute__((__format_matches__(printf, 1, "%s %g")))
3507 // ^~
3508 }
3509
3510
3511At the call sites of functions with the ``format_matches`` attribute, format
3512verification instead compares the two format strings to evaluate their
3513equivalence. Each format flavor defines equivalence between format specifiers.
3514Generally speaking, two specifiers are equivalent if they format the same type.
3515For instance, in the ``printf`` flavor, ``%2i`` and ``%-0.5d`` are compatible.
3516When ``-Wformat-signedness`` is disabled, ``%d`` and ``%u`` are compatible. For
3517a negative example, ``%ld`` is incompatible with ``%d``.
3518
3519Do note the following un-obvious cases:
3520
3521* Passing ``NULL`` as the format string does not trigger format diagnostics.
3522* When the format string is not NULL, it cannot _miss_ specifiers, even in
3523 trailing positions. For instance, ``%d`` is not accepted when the required
3524 format is ``%d %d %d``.
3525* While checks for the ``format`` attribute tolerate sone size mismatches
3526 that standard argument promotion renders immaterial (such as formatting an
3527 ``int`` with ``%hhd``, which specifies a ``char``-sized integer), checks for
3528 ``format_matches`` require specified argument sizes to match exactly.
3529* Format strings expecting a variable modifier (such as ``%*s``) are
3530 incompatible with format strings that would itemize the variable modifiers
3531 (such as ``%i %s``), even if the two specify ABI-compatible argument lists.
3532* All pointer specifiers, modifiers aside, are mutually incompatible. For
3533 instance, ``%s`` is not compatible with ``%p``, and ``%p`` is not compatible
3534 with ``%n``, and ``%hhn`` is incompatible with ``%s``, even if the pointers
3535 are ABI-compatible or identical on the selected platform. However, ``%0.5s``
3536 is compatible with ``%s``, since the difference only exists in modifier flags.
3537 This is not overridable with ``-Wformat-pedantic`` or its inverse, which
3538 control similar behavior in ``-Wformat``.
3539
3540At this time, clang implements ``format_matches`` only for format types in the
3541``printf`` family. This includes variants such as Apple's NSString format and
3542the FreeBSD ``kprintf``, but excludes ``scanf``. Using a known but unsupported
3543format silently fails in order to be compatible with other implementations that
3544would support these formats.)reST";
3545
3546static const char AttrDoc_FunctionReturnThunks[] = R"reST(The attribute ``function_return`` can replace return instructions with jumps to
3547target-specific symbols. This attribute supports 2 possible values,
3548corresponding to the values supported by the ``-mfunction-return=`` command
3549line flag:
3550
3551* ``__attribute__((function_return("keep")))`` to disable related transforms.
3552 This is useful for undoing global setting from ``-mfunction-return=`` locally
3553 for individual functions.
3554* ``__attribute__((function_return("thunk-extern")))`` to replace returns with
3555 jumps, while NOT emitting the thunk.
3556
3557The values ``thunk`` and ``thunk-inline`` from GCC are not supported.
3558
3559The symbol used for ``thunk-extern`` is target specific:
3560* X86: ``__x86_return_thunk``
3561
3562As such, this function attribute is currently only supported on X86 targets.)reST";
3563
3564static const char AttrDoc_GCCStruct[] = R"reST(The ``ms_struct`` and ``gcc_struct`` attributes request the compiler to enter a
3565special record layout compatibility mode which mimics the layout of Microsoft or
3566Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the
3567requested ABI, the attribute does nothing. However, if it does not, annotated
3568structure or class is laid out in a special compatibility mode, which slightly
3569changes offsets for fields and bit-fields. The intention is to match the layout
3570of the requested ABI for structures which only use C features.
3571
3572Note that the default behavior can be controlled by ``-mms-bitfields`` and
3573``-mno-ms-bitfields`` switches and via ``#pragma ms_struct``.
3574
3575The primary difference is for bitfields, where the MS variant only packs
3576adjacent fields into the same allocation unit if they have integral types
3577of the same size, while the GCC/Itanium variant packs all fields in a bitfield
3578tightly.)reST";
3579
3580static const char AttrDoc_GNUInline[] = R"reST(The ``gnu_inline`` changes the meaning of ``extern inline`` to use GNU inline
3581semantics, meaning:
3582
3583* If any declaration that is declared ``inline`` is not declared ``extern``,
3584 then the ``inline`` keyword is just a hint. In particular, an out-of-line
3585 definition is still emitted for a function with external linkage, even if all
3586 call sites are inlined, unlike in C99 and C++ inline semantics.
3587
3588* If all declarations that are declared ``inline`` are also declared
3589 ``extern``, then the function body is present only for inlining and no
3590 out-of-line version is emitted.
3591
3592Some important consequences: ``static inline`` emits an out-of-line
3593version if needed, a plain ``inline`` definition emits an out-of-line version
3594always, and an ``extern inline`` definition (in a header) followed by a
3595(non-``extern``) ``inline`` declaration in a source file emits an out-of-line
3596version of the function in that source file but provides the function body for
3597inlining to all includers of the header.
3598
3599Either ``__GNUC_GNU_INLINE__`` (GNU inline semantics) or
3600``__GNUC_STDC_INLINE__`` (C99 semantics) will be defined (they are mutually
3601exclusive). If ``__GNUC_STDC_INLINE__`` is defined, then the ``gnu_inline``
3602function attribute can be used to get GNU inline semantics on a per function
3603basis. If ``__GNUC_GNU_INLINE__`` is defined, then the translation unit is
3604already being compiled with GNU inline semantics as the implied default. It is
3605unspecified which macro is defined in a C++ compilation.
3606
3607GNU inline semantics are the default behavior with ``-std=gnu89``,
3608``-std=c89``, ``-std=c94``, or ``-fgnu89-inline``.)reST";
3609
3610static const char AttrDoc_GuardedBy[] = R"reST(No documentation.)reST";
3611
3612static const char AttrDoc_GuardedVar[] = R"reST(No documentation.)reST";
3613
3614static const char AttrDoc_HIPManaged[] = R"reST(The ``__managed__`` attribute can be applied to a global variable declaration in HIP.
3615A managed variable is emitted as an undefined global symbol in the device binary and is
3616registered by ``__hipRegisterManagedVariable`` in init functions. The HIP runtime allocates
3617managed memory and uses it to define the symbol when loading the device binary.
3618A managed variable can be accessed in both device and host code.)reST";
3619
3620static const char AttrDoc_HLSLAppliedSemantic[] = R"reST()reST";
3621
3622static const char AttrDoc_HLSLAssociatedResourceDecl[] = R"reST()reST";
3623
3624static const char AttrDoc_HLSLContainedType[] = R"reST()reST";
3625
3626static const char AttrDoc_HLSLControlFlowHint[] = R"reST()reST";
3627
3628static const char AttrDoc_HLSLGroupSharedAddressSpace[] = R"reST(HLSL enables threads of a compute shader to exchange values via shared memory.
3629HLSL provides barrier primitives such as GroupMemoryBarrierWithGroupSync,
3630and so on to ensure the correct ordering of reads and writes to shared memory
3631in the shader and to avoid data races.
3632Here's an example to declare a groupshared variable.
3633.. code-block:: c++
3634
3635 groupshared GSData data[5*5*1];
3636
3637The full documentation is available here: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-syntax#group-shared)reST";
3638
3639static const char AttrDoc_HLSLIsCounter[] = R"reST()reST";
3640
3641static const char AttrDoc_HLSLLoopHint[] = R"reST(The ``[loop]`` directive allows loop optimization hints to be
3642specified for the subsequent loop. The directive allows unrolling to
3643be disabled and is not compatible with [unroll(x)].
3644
3645Specifying the parameter, ``[loop]``, directs the
3646unroller to not unroll the loop.
3647
3648.. code-block:: hlsl
3649
3650 [loop]
3651 for (...) {
3652 ...
3653 }
3654
3655.. code-block:: hlsl
3656
3657 [loop]
3658 while (...) {
3659 ...
3660 }
3661
3662.. code-block:: hlsl
3663
3664 [loop]
3665 do {
3666 ...
3667 } while (...)
3668
3669See `hlsl loop extensions <https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-for>`_
3670for details.)reST";
3671
3672static const char AttrDoc_HLSLNumThreads[] = R"reST(The ``numthreads`` attribute applies to HLSL shaders where explcit thread counts
3673are required. The ``X``, ``Y``, and ``Z`` values provided to the attribute
3674dictate the thread id. Total number of threads executed is ``X * Y * Z``.
3675
3676The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-numthreads)reST";
3677
3678static const char AttrDoc_HLSLPackOffset[] = R"reST(The packoffset attribute is used to change the layout of a cbuffer.
3679Attribute spelling in HLSL is: ``packoffset( c[Subcomponent][.component] )``.
3680A subcomponent is a register number, which is an integer. A component is in the form of [.xyzw].
3681
3682Examples:
3683
3684.. code-block:: hlsl
3685
3686 cbuffer A {
3687 float3 a : packoffset(c0.y);
3688 float4 b : packoffset(c4);
3689 }
3690
3691The full documentation is available here: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-packoffset)reST";
3692
3693static const char AttrDoc_HLSLParamModifier[] = R"reST(HLSL function parameters are passed by value. Parameter declarations support
3694three qualifiers to denote parameter passing behavior. The three qualifiers are
3695`in`, `out` and `inout`.
3696
3697Parameters annotated with `in` or with no annotation are passed by value from
3698the caller to the callee.
3699
3700Parameters annotated with `out` are written to the argument after the callee
3701returns (Note: arguments values passed into `out` parameters *are not* copied
3702into the callee).
3703
3704Parameters annotated with `inout` are copied into the callee via a temporary,
3705and copied back to the argument after the callee returns.)reST";
3706
3707static const char AttrDoc_HLSLParsedSemantic[] = R"reST()reST";
3708
3709static const char AttrDoc_HLSLROV[] = R"reST()reST";
3710
3711static const char AttrDoc_HLSLRawBuffer[] = R"reST()reST";
3712
3713static const char AttrDoc_HLSLResourceBinding[] = R"reST(The resource binding attribute sets the virtual register and logical register space for a resource.
3714Attribute spelling in HLSL is: ``register(slot [, space])``.
3715``slot`` takes the format ``[type][number]``,
3716where ``type`` is a single character specifying the resource type and ``number`` is the virtual register number.
3717
3718Register types are:
3719t for shader resource views (SRV),
3720s for samplers,
3721u for unordered access views (UAV),
3722b for constant buffer views (CBV).
3723
3724Register space is specified in the format ``space[number]`` and defaults to ``space0`` if omitted.
3725Here're resource binding examples with and without space:
3726
3727.. code-block:: hlsl
3728
3729 RWBuffer<float> Uav : register(u3, space1);
3730 Buffer<float> Buf : register(t1);
3731
3732The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3d12/resource-binding-in-hlsl)reST";
3733
3734static const char AttrDoc_HLSLResourceClass[] = R"reST()reST";
3735
3736static const char AttrDoc_HLSLResourceDimension[] = R"reST()reST";
3737
3738static const char AttrDoc_HLSLShader[] = R"reST(The ``shader`` type attribute applies to HLSL shader entry functions to
3739identify the shader type for the entry function.
3740The syntax is:
3741
3742.. code-block:: text
3743
3744 ``[shader(string-literal)]``
3745
3746where the string literal is one of: "pixel", "vertex", "geometry", "hull",
3747"domain", "compute", "raygeneration", "intersection", "anyhit", "closesthit",
3748"miss", "callable", "mesh", "amplification". Normally the shader type is set
3749by shader target with the ``-T`` option like ``-Tps_6_1``. When compiling to a
3750library target like ``lib_6_3``, the shader type attribute can help the
3751compiler to identify the shader type. It is mostly used by Raytracing shaders
3752where shaders must be compiled into a library and linked at runtime.)reST";
3753
3754static const char AttrDoc_HLSLUnparsedSemantic[] = R"reST()reST";
3755
3756static const char AttrDoc_HLSLVkBinding[] = R"reST(The ``[[vk::binding]]`` attribute allows you to explicitly specify the descriptor
3757set and binding for a resource when targeting SPIR-V. This is particularly
3758useful when you need different bindings for SPIR-V and DXIL, as the ``register``
3759attribute can be used for DXIL-specific bindings.
3760
3761The attribute takes two integer arguments: the binding and the descriptor set.
3762The descriptor set is optional and defaults to 0 if not provided.
3763
3764.. code-block:: c++
3765
3766 // A structured buffer with binding 23 in descriptor set 102.
3767 [[vk::binding(23, 102)]] StructuredBuffer<float> Buf;
3768
3769 // A structured buffer with binding 14 in descriptor set 0.
3770 [[vk::binding(14)]] StructuredBuffer<float> Buf2;
3771
3772 // A cbuffer with binding 1 in descriptor set 2.
3773 [[vk::binding(1, 2)]] cbuffer MyCBuffer {
3774 float4x4 worldViewProj;
3775 };)reST";
3776
3777static const char AttrDoc_HLSLVkConstantId[] = R"reST(The ``vk::constant_id`` attribute specifies the id for a SPIR-V specialization
3778constant. The attribute applies to const global scalar variables. The variable must be initialized with a C++11 constexpr.
3779In SPIR-V, the
3780variable will be replaced with an `OpSpecConstant` with the given id.
3781The syntax is:
3782
3783.. code-block:: text
3784
3785 ``[[vk::constant_id(<Id>)]] const T Name = <Init>``)reST";
3786
3787static const char AttrDoc_HLSLVkExtBuiltinInput[] = R"reST(Vulkan shaders have `Input` builtins. Those variables are externally
3788initialized by the driver/pipeline, but each copy is private to the current
3789lane.
3790
3791Those builtins can be declared using the `[[vk::ext_builtin_input]]` attribute
3792like follows:
3793
3794.. code-block:: c++
3795
3796 [[vk::ext_builtin_input(/* WorkgroupId */ 26)]]
3797 static const uint3 groupid;
3798
3799This variable will be lowered into a module-level variable, with the `Input`
3800storage class, and the `BuiltIn 26` decoration.
3801
3802The full documentation for this inline SPIR-V attribute can be found here:
3803https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md)reST";
3804
3805static const char AttrDoc_HLSLVkExtBuiltinOutput[] = R"reST(Vulkan shaders have `Output` builtins. Those variables are externally
3806visible to the driver/pipeline, but each copy is private to the current
3807lane.
3808
3809Those builtins can be declared using the `[[vk::ext_builtin_output]]`
3810attribute like follows:
3811
3812.. code-block:: c++
3813
3814 [[vk::ext_builtin_output(/* Position */ 0)]]
3815 static float4 position;
3816
3817This variable will be lowered into a module-level variable, with the `Output`
3818storage class, and the `BuiltIn 0` decoration.
3819
3820The full documentation for this inline SPIR-V attribute can be found here:
3821https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md)reST";
3822
3823static const char AttrDoc_HLSLVkLocation[] = R"reST(Attribute used for specifying the location number for the stage input/output
3824variables. Allowed on function parameters, function returns, and struct
3825fields. This parameter has no effect when used outside of an entrypoint
3826parameter/parameter field/return value.
3827
3828This attribute maps to the 'Location' SPIR-V decoration.)reST";
3829
3830static const char AttrDoc_HLSLVkPushConstant[] = R"reST(Vulkan shaders have `PushConstants`
3831
3832The ``[[vk::push_constant]]`` attribute allows you to declare this
3833global variable as a push constant when targeting Vulkan.
3834This attribute is ignored otherwise.
3835
3836This attribute must be applied to the variable, not underlying type.
3837The variable type must be a struct, per the requirements of Vulkan, "there
3838must be no more than one push constant block statically used per shader entry
3839point.")reST";
3840
3841static const char AttrDoc_HLSLWaveSize[] = R"reST(The ``WaveSize`` attribute specify a wave size on a shader entry point in order
3842to indicate either that a shader depends on or strongly prefers a specific wave
3843size.
3844There're 2 versions of the attribute: ``WaveSize`` and ``RangedWaveSize``.
3845The syntax for ``WaveSize`` is:
3846
3847.. code-block:: text
3848
3849 ``[WaveSize(<numLanes>)]``
3850
3851The allowed wave sizes that an HLSL shader may specify are the powers of 2
3852between 4 and 128, inclusive.
3853In other words, the set: [4, 8, 16, 32, 64, 128].
3854
3855The syntax for ``RangedWaveSize`` is:
3856
3857.. code-block:: text
3858
3859 ``[WaveSize(<minWaveSize>, <maxWaveSize>, [prefWaveSize])]``
3860
3861Where minWaveSize is the minimum wave size supported by the shader representing
3862the beginning of the allowed range, maxWaveSize is the maximum wave size
3863supported by the shader representing the end of the allowed range, and
3864prefWaveSize is the optional preferred wave size representing the size expected
3865to be the most optimal for this shader.
3866
3867``WaveSize`` is available for HLSL shader model 6.6 and later.
3868``RangedWaveSize`` available for HLSL shader model 6.8 and later.
3869
3870The full documentation is available here: https://microsoft.github.io/DirectX-Specs/d3d/HLSL_SM_6_6_WaveSize.html
3871and https://microsoft.github.io/hlsl-specs/proposals/0013-wave-size-range.html)reST";
3872
3873static const char AttrDoc_Hot[] = R"reST(``__attribute__((hot))`` marks a function as hot, as a manual alternative to PGO hotness data.
3874If PGO data is available, the annotation ``__attribute__((hot))`` overrides the profile count based hotness (unlike ``__attribute__((cold))``).)reST";
3875
3876static const char AttrDoc_HybridPatchable[] = R"reST(The ``hybrid_patchable`` attribute declares an ARM64EC function with an additional
3877x86-64 thunk, which may be patched at runtime.
3878
3879For more information see
3880`ARM64EC ABI documentation <https://learn.microsoft.com/en-us/windows/arm/arm64ec-abi>`_.)reST";
3881
3882static const char AttrDoc_IBAction[] = R"reST(No documentation.)reST";
3883
3884static const char AttrDoc_IBOutlet[] = R"reST(No documentation.)reST";
3885
3886static const char AttrDoc_IBOutletCollection[] = R"reST(No documentation.)reST";
3887
3888static const char AttrDoc_IFunc[] = R"reST(``__attribute__((ifunc("resolver")))`` is used to mark that the address of a
3889declaration should be resolved at runtime by calling a resolver function.
3890
3891The symbol name of the resolver function is given in quotes. A function with
3892this name (after mangling) must be defined in the current translation unit; it
3893may be ``static``. The resolver function should return a pointer.
3894
3895The ``ifunc`` attribute may only be used on a function declaration. A function
3896declaration with an ``ifunc`` attribute is considered to be a definition of the
3897declared entity. The entity must not have weak linkage; for example, in C++,
3898it cannot be applied to a declaration if a definition at that location would be
3899considered inline.
3900
3901Not all targets support this attribute:
3902
3903- ELF target support depends on both the linker and runtime linker, and is
3904 available in at least lld 4.0 and later, binutils 2.20.1 and later, glibc
3905 v2.11.1 and later, and FreeBSD 9.1 and later.
3906- Mach-O targets support it, but with slightly different semantics: the resolver
3907 is run at first call, instead of at load time by the runtime linker.
3908- Windows target supports it on AArch64, but with different semantics: the
3909 ``ifunc`` is replaced with a global function pointer, and the call is replaced
3910 with an indirect call. The function pointer is initialized by a constructor
3911 that calls the resolver.
3912- Baremetal target supports it on AVR.
3913- AIX/XCOFF supports it via a compiler-only solution. An ifunc appears as a
3914 regular function (has an entry point ``.foo[PR]`` and a function descriptor
3915 ``foo[DS]``). The entry point is a stub that branches to the function address
3916 in the descriptor, and the descriptor is initialized via a constructor
3917 function (``__init_ifuncs``) that is linked into every shared object and
3918 executable. ``__init_ifuncs`` calls the resolver of each ifunc and stores the
3919 result in the corresponding descriptor.
3920- Other targets currently do not support this attribute.)reST";
3921
3922static const char AttrDoc_InferredNoReturn[] = R"reST()reST";
3923
3924static const char AttrDoc_InitPriority[] = R"reST(In C++, the order in which global variables are initialized across translation
3925units is unspecified, unlike the ordering within a single translation unit. The
3926``init_priority`` attribute allows you to specify a relative ordering for the
3927initialization of objects declared at namespace scope in C++ within a single
3928linked image on supported platforms. The priority is given as an integer constant
3929expression between 101 and 65535 (inclusive). Priorities outside of that range are
3930reserved for use by the implementation. A lower value indicates a higher priority
3931of initialization. Note that only the relative ordering of values is important.
3932For example:
3933
3934.. code-block:: c++
3935
3936 struct SomeType { SomeType(); };
3937 __attribute__((init_priority(200))) SomeType Obj1;
3938 __attribute__((init_priority(101))) SomeType Obj2;
3939
3940``Obj2`` will be initialized *before* ``Obj1`` despite the usual order of
3941initialization being the opposite.
3942
3943Note that this attribute does not control the initialization order of objects
3944across final linked image boundaries like shared objects and executables.
3945
3946On Windows, ``init_seg(compiler)`` is represented with a priority of 200 and
3947``init_seg(library)`` is represented with a priority of 400. ``init_seg(user)``
3948uses the default 65535 priority.
3949
3950On MachO platforms, this attribute also does not control the order of initialization
3951across translation units, where it only affects the order within a single TU.
3952
3953This attribute is only supported for C++ and Objective-C++ and is ignored in
3954other language modes. Currently, this attribute is not implemented on z/OS.)reST";
3955
3956static const char AttrDoc_InitSeg[] = R"reST(The attribute applied by ``pragma init_seg()`` controls the section into
3957which global initialization function pointers are emitted. It is only
3958available with ``-fms-extensions``. Typically, this function pointer is
3959emitted into ``.CRT$XCU`` on Windows. The user can change the order of
3960initialization by using a different section name with the same
3961``.CRT$XC`` prefix and a suffix that sorts lexicographically before or
3962after the standard ``.CRT$XCU`` sections. See the init_seg_
3963documentation on MSDN for more information.
3964
3965.. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx)reST";
3966
3967static const char AttrDoc_IntelOclBicc[] = R"reST(No documentation.)reST";
3968
3969static const char AttrDoc_InternalLinkage[] = R"reST(The ``internal_linkage`` attribute changes the linkage type of the declaration
3970to internal. This is similar to C-style ``static``, but can be used on classes
3971and class methods. When applied to a class definition, this attribute affects
3972all methods and static data members of that class. This can be used to contain
3973the ABI of a C++ library by excluding unwanted class methods from the export
3974tables.)reST";
3975
3976static const char AttrDoc_LTOVisibilityPublic[] = R"reST(See :doc:`LTOVisibility`.)reST";
3977
3978static const char AttrDoc_LayoutVersion[] = R"reST(The layout_version attribute requests that the compiler utilize the class
3979layout rules of a particular compiler version.
3980This attribute only applies to struct, class, and union types.
3981It is only supported when using the Microsoft C++ ABI.)reST";
3982
3983static const char AttrDoc_Leaf[] = R"reST(The ``leaf`` attribute is used as a compiler hint to improve dataflow analysis
3984in library functions. Functions marked with the ``leaf`` attribute are not allowed
3985to jump back into the caller's translation unit, whether through invoking a
3986callback function, an external function call, use of ``longjmp``, or other means.
3987Therefore, they cannot use or modify any data that does not escape the caller function's
3988compilation unit.
3989
3990For more information see
3991`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html>`)reST";
3992
3993static const char AttrDoc_LifetimeBound[] = R"reST(The ``lifetimebound`` attribute on a function parameter or implicit object
3994parameter indicates that objects that are referred to by that parameter may
3995also be referred to by the return value of the annotated function (or, for a
3996parameter of a constructor, by the value of the constructed object).
3997
3998By default, a reference is considered to refer to its referenced object, a
3999pointer is considered to refer to its pointee, a ``std::initializer_list<T>``
4000is considered to refer to its underlying array, and aggregates (arrays and
4001simple ``struct``\s) are considered to refer to all objects that their
4002transitive subobjects refer to.
4003
4004Clang warns if it is able to detect that an object or reference refers to
4005another object with a shorter lifetime. For example, Clang will warn if a
4006function returns a reference to a local variable, or if a reference is bound to
4007a temporary object whose lifetime is not extended. By using the
4008``lifetimebound`` attribute, this determination can be extended to look through
4009user-declared functions. For example:
4010
4011.. code-block:: c++
4012
4013 #include <map>
4014 #include <string>
4015
4016 using namespace std::literals;
4017
4018 // Returns m[key] if key is present, or default_value if not.
4019 template<typename T, typename U>
4020 const U &get_or_default(const std::map<T, U> &m [[clang::lifetimebound]],
4021 const T &key, /* note, not lifetimebound */
4022 const U &default_value [[clang::lifetimebound]]) {
4023 if (auto iter = m.find(key); iter != m.end()) return iter->second;
4024 else return default_value;
4025 }
4026
4027 int main() {
4028 std::map<std::string, std::string> m;
4029 // warning: temporary bound to local reference 'val1' will be destroyed
4030 // at the end of the full-expression
4031 const std::string &val1 = get_or_default(m, "foo"s, "bar"s);
4032
4033 // No warning in this case.
4034 std::string def_val = "bar"s;
4035 const std::string &val2 = get_or_default(m, "foo"s, def_val);
4036
4037 return 0;
4038 }
4039
4040The attribute can be applied to the implicit ``this`` parameter of a member
4041function by writing the attribute after the function type:
4042
4043.. code-block:: c++
4044
4045 struct string {
4046 // The returned pointer should not outlive ``*this``.
4047 const char *data() const [[clang::lifetimebound]];
4048 };
4049
4050This attribute is inspired by the C++ committee paper `P0936R0
4051<http://wg21.link/p0936r0>`_, but does not affect whether temporary objects
4052have their lifetimes extended.)reST";
4053
4054static const char AttrDoc_LifetimeCaptureBy[] = R"reST(Similar to `lifetimebound`_, the ``lifetime_capture_by(X)`` attribute on a
4055function parameter or implicit object parameter indicates that the capturing
4056entity ``X`` may refer to the object referred by that parameter.
4057
4058Below is a list of types of the parameters and what they're considered to refer to:
4059
4060- A reference param (of non-view type) is considered to refer to its referenced object.
4061- A pointer param (of non-view type) is considered to refer to its pointee.
4062- View type param (type annotated with ``[[gsl::Pointer()]]``) is considered to refer
4063 to its pointee (gsl owner). This holds true even if the view type appears as a reference
4064 in the parameter. For example, both ``std::string_view`` and
4065 ``const std::string_view &`` are considered to refer to a ``std::string``.
4066- A ``std::initializer_list<T>`` is considered to refer to its underlying array.
4067- Aggregates (arrays and simple ``struct``\s) are considered to refer to all
4068 objects that their transitive subobjects refer to.
4069
4070Clang would diagnose when a temporary object is used as an argument to such an
4071annotated parameter.
4072In this case, the capturing entity ``X`` could capture a dangling reference to this
4073temporary object.
4074
4075.. code-block:: c++
4076
4077 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
4078 s.insert(a);
4079 }
4080 void use() {
4081 std::set<std::string_view> s;
4082 addToSet(std::string(), s); // Warning: object whose reference is captured by 's' will be destroyed at the end of the full-expression.
4083 // ^^^^^^^^^^^^^
4084 std::string local;
4085 addToSet(local, s); // Ok.
4086 }
4087
4088The capturing entity ``X`` can be one of the following:
4089
4090- Another (named) function parameter.
4091
4092 .. code-block:: c++
4093
4094 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
4095 s.insert(a);
4096 }
4097
4098- ``this`` (in case of member functions).
4099
4100 .. code-block:: c++
4101
4102 class S {
4103 void addToSet(std::string_view a [[clang::lifetime_capture_by(this)]]) {
4104 s.insert(a);
4105 }
4106 std::set<std::string_view> s;
4107 };
4108
4109 Note: When applied to a constructor parameter, `[[clang::lifetime_capture_by(this)]]` is just an alias of `[[clang::lifetimebound]]`.
4110
4111- `global`, `unknown`.
4112
4113 .. code-block:: c++
4114
4115 std::set<std::string_view> s;
4116 void addToSet(std::string_view a [[clang::lifetime_capture_by(global)]]) {
4117 s.insert(a);
4118 }
4119 void addSomewhere(std::string_view a [[clang::lifetime_capture_by(unknown)]]);
4120
4121The attribute can be applied to the implicit ``this`` parameter of a member
4122function by writing the attribute after the function type:
4123
4124.. code-block:: c++
4125
4126 struct S {
4127 const char *data(std::set<S*>& s) [[clang::lifetime_capture_by(s)]] {
4128 s.insert(this);
4129 }
4130 };
4131
4132The attribute supports specifying more than one capturing entities:
4133
4134.. code-block:: c++
4135
4136 void addToSets(std::string_view a [[clang::lifetime_capture_by(s1, s2)]],
4137 std::set<std::string_view>& s1,
4138 std::set<std::string_view>& s2) {
4139 s1.insert(a);
4140 s2.insert(a);
4141 }
4142
4143Limitation: The capturing entity ``X`` is not used by the analysis and is
4144used for documentation purposes only. This is because the analysis is
4145statement-local and only detects use of a temporary as an argument to the
4146annotated parameter.
4147
4148.. code-block:: c++
4149
4150 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s);
4151 void use() {
4152 std::set<std::string_view> s;
4153 if (foo()) {
4154 std::string str;
4155 addToSet(str, s); // Not detected.
4156 }
4157 })reST";
4158
4159static const char AttrDoc_Likely[] = R"reST(The ``likely`` and ``unlikely`` attributes are used as compiler hints.
4160The attributes are used to aid the compiler to determine which branch is
4161likely or unlikely to be taken. This is done by marking the branch substatement
4162with one of the two attributes.
4163
4164It isn't allowed to annotate a single statement with both ``likely`` and
4165``unlikely``. Annotating the ``true`` and ``false`` branch of an ``if``
4166statement with the same likelihood attribute will result in a diagnostic and
4167the attributes are ignored on both branches.
4168
4169In a ``switch`` statement it's allowed to annotate multiple ``case`` labels
4170or the ``default`` label with the same likelihood attribute. This makes
4171* all labels without an attribute have a neutral likelihood,
4172* all labels marked ``[[likely]]`` have an equally positive likelihood, and
4173* all labels marked ``[[unlikely]]`` have an equally negative likelihood.
4174The neutral likelihood is the more likely of path execution than the negative
4175likelihood. The positive likelihood is the more likely of path of execution
4176than the neutral likelihood.
4177
4178These attributes have no effect on the generated code when using
4179PGO (Profile-Guided Optimization) or at optimization level 0.
4180
4181In Clang, the attributes will be ignored if they're not placed on
4182* the ``case`` or ``default`` label of a ``switch`` statement,
4183* or on the substatement of an ``if`` or ``else`` statement,
4184* or on the substatement of an ``for`` or ``while`` statement.
4185The C++ Standard recommends to honor them on every statement in the
4186path of execution, but that can be confusing:
4187
4188.. code-block:: c++
4189
4190 if (b) {
4191 [[unlikely]] --b; // Per the standard this is in the path of
4192 // execution, so this branch should be considered
4193 // unlikely. However, Clang ignores the attribute
4194 // here since it is not on the substatement.
4195 }
4196
4197 if (b) {
4198 --b;
4199 if(b)
4200 return;
4201 [[unlikely]] --b; // Not in the path of execution,
4202 } // the branch has no likelihood information.
4203
4204 if (b) {
4205 --b;
4206 foo(b);
4207 // Whether or not the next statement is in the path of execution depends
4208 // on the declaration of foo():
4209 // In the path of execution: void foo(int);
4210 // Not in the path of execution: [[noreturn]] void foo(int);
4211 // This means the likelihood of the branch depends on the declaration
4212 // of foo().
4213 [[unlikely]] --b;
4214 }
4215
4216
4217Below are some example usages of the likelihood attributes and their effects:
4218
4219.. code-block:: c++
4220
4221 if (b) [[likely]] { // Placement on the first statement in the branch.
4222 // The compiler will optimize to execute the code here.
4223 } else {
4224 }
4225
4226 if (b)
4227 [[unlikely]] b++; // Placement on the first statement in the branch.
4228 else {
4229 // The compiler will optimize to execute the code here.
4230 }
4231
4232 if (b) {
4233 [[unlikely]] b++; // Placement on the second statement in the branch.
4234 } // The attribute will be ignored.
4235
4236 if (b) [[likely]] {
4237 [[unlikely]] b++; // No contradiction since the second attribute
4238 } // is ignored.
4239
4240 if (b)
4241 ;
4242 else [[likely]] {
4243 // The compiler will optimize to execute the code here.
4244 }
4245
4246 if (b)
4247 ;
4248 else
4249 // The compiler will optimize to execute the next statement.
4250 [[likely]] b = f();
4251
4252 if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
4253 else [[likely]]; // and the attributes are ignored.
4254
4255 if (b)
4256 [[likely]] int i = 5; // Issues a diagnostic since the attribute
4257 // isn't allowed on a declaration.
4258
4259 switch (i) {
4260 [[likely]] case 1: // This value is likely
4261 ...
4262 break;
4263
4264 [[unlikely]] case 2: // This value is unlikely
4265 ...
4266 [[fallthrough]];
4267
4268 case 3: // No likelihood attribute
4269 ...
4270 [[likely]] break; // No effect
4271
4272 case 4: [[likely]] { // attribute on substatement has no effect
4273 ...
4274 break;
4275 }
4276
4277 [[unlikely]] default: // All other values are unlikely
4278 ...
4279 break;
4280 }
4281
4282 switch (i) {
4283 [[likely]] case 0: // This value and code path is likely
4284 ...
4285 [[fallthrough]];
4286
4287 case 1: // No likelihood attribute, code path is neutral
4288 break; // falling through has no effect on the likelihood
4289
4290 case 2: // No likelihood attribute, code path is neutral
4291 [[fallthrough]];
4292
4293 [[unlikely]] default: // This value and code path are both unlikely
4294 break;
4295 }
4296
4297 for(int i = 0; i != size; ++i) [[likely]] {
4298 ... // The loop is the likely path of execution
4299 }
4300
4301 for(const auto &E : Elements) [[likely]] {
4302 ... // The loop is the likely path of execution
4303 }
4304
4305 while(i != size) [[unlikely]] {
4306 ... // The loop is the unlikely path of execution
4307 } // The generated code will optimize to skip the loop body
4308
4309 while(true) [[unlikely]] {
4310 ... // The attribute has no effect
4311 } // Clang elides the comparison and generates an infinite
4312 // loop)reST";
4313
4314static const char AttrDoc_LoaderUninitialized[] = R"reST(The ``loader_uninitialized`` attribute can be placed on global variables to
4315indicate that the variable does not need to be zero initialized by the loader.
4316On most targets, zero-initialization does not incur any additional cost.
4317For example, most general purpose operating systems deliberately ensure
4318that all memory is properly initialized in order to avoid leaking privileged
4319information from the kernel or other programs. However, some targets
4320do not make this guarantee, and on these targets, avoiding an unnecessary
4321zero-initialization can have a significant impact on load times and/or code
4322size.
4323
4324A declaration with this attribute is a non-tentative definition just as if it
4325provided an initializer. Variables with this attribute are considered to be
4326uninitialized in the same sense as a local variable, and the programs must
4327write to them before reading from them. If the variable's type is a C++ class
4328type with a non-trivial default constructor, or an array thereof, this attribute
4329only suppresses the static zero-initialization of the variable, not the dynamic
4330initialization provided by executing the default constructor.)reST";
4331
4332static const char AttrDoc_LockReturned[] = R"reST(No documentation.)reST";
4333
4334static const char AttrDoc_LocksExcluded[] = R"reST(No documentation.)reST";
4335
4336static const char AttrDoc_LoopHint[] = R"reST(The ``#pragma clang loop`` directive allows loop optimization hints to be
4337specified for the subsequent loop. The directive allows pipelining to be
4338disabled, or vectorization, vector predication, interleaving, and unrolling to
4339be enabled or disabled. Vector width, vector predication, interleave count,
4340unrolling count, and the initiation interval for pipelining can be explicitly
4341specified. See `language extensions
4342<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
4343for details.)reST";
4344
4345static const char AttrDoc_M68kInterrupt[] = R"reST(No documentation.)reST";
4346
4347static const char AttrDoc_M68kRTD[] = R"reST(On M68k targets, this attribute changes the calling convention of a function
4348to clear parameters off the stack on return. In other words, callee is
4349responsible for cleaning out the stack space allocated for incoming paramters.
4350This convention does not support variadic calls or unprototyped functions in C.
4351When targeting M68010 or newer CPUs, this calling convention is implemented
4352using the `rtd` instruction.)reST";
4353
4354static const char AttrDoc_MIGServerRoutine[] = R"reST(The Mach Interface Generator release-on-success convention dictates
4355functions that follow it to only release arguments passed to them when they
4356return "success" (a ``kern_return_t`` error code that indicates that
4357no errors have occurred). Otherwise the release is performed by the MIG client
4358that called the function. The annotation ``__attribute__((mig_server_routine))``
4359is applied in order to specify which functions are expected to follow the
4360convention. This allows the Static Analyzer to find bugs caused by violations of
4361that convention. The attribute would normally appear on the forward declaration
4362of the actual server routine in the MIG server header, but it may also be
4363added to arbitrary functions that need to follow the same convention - for
4364example, a user can add them to auxiliary functions called by the server routine
4365that have their return value of type ``kern_return_t`` unconditionally returned
4366from the routine. The attribute can be applied to C++ methods, and in this case
4367it will be automatically applied to overrides if the method is virtual. The
4368attribute can also be written using C++11 syntax: ``[[mig::server_routine]]``.)reST";
4369
4370static const char AttrDoc_MSABI[] = R"reST(On non-Windows x86_64 and aarch64 targets, this attribute changes the calling convention of
4371a function to match the default convention used on Windows. This
4372attribute has no effect on Windows targets or non-x86_64, non-aarch64 targets.)reST";
4373
4374static const char AttrDoc_MSAllocator[] = R"reST(The ``__declspec(allocator)`` attribute is applied to functions that allocate
4375memory, such as operator new in C++. When CodeView debug information is emitted
4376(enabled by ``clang -gcodeview`` or ``clang-cl /Z7``), Clang will attempt to
4377record the code offset of heap allocation call sites in the debug info. It will
4378also record the type being allocated using some local heuristics. The Visual
4379Studio debugger uses this information to `profile memory usage`_.
4380
4381.. _profile memory usage: https://docs.microsoft.com/en-us/visualstudio/profiling/memory-usage
4382
4383This attribute does not affect optimizations in any way, unlike GCC's
4384``__attribute__((malloc))``.)reST";
4385
4386static const char AttrDoc_MSConstexpr[] = R"reST(The ``[[msvc::constexpr]]`` attribute can be applied only to a function
4387definition or a ``return`` statement. It does not impact function declarations.
4388A ``[[msvc::constexpr]]`` function cannot be ``constexpr`` or ``consteval``.
4389A ``[[msvc::constexpr]]`` function is treated as if it were a ``constexpr`` function
4390when it is evaluated in a constant context of ``[[msvc::constexpr]] return`` statement.
4391Otherwise, it is treated as a regular function.
4392
4393Semantics of this attribute are enabled only under MSVC compatibility
4394(``-fms-compatibility-version``) 19.33 and later.)reST";
4395
4396static const char AttrDoc_MSInheritance[] = R"reST(This collection of keywords is enabled under ``-fms-extensions`` and controls
4397the pointer-to-member representation used on ``*-*-win32`` targets.
4398
4399The ``*-*-win32`` targets utilize a pointer-to-member representation which
4400varies in size and alignment depending on the definition of the underlying
4401class.
4402
4403However, this is problematic when a forward declaration is only available and
4404no definition has been made yet. In such cases, Clang is forced to utilize the
4405most general representation that is available to it.
4406
4407These keywords make it possible to use a pointer-to-member representation other
4408than the most general one regardless of whether or not the definition will ever
4409be present in the current translation unit.
4410
4411This family of keywords belong between the ``class-key`` and ``class-name``:
4412
4413.. code-block:: c++
4414
4415 struct __single_inheritance S;
4416 int S::*i;
4417 struct S {};
4418
4419This keyword can be applied to class templates but only has an effect when used
4420on full specializations:
4421
4422.. code-block:: c++
4423
4424 template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
4425 template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
4426 template <> struct __single_inheritance A<int, float>;
4427
4428Note that choosing an inheritance model less general than strictly necessary is
4429an error:
4430
4431.. code-block:: c++
4432
4433 struct __multiple_inheritance S; // error: inheritance model does not match definition
4434 int S::*i;
4435 struct S {};)reST";
4436
4437static const char AttrDoc_MSNoVTable[] = R"reST(This attribute can be added to a class declaration or definition to signal to
4438the compiler that constructors and destructors will not reference the virtual
4439function table. It is only supported when using the Microsoft C++ ABI.)reST";
4440
4441static const char AttrDoc_MSP430Interrupt[] = R"reST(No documentation.)reST";
4442
4443static const char AttrDoc_MSStruct[] = R"reST(The ``ms_struct`` and ``gcc_struct`` attributes request the compiler to enter a
4444special record layout compatibility mode which mimics the layout of Microsoft or
4445Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the
4446requested ABI, the attribute does nothing. However, if it does not, annotated
4447structure or class is laid out in a special compatibility mode, which slightly
4448changes offsets for fields and bit-fields. The intention is to match the layout
4449of the requested ABI for structures which only use C features.
4450
4451Note that the default behavior can be controlled by ``-mms-bitfields`` and
4452``-mno-ms-bitfields`` switches and via ``#pragma ms_struct``.
4453
4454The primary difference is for bitfields, where the MS variant only packs
4455adjacent fields into the same allocation unit if they have integral types
4456of the same size, while the GCC/Itanium variant packs all fields in a bitfield
4457tightly.)reST";
4458
4459static const char AttrDoc_MSVtorDisp[] = R"reST()reST";
4460
4461static const char AttrDoc_MallocSpan[] = R"reST(The ``malloc_span`` attribute can be used to mark that a function which acts
4462like a system memory allocation function and returns a span-like structure,
4463where the returned memory range does not alias storage from any other object
4464accessible to the caller.
4465
4466In this context, a span-like structure is assumed to have two non-static data
4467members, one of which is a pointer to the start of the allocated memory and
4468the other one is either an integer type containing the size of the actually
4469allocated memory or a pointer to the end of the allocated region. Note, static
4470data members do not impact whether a type is span-like or not.)reST";
4471
4472static const char AttrDoc_MaxFieldAlignment[] = R"reST()reST";
4473
4474static const char AttrDoc_MayAlias[] = R"reST(No documentation.)reST";
4475
4476static const char AttrDoc_MaybeUndef[] = R"reST(The ``maybe_undef`` attribute can be placed on a function parameter. It indicates
4477that the parameter is allowed to use undef values. It informs the compiler
4478to insert a freeze LLVM IR instruction on the function parameter.
4479Please note that this is an attribute that is used as an internal
4480implementation detail and not intended to be used by external users.
4481
4482In languages HIP, CUDA etc., some functions have multi-threaded semantics and
4483it is enough for only one or some threads to provide defined arguments.
4484Depending on semantics, undef arguments in some threads don't produce
4485undefined results in the function call. Since, these functions accept undefined
4486arguments, ``maybe_undef`` attribute can be placed.
4487
4488Sample usage:
4489.. code-block:: c
4490
4491 void maybeundeffunc(int __attribute__((maybe_undef))param);)reST";
4492
4493static const char AttrDoc_MicroMips[] = R"reST(Clang supports the GNU style ``__attribute__((micromips))`` and
4494``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes
4495may be attached to a function definition and instructs the backend to generate
4496or not to generate microMIPS code for that function.
4497
4498These attributes override the ``-mmicromips`` and ``-mno-micromips`` options
4499on the command line.)reST";
4500
4501static const char AttrDoc_MinSize[] = R"reST(This function attribute indicates that optimization passes and code generator passes
4502make choices that keep the function code size as small as possible. Optimizations may
4503also sacrifice runtime performance in order to minimize the size of the generated code.)reST";
4504
4505static const char AttrDoc_MinVectorWidth[] = R"reST(Clang supports the ``__attribute__((min_vector_width(width)))`` attribute. This
4506attribute may be attached to a function and informs the backend that this
4507function desires vectors of at least this width to be generated. Target-specific
4508maximum vector widths still apply. This means even if you ask for something
4509larger than the target supports, you will only get what the target supports.
4510This attribute is meant to be a hint to control target heuristics that may
4511generate narrower vectors than what the target hardware supports.
4512
4513This is currently used by the X86 target to allow some CPUs that support 512-bit
4514vectors to be limited to using 256-bit vectors to avoid frequency penalties.
4515This is currently enabled with the ``-prefer-vector-width=256`` command line
4516option. The ``min_vector_width`` attribute can be used to prevent the backend
4517from trying to split vector operations to match the ``prefer-vector-width``. All
4518X86 vector intrinsics from x86intrin.h already set this attribute. Additionally,
4519use of any of the X86-specific vector builtins will implicitly set this
4520attribute on the calling function. The intent is that explicitly writing vector
4521code using the X86 intrinsics will prevent ``prefer-vector-width`` from
4522affecting the code.)reST";
4523
4524static const char AttrDoc_Mips16[] = R"reST(No documentation.)reST";
4525
4526static const char AttrDoc_MipsInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt("ARGUMENT")))`` attribute on
4527MIPS targets. This attribute may be attached to a function definition and instructs
4528the backend to generate appropriate function entry/exit code so that it can be used
4529directly as an interrupt service routine.
4530
4531By default, the compiler will produce a function prologue and epilogue suitable for
4532an interrupt service routine that handles an External Interrupt Controller (eic)
4533generated interrupt. This behavior can be explicitly requested with the "eic"
4534argument.
4535
4536Otherwise, for use with vectored interrupt mode, the argument passed should be
4537of the form "vector=LEVEL" where LEVEL is one of the following values:
4538"sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will
4539then set the interrupt mask to the corresponding level which will mask all
4540interrupts up to and including the argument.
4541
4542The semantics are as follows:
4543
4544- The prologue is modified so that the Exception Program Counter (EPC) and
4545 Status coprocessor registers are saved to the stack. The interrupt mask is
4546 set so that the function can only be interrupted by a higher priority
4547 interrupt. The epilogue will restore the previous values of EPC and Status.
4548
4549- The prologue and epilogue are modified to save and restore all non-kernel
4550 registers as necessary.
4551
4552- The FPU is disabled in the prologue, as the floating pointer registers are not
4553 spilled to the stack.
4554
4555- The function return sequence is changed to use an exception return instruction.
4556
4557- The parameter sets the interrupt mask for the function corresponding to the
4558 interrupt level specified. If no mask is specified the interrupt mask
4559 defaults to "eic".)reST";
4560
4561static const char AttrDoc_MipsLongCall[] = R"reST(Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
4562and ``__attribute__((near))`` attributes on MIPS targets. These attributes may
4563only be added to function declarations and change the code generated
4564by the compiler when directly calling the function. The ``near`` attribute
4565allows calls to the function to be made using the ``jal`` instruction, which
4566requires the function to be located in the same naturally aligned 256MB
4567segment as the caller. The ``long_call`` and ``far`` attributes are synonyms
4568and require the use of a different call sequence that works regardless
4569of the distance between the functions.
4570
4571These attributes have no effect for position-independent code.
4572
4573These attributes take priority over command line switches such
4574as ``-mlong-calls`` and ``-mno-long-calls``.)reST";
4575
4576static const char AttrDoc_MipsShortCall[] = R"reST(Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
4577``__attribute__((short__call))``, and ``__attribute__((near))`` attributes
4578on MIPS targets. These attributes may only be added to function declarations
4579and change the code generated by the compiler when directly calling
4580the function. The ``short_call`` and ``near`` attributes are synonyms and
4581allow calls to the function to be made using the ``jal`` instruction, which
4582requires the function to be located in the same naturally aligned 256MB segment
4583as the caller. The ``long_call`` and ``far`` attributes are synonyms and
4584require the use of a different call sequence that works regardless
4585of the distance between the functions.
4586
4587These attributes have no effect for position-independent code.
4588
4589These attributes take priority over command line switches such
4590as ``-mlong-calls`` and ``-mno-long-calls``.)reST";
4591
4592static const char AttrDoc_Mode[] = R"reST(No documentation.)reST";
4593
4594static const char AttrDoc_ModularFormat[] = R"reST(The ``modular_format`` attribute can be applied to a function that bears the
4595``format`` attribute (or standard library functions) to indicate that the
4596implementation is "modular", that is, that the implementation is logically
4597divided into a number of named aspects. When the compiler can determine that
4598not all aspects of the implementation are needed for a given call, the compiler
4599may redirect the call to the identifier given as the first argument to the
4600attribute (the modular implementation function).
4601
4602The second argument is an implementation name, and the remaining arguments are
4603aspects of the format string for the compiler to report. The implementation
4604name is an unevaluated identifier in the C namespace.
4605
4606The compiler reports that a call requires an aspect by issuing a relocation for
4607the symbol ``<impl_name>_<aspect>`` at the point of the call. This arranges for
4608code and data needed to support the aspect of the implementation to be brought
4609into the link to satisfy weak references in the modular implemenation function.
4610If the compiler does not understand an aspect, it must summarily consider any
4611call to require that aspect.
4612
4613For example, say ``printf`` is annotated with
4614``modular_format(__modular_printf, "__printf", "float")``. Then, a call to
4615``printf(var, 42)`` would be untouched. A call to ``printf("%d", 42)`` would
4616become a call to ``__modular_printf`` with the same arguments, as would
4617``printf("%f", 42.0)``. The latter would be accompanied with a strong
4618relocation against the symbol ``__printf_float``, which would bring floating
4619point support for ``printf`` into the link.
4620
4621If the attribute appears more than once on a declaration, or across a chain of
4622redeclarations, it is an error for the attributes to have different arguments,
4623excepting that the aspects may be in any order.
4624
4625The following aspects are currently supported:
4626
4627- ``float``: The call has a floating point argument)reST";
4628
4629static const char AttrDoc_MustTail[] = R"reST(If a ``return`` statement is marked ``musttail``, this indicates that the
4630compiler must generate a tail call for the program to be correct, even when
4631optimizations are disabled. This guarantees that the call will not cause
4632unbounded stack growth if it is part of a recursive cycle in the call graph.
4633
4634If the callee is a virtual function that is implemented by a thunk, there is
4635no guarantee in general that the thunk tail-calls the implementation of the
4636virtual function, so such a call in a recursive cycle can still result in
4637unbounded stack growth.
4638
4639``clang::musttail`` can only be applied to a ``return`` statement whose value
4640is the result of a function call (even functions returning void must use
4641``return``, although no value is returned). The target function must have the
4642same number of arguments as the caller. The types of the return value and all
4643arguments must be similar according to C++ rules (differing only in cv
4644qualifiers or array size), including the implicit "this" argument, if any.
4645Any variables in scope, including all arguments to the function and the
4646return value must be trivially destructible. The calling convention of the
4647caller and callee must match, and they must not be variadic functions or have
4648old style K&R C function declarations.
4649
4650The lifetimes of all local variables and function parameters end immediately
4651before the call to the function. This means that it is undefined behaviour to
4652pass a pointer or reference to a local variable to the called function, which
4653is not the case without the attribute. Clang will emit a warning in common
4654cases where this happens.
4655
4656``clang::musttail`` provides assurances that the tail call can be optimized on
4657all targets, not just one.)reST";
4658
4659static const char AttrDoc_NSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4660(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4661convention (e.g. functions starting with "get" are assumed to return at
4662``+0``).
4663
4664It can be overridden using a family of the following attributes. In
4665Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4666a function communicates that the object is returned at ``+1``, and the caller
4667is responsible for freeing it.
4668Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4669specifies that the object is returned at ``+0`` and the ownership remains with
4670the callee.
4671The annotation ``__attribute__((ns_consumes_self))`` specifies that
4672the Objective-C method call consumes the reference to ``self``, e.g. by
4673attaching it to a supplied parameter.
4674Additionally, parameters can have an annotation
4675``__attribute__((ns_consumed))``, which specifies that passing an owned object
4676as that parameter effectively transfers the ownership, and the caller is no
4677longer responsible for it.
4678These attributes affect code generation when interacting with ARC code, and
4679they are used by the Clang Static Analyzer.
4680
4681In C programs using CoreFoundation, a similar set of attributes:
4682``__attribute__((cf_returns_not_retained))``,
4683``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4684have the same respective semantics when applied to CoreFoundation objects.
4685These attributes affect code generation when interacting with ARC code, and
4686they are used by the Clang Static Analyzer.
4687
4688Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4689the same attribute family is present:
4690``__attribute__((os_returns_not_retained))``,
4691``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4692with the same respective semantics.
4693Similar to ``__attribute__((ns_consumes_self))``,
4694``__attribute__((os_consumes_this))`` specifies that the method call consumes
4695the reference to "this" (e.g., when attaching it to a different object supplied
4696as a parameter).
4697Out parameters (parameters the function is meant to write into,
4698either via pointers-to-pointers or references-to-pointers)
4699may be annotated with ``__attribute__((os_returns_retained))``
4700or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4701written into the out parameter should (or respectively should not) be released
4702after use.
4703Since often out parameters may or may not be written depending on the exit
4704code of the function,
4705annotations ``__attribute__((os_returns_retained_on_zero))``
4706and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4707an out parameter at ``+1`` is written if and only if the function returns a zero
4708(respectively non-zero) error code.
4709Observe that return-code-dependent out parameter annotations are only
4710available for retained out parameters, as non-retained object do not have to be
4711released by the callee.
4712These attributes are only used by the Clang Static Analyzer.
4713
4714The family of attributes ``X_returns_X_retained`` can be added to functions,
4715C++ methods, and Objective-C methods and properties.
4716Attributes ``X_consumed`` can be added to parameters of methods, functions,
4717and Objective-C methods.)reST";
4718
4719static const char AttrDoc_NSConsumesSelf[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4720(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4721convention (e.g. functions starting with "get" are assumed to return at
4722``+0``).
4723
4724It can be overridden using a family of the following attributes. In
4725Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4726a function communicates that the object is returned at ``+1``, and the caller
4727is responsible for freeing it.
4728Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4729specifies that the object is returned at ``+0`` and the ownership remains with
4730the callee.
4731The annotation ``__attribute__((ns_consumes_self))`` specifies that
4732the Objective-C method call consumes the reference to ``self``, e.g. by
4733attaching it to a supplied parameter.
4734Additionally, parameters can have an annotation
4735``__attribute__((ns_consumed))``, which specifies that passing an owned object
4736as that parameter effectively transfers the ownership, and the caller is no
4737longer responsible for it.
4738These attributes affect code generation when interacting with ARC code, and
4739they are used by the Clang Static Analyzer.
4740
4741In C programs using CoreFoundation, a similar set of attributes:
4742``__attribute__((cf_returns_not_retained))``,
4743``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4744have the same respective semantics when applied to CoreFoundation objects.
4745These attributes affect code generation when interacting with ARC code, and
4746they are used by the Clang Static Analyzer.
4747
4748Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4749the same attribute family is present:
4750``__attribute__((os_returns_not_retained))``,
4751``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4752with the same respective semantics.
4753Similar to ``__attribute__((ns_consumes_self))``,
4754``__attribute__((os_consumes_this))`` specifies that the method call consumes
4755the reference to "this" (e.g., when attaching it to a different object supplied
4756as a parameter).
4757Out parameters (parameters the function is meant to write into,
4758either via pointers-to-pointers or references-to-pointers)
4759may be annotated with ``__attribute__((os_returns_retained))``
4760or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4761written into the out parameter should (or respectively should not) be released
4762after use.
4763Since often out parameters may or may not be written depending on the exit
4764code of the function,
4765annotations ``__attribute__((os_returns_retained_on_zero))``
4766and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4767an out parameter at ``+1`` is written if and only if the function returns a zero
4768(respectively non-zero) error code.
4769Observe that return-code-dependent out parameter annotations are only
4770available for retained out parameters, as non-retained object do not have to be
4771released by the callee.
4772These attributes are only used by the Clang Static Analyzer.
4773
4774The family of attributes ``X_returns_X_retained`` can be added to functions,
4775C++ methods, and Objective-C methods and properties.
4776Attributes ``X_consumed`` can be added to parameters of methods, functions,
4777and Objective-C methods.)reST";
4778
4779static const char AttrDoc_NSErrorDomain[] = R"reST(In Cocoa frameworks in Objective-C, one can group related error codes in enums
4780and categorize these enums with error domains.
4781
4782The ``ns_error_domain`` attribute indicates a global ``NSString`` or
4783``CFString`` constant representing the error domain that an error code belongs
4784to. For pointer uniqueness and code size this is a constant symbol, not a
4785literal.
4786
4787The domain and error code need to be used together. The ``ns_error_domain``
4788attribute links error codes to their domain at the source level.
4789
4790This metadata is useful for documentation purposes, for static analysis, and for
4791improving interoperability between Objective-C and Swift. It is not used for
4792code generation in Objective-C.
4793
4794For example:
4795
4796 .. code-block:: objc
4797
4798 #define NS_ERROR_ENUM(_type, _name, _domain) \
4799 enum _name : _type _name; enum __attribute__((ns_error_domain(_domain))) _name : _type
4800
4801 extern NSString *const MyErrorDomain;
4802 typedef NS_ERROR_ENUM(unsigned char, MyErrorEnum, MyErrorDomain) {
4803 MyErrFirst,
4804 MyErrSecond,
4805 };)reST";
4806
4807static const char AttrDoc_NSReturnsAutoreleased[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4808(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4809convention (e.g. functions starting with "get" are assumed to return at
4810``+0``).
4811
4812It can be overridden using a family of the following attributes. In
4813Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4814a function communicates that the object is returned at ``+1``, and the caller
4815is responsible for freeing it.
4816Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4817specifies that the object is returned at ``+0`` and the ownership remains with
4818the callee.
4819The annotation ``__attribute__((ns_consumes_self))`` specifies that
4820the Objective-C method call consumes the reference to ``self``, e.g. by
4821attaching it to a supplied parameter.
4822Additionally, parameters can have an annotation
4823``__attribute__((ns_consumed))``, which specifies that passing an owned object
4824as that parameter effectively transfers the ownership, and the caller is no
4825longer responsible for it.
4826These attributes affect code generation when interacting with ARC code, and
4827they are used by the Clang Static Analyzer.
4828
4829In C programs using CoreFoundation, a similar set of attributes:
4830``__attribute__((cf_returns_not_retained))``,
4831``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4832have the same respective semantics when applied to CoreFoundation objects.
4833These attributes affect code generation when interacting with ARC code, and
4834they are used by the Clang Static Analyzer.
4835
4836Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4837the same attribute family is present:
4838``__attribute__((os_returns_not_retained))``,
4839``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4840with the same respective semantics.
4841Similar to ``__attribute__((ns_consumes_self))``,
4842``__attribute__((os_consumes_this))`` specifies that the method call consumes
4843the reference to "this" (e.g., when attaching it to a different object supplied
4844as a parameter).
4845Out parameters (parameters the function is meant to write into,
4846either via pointers-to-pointers or references-to-pointers)
4847may be annotated with ``__attribute__((os_returns_retained))``
4848or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4849written into the out parameter should (or respectively should not) be released
4850after use.
4851Since often out parameters may or may not be written depending on the exit
4852code of the function,
4853annotations ``__attribute__((os_returns_retained_on_zero))``
4854and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4855an out parameter at ``+1`` is written if and only if the function returns a zero
4856(respectively non-zero) error code.
4857Observe that return-code-dependent out parameter annotations are only
4858available for retained out parameters, as non-retained object do not have to be
4859released by the callee.
4860These attributes are only used by the Clang Static Analyzer.
4861
4862The family of attributes ``X_returns_X_retained`` can be added to functions,
4863C++ methods, and Objective-C methods and properties.
4864Attributes ``X_consumed`` can be added to parameters of methods, functions,
4865and Objective-C methods.)reST";
4866
4867static const char AttrDoc_NSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4868(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4869convention (e.g. functions starting with "get" are assumed to return at
4870``+0``).
4871
4872It can be overridden using a family of the following attributes. In
4873Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4874a function communicates that the object is returned at ``+1``, and the caller
4875is responsible for freeing it.
4876Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4877specifies that the object is returned at ``+0`` and the ownership remains with
4878the callee.
4879The annotation ``__attribute__((ns_consumes_self))`` specifies that
4880the Objective-C method call consumes the reference to ``self``, e.g. by
4881attaching it to a supplied parameter.
4882Additionally, parameters can have an annotation
4883``__attribute__((ns_consumed))``, which specifies that passing an owned object
4884as that parameter effectively transfers the ownership, and the caller is no
4885longer responsible for it.
4886These attributes affect code generation when interacting with ARC code, and
4887they are used by the Clang Static Analyzer.
4888
4889In C programs using CoreFoundation, a similar set of attributes:
4890``__attribute__((cf_returns_not_retained))``,
4891``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4892have the same respective semantics when applied to CoreFoundation objects.
4893These attributes affect code generation when interacting with ARC code, and
4894they are used by the Clang Static Analyzer.
4895
4896Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4897the same attribute family is present:
4898``__attribute__((os_returns_not_retained))``,
4899``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4900with the same respective semantics.
4901Similar to ``__attribute__((ns_consumes_self))``,
4902``__attribute__((os_consumes_this))`` specifies that the method call consumes
4903the reference to "this" (e.g., when attaching it to a different object supplied
4904as a parameter).
4905Out parameters (parameters the function is meant to write into,
4906either via pointers-to-pointers or references-to-pointers)
4907may be annotated with ``__attribute__((os_returns_retained))``
4908or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4909written into the out parameter should (or respectively should not) be released
4910after use.
4911Since often out parameters may or may not be written depending on the exit
4912code of the function,
4913annotations ``__attribute__((os_returns_retained_on_zero))``
4914and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4915an out parameter at ``+1`` is written if and only if the function returns a zero
4916(respectively non-zero) error code.
4917Observe that return-code-dependent out parameter annotations are only
4918available for retained out parameters, as non-retained object do not have to be
4919released by the callee.
4920These attributes are only used by the Clang Static Analyzer.
4921
4922The family of attributes ``X_returns_X_retained`` can be added to functions,
4923C++ methods, and Objective-C methods and properties.
4924Attributes ``X_consumed`` can be added to parameters of methods, functions,
4925and Objective-C methods.)reST";
4926
4927static const char AttrDoc_NSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4928(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4929convention (e.g. functions starting with "get" are assumed to return at
4930``+0``).
4931
4932It can be overridden using a family of the following attributes. In
4933Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4934a function communicates that the object is returned at ``+1``, and the caller
4935is responsible for freeing it.
4936Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4937specifies that the object is returned at ``+0`` and the ownership remains with
4938the callee.
4939The annotation ``__attribute__((ns_consumes_self))`` specifies that
4940the Objective-C method call consumes the reference to ``self``, e.g. by
4941attaching it to a supplied parameter.
4942Additionally, parameters can have an annotation
4943``__attribute__((ns_consumed))``, which specifies that passing an owned object
4944as that parameter effectively transfers the ownership, and the caller is no
4945longer responsible for it.
4946These attributes affect code generation when interacting with ARC code, and
4947they are used by the Clang Static Analyzer.
4948
4949In C programs using CoreFoundation, a similar set of attributes:
4950``__attribute__((cf_returns_not_retained))``,
4951``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4952have the same respective semantics when applied to CoreFoundation objects.
4953These attributes affect code generation when interacting with ARC code, and
4954they are used by the Clang Static Analyzer.
4955
4956Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4957the same attribute family is present:
4958``__attribute__((os_returns_not_retained))``,
4959``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4960with the same respective semantics.
4961Similar to ``__attribute__((ns_consumes_self))``,
4962``__attribute__((os_consumes_this))`` specifies that the method call consumes
4963the reference to "this" (e.g., when attaching it to a different object supplied
4964as a parameter).
4965Out parameters (parameters the function is meant to write into,
4966either via pointers-to-pointers or references-to-pointers)
4967may be annotated with ``__attribute__((os_returns_retained))``
4968or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4969written into the out parameter should (or respectively should not) be released
4970after use.
4971Since often out parameters may or may not be written depending on the exit
4972code of the function,
4973annotations ``__attribute__((os_returns_retained_on_zero))``
4974and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4975an out parameter at ``+1`` is written if and only if the function returns a zero
4976(respectively non-zero) error code.
4977Observe that return-code-dependent out parameter annotations are only
4978available for retained out parameters, as non-retained object do not have to be
4979released by the callee.
4980These attributes are only used by the Clang Static Analyzer.
4981
4982The family of attributes ``X_returns_X_retained`` can be added to functions,
4983C++ methods, and Objective-C methods and properties.
4984Attributes ``X_consumed`` can be added to parameters of methods, functions,
4985and Objective-C methods.)reST";
4986
4987static const char AttrDoc_Naked[] = R"reST(No documentation.)reST";
4988
4989static const char AttrDoc_NoAlias[] = R"reST(The ``noalias`` attribute indicates that the only memory accesses inside
4990function are loads and stores from objects pointed to by its pointer-typed
4991arguments, with arbitrary offsets.)reST";
4992
4993static const char AttrDoc_NoBuiltin[] = R"reST(The ``__attribute__((no_builtin))`` is similar to the ``-fno-builtin`` flag
4994except it is specific to the body of a function. The attribute may also be
4995applied to a virtual function but has no effect on the behavior of overriding
4996functions in a derived class.
4997
4998It accepts one or more strings corresponding to the specific names of the
4999builtins to disable (e.g. "memcpy", "memset").
5000If the attribute is used without parameters it will disable all buitins at
5001once.
5002
5003.. code-block:: c++
5004
5005 // The compiler is not allowed to add any builtin to foo's body.
5006 void foo(char* data, size_t count) __attribute__((no_builtin)) {
5007 // The compiler is not allowed to convert the loop into
5008 // `__builtin_memset(data, 0xFE, count);`.
5009 for (size_t i = 0; i < count; ++i)
5010 data[i] = 0xFE;
5011 }
5012
5013 // The compiler is not allowed to add the `memcpy` builtin to bar's body.
5014 void bar(char* data, size_t count) __attribute__((no_builtin("memcpy"))) {
5015 // The compiler is allowed to convert the loop into
5016 // `__builtin_memset(data, 0xFE, count);` but cannot generate any
5017 // `__builtin_memcpy`
5018 for (size_t i = 0; i < count; ++i)
5019 data[i] = 0xFE;
5020 })reST";
5021
5022static const char AttrDoc_NoCommon[] = R"reST(No documentation.)reST";
5023
5024static const char AttrDoc_NoConvergent[] = R"reST(This attribute prevents a function from being treated as convergent; when a
5025function is marked ``noconvergent``, calls to that function are not
5026automatically assumed to be convergent, unless such calls are explicitly marked
5027as ``convergent``. If a statement is marked as ``noconvergent``, any calls to
5028inline ``asm`` in that statement are no longer treated as convergent.
5029
5030In languages following SPMD/SIMT programming model, e.g., CUDA/HIP, function
5031declarations and inline asm calls are treated as convergent by default for
5032correctness. This ``noconvergent`` attribute is helpful for developers to
5033prevent them from being treated as convergent when it's safe.
5034
5035.. code-block:: c
5036
5037 __device__ float bar(float);
5038 __device__ float foo(float) __attribute__((noconvergent)) {}
5039
5040 __device__ int example(void) {
5041 float x;
5042 [[clang::noconvergent]] x = bar(x); // no effect on convergence
5043 [[clang::noconvergent]] { asm volatile ("nop"); } // the asm call is non-convergent
5044 })reST";
5045
5046static const char AttrDoc_NoDebug[] = R"reST(The ``nodebug`` attribute allows you to suppress debugging information for a
5047function or method, for a variable that is not a parameter or a non-static
5048data member, or for a typedef or using declaration.)reST";
5049
5050static const char AttrDoc_NoDeref[] = R"reST(The ``noderef`` attribute causes clang to diagnose dereferences of annotated pointer types.
5051This is ideally used with pointers that point to special memory which cannot be read
5052from or written to, but allowing for the pointer to be used in pointer arithmetic.
5053The following are examples of valid expressions where dereferences are diagnosed:
5054
5055.. code-block:: c
5056
5057 int __attribute__((noderef)) *p;
5058 int x = *p; // warning
5059
5060 int __attribute__((noderef)) **p2;
5061 x = **p2; // warning
5062
5063 int * __attribute__((noderef)) *p3;
5064 p = *p3; // warning
5065
5066 struct S {
5067 int a;
5068 };
5069 struct S __attribute__((noderef)) *s;
5070 x = s->a; // warning
5071 x = (*s).a; // warning
5072
5073Not all dereferences may diagnose a warning if the value directed by the pointer may not be
5074accessed. The following are examples of valid expressions where may not be diagnosed:
5075
5076.. code-block:: c
5077
5078 int *q;
5079 int __attribute__((noderef)) *p;
5080 q = &*p;
5081 q = *&p;
5082
5083 struct S {
5084 int a;
5085 };
5086 struct S __attribute__((noderef)) *s;
5087 p = &s->a;
5088 p = &(*s).a;
5089
5090``noderef`` is currently only supported for pointers and arrays and not usable
5091for references or Objective-C object pointers.
5092
5093.. code-block:: c++
5094
5095 int x = 2;
5096 int __attribute__((noderef)) &y = x; // warning: 'noderef' can only be used on an array or pointer type
5097
5098.. code-block:: objc
5099
5100 id __attribute__((noderef)) obj = [NSObject new]; // warning: 'noderef' can only be used on an array or pointer type)reST";
5101
5102static const char AttrDoc_NoDestroy[] = R"reST(The ``no_destroy`` attribute specifies that a variable with static or thread
5103storage duration shouldn't have its exit-time destructor run. Annotating every
5104static and thread duration variable with this attribute is equivalent to
5105invoking clang with -fno-c++-static-destructors.
5106
5107If a variable is declared with this attribute, clang doesn't access check or
5108generate the type's destructor. If you have a type that you only want to be
5109annotated with ``no_destroy``, you can therefore declare the destructor private:
5110
5111.. code-block:: c++
5112
5113 struct only_no_destroy {
5114 only_no_destroy();
5115 private:
5116 ~only_no_destroy();
5117 };
5118
5119 [[clang::no_destroy]] only_no_destroy global; // fine!
5120
5121Note that destructors are still required for subobjects of aggregates annotated
5122with this attribute. This is because previously constructed subobjects need to
5123be destroyed if an exception gets thrown before the initialization of the
5124complete object is complete. For instance:
5125
5126.. code-block:: c++
5127
5128 void f() {
5129 try {
5130 [[clang::no_destroy]]
5131 static only_no_destroy array[10]; // error, only_no_destroy has a private destructor.
5132 } catch (...) {
5133 // Handle the error
5134 }
5135 }
5136
5137Here, if the construction of ``array[9]`` fails with an exception, ``array[0..8]``
5138will be destroyed, so the element's destructor needs to be accessible.)reST";
5139
5140static const char AttrDoc_NoDuplicate[] = R"reST(The ``noduplicate`` attribute can be placed on function declarations to control
5141whether function calls to this function can be duplicated or not as a result of
5142optimizations. This is required for the implementation of functions with
5143certain special requirements, like the OpenCL "barrier" function, that might
5144need to be run concurrently by all the threads that are executing in lockstep
5145on the hardware. For example this attribute applied on the function
5146"nodupfunc" in the code below avoids that:
5147
5148.. code-block:: c
5149
5150 void nodupfunc() __attribute__((noduplicate));
5151 // Setting it as a C++11 attribute is also valid
5152 // void nodupfunc() [[clang::noduplicate]];
5153 void foo();
5154 void bar();
5155
5156 nodupfunc();
5157 if (a > n) {
5158 foo();
5159 } else {
5160 bar();
5161 }
5162
5163gets possibly modified by some optimizations into code similar to this:
5164
5165.. code-block:: c
5166
5167 if (a > n) {
5168 nodupfunc();
5169 foo();
5170 } else {
5171 nodupfunc();
5172 bar();
5173 }
5174
5175where the call to "nodupfunc" is duplicated and sunk into the two branches
5176of the condition.)reST";
5177
5178static const char AttrDoc_NoEscape[] = R"reST(``noescape`` placed on a function parameter of a pointer type is used to inform
5179the compiler that the pointer cannot escape: that is, no reference to the object
5180the pointer points to that is derived from the parameter value will survive
5181after the function returns. Users are responsible for making sure parameters
5182annotated with ``noescape`` do not actually escape. Calling ``free()`` on such
5183a parameter does not constitute an escape.
5184
5185For example:
5186
5187.. code-block:: c
5188
5189 int *gp;
5190
5191 void nonescapingFunc(__attribute__((noescape)) int *p) {
5192 *p += 100; // OK.
5193 }
5194
5195 void escapingFunc(__attribute__((noescape)) int *p) {
5196 gp = p; // Not OK.
5197 }
5198
5199Additionally, when the parameter is a `block pointer
5200<https://clang.llvm.org/docs/BlockLanguageSpec.html>`, the same restriction
5201applies to copies of the block. For example:
5202
5203.. code-block:: c
5204
5205 typedef void (^BlockTy)();
5206 BlockTy g0, g1;
5207
5208 void nonescapingFunc(__attribute__((noescape)) BlockTy block) {
5209 block(); // OK.
5210 }
5211
5212 void escapingFunc(__attribute__((noescape)) BlockTy block) {
5213 g0 = block; // Not OK.
5214 g1 = Block_copy(block); // Not OK either.
5215 })reST";
5216
5217static const char AttrDoc_NoFieldProtection[] = R"reST(No documentation.)reST";
5218
5219static const char AttrDoc_NoInline[] = R"reST(This function attribute suppresses the inlining of a function at the call sites
5220of the function.
5221
5222``[[clang::noinline]]`` spelling can be used as a statement attribute; other
5223spellings of the attribute are not supported on statements. If a statement is
5224marked ``[[clang::noinline]]`` and contains calls, those calls inside the
5225statement will not be inlined by the compiler.
5226
5227``__noinline__`` can be used as a keyword in CUDA/HIP languages. This is to
5228avoid diagnostics due to usage of ``__attribute__((__noinline__))``
5229with ``__noinline__`` defined as a macro as ``__attribute__((noinline))``.
5230
5231.. code-block:: c
5232
5233 int example(void) {
5234 int r;
5235 [[clang::noinline]] foo();
5236 [[clang::noinline]] r = bar();
5237 return r;
5238 })reST";
5239
5240static const char AttrDoc_NoInstrumentFunction[] = R"reST(No documentation.)reST";
5241
5242static const char AttrDoc_NoMerge[] = R"reST(If a statement is marked ``nomerge`` and contains call expressions, those call
5243expressions inside the statement will not be merged during optimization. This
5244attribute can be used to prevent the optimizer from obscuring the source
5245location of certain calls. For example, it will prevent tail merging otherwise
5246identical code sequences that raise an exception or terminate the program. Tail
5247merging normally reduces the precision of source location information, making
5248stack traces less useful for debugging. This attribute gives the user control
5249over the tradeoff between code size and debug information precision.
5250
5251``nomerge`` attribute can also be used as function attribute to prevent all
5252calls to the specified function from merging. It has no effect on indirect
5253calls to such functions. For example:
5254
5255.. code-block:: c++
5256
5257 [[clang::nomerge]] void foo(int) {}
5258
5259 void bar(int x) {
5260 auto *ptr = foo;
5261 if (x) foo(1); else foo(2); // will not be merged
5262 if (x) ptr(1); else ptr(2); // indirect call, can be merged
5263 }
5264
5265``nomerge`` attribute can also be used for pointers to functions to
5266prevent calls through such pointer from merging. In such case the
5267effect applies only to a specific function pointer. For example:
5268
5269.. code-block:: c++
5270
5271 [[clang::nomerge]] void (*foo)(int);
5272
5273 void bar(int x) {
5274 auto *ptr = foo;
5275 if (x) foo(1); else foo(2); // will not be merged
5276 if (x) ptr(1); else ptr(2); // 'ptr' has no 'nomerge' attribute, can be merged
5277 })reST";
5278
5279static const char AttrDoc_NoMicroMips[] = R"reST(Clang supports the GNU style ``__attribute__((micromips))`` and
5280``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes
5281may be attached to a function definition and instructs the backend to generate
5282or not to generate microMIPS code for that function.
5283
5284These attributes override the ``-mmicromips`` and ``-mno-micromips`` options
5285on the command line.)reST";
5286
5287static const char AttrDoc_NoMips16[] = R"reST(No documentation.)reST";
5288
5289static const char AttrDoc_NoOutline[] = R"reST(This function attribute suppresses outlining from the annotated function.
5290
5291Outlining is the process where common parts of separate functions are extracted
5292into a separate function (or assembly snippet), and calls to that function or
5293snippet are inserted in the original functions. In this way, it can be seen as
5294the opposite of inlining. It can help to reduce code size.)reST";
5295
5296static const char AttrDoc_NoProfileFunction[] = R"reST(Use the ``no_profile_instrument_function`` attribute on a function declaration
5297to denote that the compiler should not instrument the function with
5298profile-related instrumentation, such as via the
5299``-fprofile-generate`` / ``-fprofile-instr-generate`` /
5300``-fcs-profile-generate`` / ``-fprofile-arcs`` flags.)reST";
5301
5302static const char AttrDoc_NoRandomizeLayout[] = R"reST(The attribute ``randomize_layout``, when attached to a C structure, selects it
5303for structure layout field randomization; a compile-time hardening technique. A
5304"seed" value, is specified via the ``-frandomize-layout-seed=`` command line flag.
5305For example:
5306
5307.. code-block:: bash
5308
5309 SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
5310 make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
5311
5312You can also supply the seed in a file with ``-frandomize-layout-seed-file=``.
5313For example:
5314
5315.. code-block:: bash
5316
5317 od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
5318 make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
5319
5320The randomization is deterministic based for a given seed, so the entire
5321program should be compiled with the same seed, but keep the seed safe
5322otherwise.
5323
5324The attribute ``no_randomize_layout``, when attached to a C structure,
5325instructs the compiler that this structure should not have its field layout
5326randomized.)reST";
5327
5328static const char AttrDoc_NoReturn[] = R"reST(No documentation.)reST";
5329
5330static const char AttrDoc_NoSanitize[] = R"reST(Use the ``no_sanitize`` attribute on a function or a global variable
5331declaration to specify that a particular instrumentation or set of
5332instrumentations should not be applied.
5333
5334The attribute takes a list of string literals with the following accepted
5335values:
5336
5337* all values accepted by ``-fno-sanitize=``;
5338* ``coverage``, to disable SanitizerCoverage instrumentation.
5339
5340For example, ``__attribute__((no_sanitize("address", "thread")))`` specifies
5341that AddressSanitizer and ThreadSanitizer should not be applied to the function
5342or variable. Using ``__attribute__((no_sanitize("coverage")))`` specifies that
5343SanitizerCoverage should not be applied to the function.
5344
5345See :ref:`Controlling Code Generation <controlling-code-generation>` for a
5346full list of supported sanitizer flags.)reST";
5347
5348static const char AttrDoc_NoSpecializations[] = R"reST(``[[clang::no_specializations]]`` can be applied to function, class, or variable
5349templates which should not be explicitly specialized by users. This is primarily
5350used to diagnose user specializations of standard library type traits.)reST";
5351
5352static const char AttrDoc_NoSpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
5353 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_
5354 is *not* needed for the function body. This can also be applied to a method
5355 in Objective C. This attribute will take precedence over the command line flag in
5356 the case where `-mspeculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified.
5357
5358 Warning: This attribute may not prevent Speculative Load Hardening from being
5359 enabled for a function which inlines a function that has the
5360 'speculative_load_hardening' attribute. This is intended to provide a
5361 maximally conservative model where the code that is marked with the
5362 'speculative_load_hardening' attribute will always (even when inlined)
5363 be hardened. A user of this attribute may want to mark functions called by
5364 a function they do not want to be hardened with the 'noinline' attribute.
5365
5366 For example:
5367
5368 .. code-block:: c
5369
5370 __attribute__((speculative_load_hardening))
5371 int foo(int i) {
5372 return i;
5373 }
5374
5375 // Note: bar() may still have speculative load hardening enabled if
5376 // foo() is inlined into bar(). Mark foo() with __attribute__((noinline))
5377 // to avoid this situation.
5378 __attribute__((no_speculative_load_hardening))
5379 int bar(int i) {
5380 return foo(i);
5381 })reST";
5382
5383static const char AttrDoc_NoSplitStack[] = R"reST(The ``no_split_stack`` attribute disables the emission of the split stack
5384preamble for a particular function. It has no effect if ``-fsplit-stack``
5385is not specified.)reST";
5386
5387static const char AttrDoc_NoStackProtector[] = R"reST(Clang supports the GNU style ``__attribute__((no_stack_protector))`` and Microsoft
5388style ``__declspec(safebuffers)`` attribute which disables
5389the stack protector on the specified function. This attribute is useful for
5390selectively disabling the stack protector on some functions when building with
5391``-fstack-protector`` compiler option.
5392
5393For example, it disables the stack protector for the function ``foo`` but function
5394``bar`` will still be built with the stack protector with the ``-fstack-protector``
5395option.
5396
5397.. code-block:: c
5398
5399 int __attribute__((no_stack_protector))
5400 foo (int x); // stack protection will be disabled for foo.
5401
5402 int bar(int y); // bar can be built with the stack protector.)reST";
5403
5404static const char AttrDoc_NoThreadSafetyAnalysis[] = R"reST(No documentation.)reST";
5405
5406static const char AttrDoc_NoThrow[] = R"reST(Clang supports the GNU style ``__attribute__((nothrow))`` and Microsoft style
5407``__declspec(nothrow)`` attribute as an equivalent of ``noexcept`` on function
5408declarations. This attribute informs the compiler that the annotated function
5409does not throw an exception. This prevents exception-unwinding. This attribute
5410is particularly useful on functions in the C Standard Library that are
5411guaranteed to not throw an exception.)reST";
5412
5413static const char AttrDoc_NoTrivialAutoVarInit[] = R"reST(The ``__declspec(no_init_all)`` attribute disables the automatic initialization that the
5414`-ftrivial-auto-var-init`_ flag would have applied to locals in a marked function, or instances of
5415a marked type. Note that this attribute has no effect for locals that are automatically initialized
5416without the `-ftrivial-auto-var-init`_ flag.
5417
5418.. _`-ftrivial-auto-var-init`: ClangCommandLineReference.html#cmdoption-clang-ftrivial-auto-var-init)reST";
5419
5420static const char AttrDoc_NoUniqueAddress[] = R"reST(The ``no_unique_address`` attribute allows tail padding in a non-static data
5421member to overlap other members of the enclosing class (and in the special
5422case when the type is empty, permits it to fully overlap other members).
5423The field is laid out as if a base class were encountered at the corresponding
5424point within the class (except that it does not share a vptr with the enclosing
5425object).
5426
5427Example usage:
5428
5429.. code-block:: c++
5430
5431 template<typename T, typename Alloc> struct my_vector {
5432 T *p;
5433 [[no_unique_address]] Alloc alloc;
5434 // ...
5435 };
5436 static_assert(sizeof(my_vector<int, std::allocator<int>>) == sizeof(int*));
5437
5438``[[no_unique_address]]`` is a standard C++20 attribute. Clang supports its use
5439in C++11 onwards.
5440
5441On MSVC targets, ``[[no_unique_address]]`` is ignored; use
5442``[[msvc::no_unique_address]]`` instead. Currently there is no guarantee of ABI
5443compatibility or stability with MSVC.)reST";
5444
5445static const char AttrDoc_NoUwtable[] = R"reST(Clang supports the ``nouwtable`` attribute which skips emitting
5446the unwind table entry for the specified function. This attribute is useful for
5447selectively emitting the unwind table entry on some functions when building with
5448``-funwind-tables`` compiler option.)reST";
5449
5450static const char AttrDoc_NonAllocating[] = R"reST(Declares that a function or function type either does or does not allocate heap memory, according
5451to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5452is false, the attribute is equivalent to ``allocating``.)reST";
5453
5454static const char AttrDoc_NonBlocking[] = R"reST(Declares that a function or function type either does or does not block in any way, according
5455to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5456is false, the attribute is equivalent to ``blocking``.
5457
5458For the purposes of diagnostics, ``nonblocking`` is considered to include the
5459``nonallocating`` guarantee and is therefore a "stronger" constraint or attribute.)reST";
5460
5461static const char AttrDoc_NonNull[] = R"reST(The ``nonnull`` attribute indicates that some function parameters must not be
5462null, and can be used in several different ways. It's original usage
5463(`from GCC <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes>`_)
5464is as a function (or Objective-C method) attribute that specifies which
5465parameters of the function are nonnull in a comma-separated list. For example:
5466
5467 .. code-block:: c
5468
5469 extern void * my_memcpy (void *dest, const void *src, size_t len)
5470 __attribute__((nonnull (1, 2)));
5471
5472Here, the ``nonnull`` attribute indicates that parameters 1 and 2
5473cannot have a null value. Omitting the parenthesized list of parameter indices
5474means that all parameters of pointer type cannot be null:
5475
5476 .. code-block:: c
5477
5478 extern void * my_memcpy (void *dest, const void *src, size_t len)
5479 __attribute__((nonnull));
5480
5481Clang also allows the ``nonnull`` attribute to be placed directly on a function
5482(or Objective-C method) parameter, eliminating the need to specify the
5483parameter index ahead of type. For example:
5484
5485 .. code-block:: c
5486
5487 extern void * my_memcpy (void *dest __attribute__((nonnull)),
5488 const void *src __attribute__((nonnull)), size_t len);
5489
5490Note that the ``nonnull`` attribute indicates that passing null to a non-null
5491parameter is undefined behavior, which the optimizer may take advantage of to,
5492e.g., remove null checks. The ``_Nonnull`` type qualifier indicates that a
5493pointer cannot be null in a more general manner (because it is part of the type
5494system) and does not imply undefined behavior, making it more widely applicable.)reST";
5495
5496static const char AttrDoc_NonString[] = R"reST(The ``nonstring`` attribute can be applied to the declaration of a variable or
5497a field whose type is a character pointer or character array to specify that
5498the buffer is not intended to behave like a null-terminated string. This will
5499silence diagnostics with code like:
5500
5501.. code-block:: c
5502
5503 char BadStr[3] = "foo"; // No space for the null terminator, diagnosed
5504 __attribute__((nonstring)) char NotAStr[3] = "foo"; // Not diagnosed)reST";
5505
5506static const char AttrDoc_NotTailCalled[] = R"reST(The ``not_tail_called`` attribute prevents tail-call optimization on statically
5507bound calls. Objective-c methods, and functions marked as ``always_inline``
5508cannot be marked as ``not_tail_called``.
5509
5510For example, it prevents tail-call optimization in the following case:
5511
5512 .. code-block:: c
5513
5514 int __attribute__((not_tail_called)) foo1(int);
5515
5516 int foo2(int a) {
5517 return foo1(a); // No tail-call optimization on direct calls.
5518 }
5519
5520However, it doesn't prevent tail-call optimization in this case:
5521
5522 .. code-block:: c
5523
5524 int __attribute__((not_tail_called)) foo1(int);
5525
5526 int foo2(int a) {
5527 int (*fn)(int) = &foo1;
5528
5529 // not_tail_called has no effect on an indirect call even if the call can
5530 // be resolved at compile time.
5531 return (*fn)(a);
5532 }
5533
5534Generally, marking an overriding virtual function as ``not_tail_called`` is
5535not useful, because this attribute is a property of the static type. Calls
5536made through a pointer or reference to the base class type will respect
5537the ``not_tail_called`` attribute of the base class's member function,
5538regardless of the runtime destination of the call:
5539
5540 .. code-block:: c++
5541
5542 struct Foo { virtual void f(); };
5543 struct Bar : Foo {
5544 [[clang::not_tail_called]] void f() override;
5545 };
5546 void callera(Bar& bar) {
5547 Foo& foo = bar;
5548 // not_tail_called has no effect on here, even though the
5549 // underlying method is f from Bar.
5550 foo.f();
5551 bar.f(); // No tail-call optimization on here.
5552 })reST";
5553
5554static const char AttrDoc_OMPAllocateDecl[] = R"reST()reST";
5555
5556static const char AttrDoc_OMPAssume[] = R"reST(Clang supports the ``[[omp::assume("assumption")]]`` attribute to
5557provide additional information to the optimizer. The string-literal, here
5558"assumption", will be attached to the function declaration such that later
5559analysis and optimization passes can assume the "assumption" to hold.
5560This is similar to :ref:`__builtin_assume <langext-__builtin_assume>` but
5561instead of an expression that can be assumed to be non-zero, the assumption is
5562expressed as a string and it holds for the entire function.
5563
5564A function can have multiple assume attributes and they propagate from prior
5565declarations to later definitions. Multiple assumptions are aggregated into a
5566single comma separated string. Thus, one can provide multiple assumptions via
5567a comma separated string, i.a.,
5568``[[omp::assume("assumption1,assumption2")]]``.
5569
5570While LLVM plugins might provide more assumption strings, the default LLVM
5571optimization passes are aware of the following assumptions:
5572
5573 .. code-block:: none
5574
5575 "omp_no_openmp"
5576 "omp_no_openmp_routines"
5577 "omp_no_parallelism"
5578 "omp_no_openmp_constructs"
5579
5580The OpenMP standard defines the meaning of OpenMP assumptions ("omp_XYZ" is
5581spelled "XYZ" in the `OpenMP 5.1 Standard`_).
5582
5583.. _`OpenMP 5.1 Standard`: https://www.openmp.org/spec-html/5.1/openmpsu37.html#x56-560002.5.2)reST";
5584
5585static const char AttrDoc_OMPCaptureKind[] = R"reST()reST";
5586
5587static const char AttrDoc_OMPCaptureNoInit[] = R"reST()reST";
5588
5589static const char AttrDoc_OMPDeclareSimdDecl[] = R"reST(The ``declare simd`` construct can be applied to a function to enable the creation
5590of one or more versions that can process multiple arguments using SIMD
5591instructions from a single invocation in a SIMD loop. The ``declare simd``
5592directive is a declarative directive. There may be multiple ``declare simd``
5593directives for a function. The use of a ``declare simd`` construct on a function
5594enables the creation of SIMD versions of the associated function that can be
5595used to process multiple arguments from a single invocation from a SIMD loop
5596concurrently.
5597The syntax of the ``declare simd`` construct is as follows:
5598
5599 .. code-block:: none
5600
5601 #pragma omp declare simd [clause[[,] clause] ...] new-line
5602 [#pragma omp declare simd [clause[[,] clause] ...] new-line]
5603 [...]
5604 function definition or declaration
5605
5606where clause is one of the following:
5607
5608 .. code-block:: none
5609
5610 simdlen(length)
5611 linear(argument-list[:constant-linear-step])
5612 aligned(argument-list[:alignment])
5613 uniform(argument-list)
5614 inbranch
5615 notinbranch)reST";
5616
5617static const char AttrDoc_OMPDeclareTargetDecl[] = R"reST(The ``declare target`` directive specifies that variables and functions are mapped
5618to a device for OpenMP offload mechanism.
5619
5620The syntax of the declare target directive is as follows:
5621
5622 .. code-block:: c
5623
5624 #pragma omp declare target new-line
5625 declarations-definition-seq
5626 #pragma omp end declare target new-line
5627
5628or
5629
5630 .. code-block:: c
5631
5632 #pragma omp declare target (extended-list) new-line
5633
5634or
5635
5636 .. code-block:: c
5637
5638 #pragma omp declare target clause[ [,] clause ... ] new-line
5639
5640where clause is one of the following:
5641
5642
5643 .. code-block:: c
5644
5645 to(extended-list)
5646 link(list)
5647 device_type(host | nohost | any))reST";
5648
5649static const char AttrDoc_OMPDeclareVariant[] = R"reST(The ``declare variant`` directive declares a specialized variant of a base
5650function and specifies the context in which that specialized variant is used.
5651The declare variant directive is a declarative directive.
5652The syntax of the ``declare variant`` construct is as follows:
5653
5654 .. code-block:: none
5655
5656 #pragma omp declare variant(variant-func-id) clause new-line
5657 [#pragma omp declare variant(variant-func-id) clause new-line]
5658 [...]
5659 function definition or declaration
5660
5661where clause is one of the following:
5662
5663 .. code-block:: none
5664
5665 match(context-selector-specification)
5666
5667and where ``variant-func-id`` is the name of a function variant that is either a
5668base language identifier or, for C++, a template-id.
5669
5670Clang provides the following context selector extensions, used via
5671``implementation={extension(EXTENSION)}``:
5672
5673 .. code-block:: none
5674
5675 match_all
5676 match_any
5677 match_none
5678 disable_implicit_base
5679 allow_templates
5680 bind_to_declaration
5681
5682The match extensions change when the *entire* context selector is considered a
5683match for an OpenMP context. The default is ``all``, with ``none`` no trait in the
5684selector is allowed to be in the OpenMP context, with ``any`` a single trait in
5685both the selector and OpenMP context is sufficient. Only a single match
5686extension trait is allowed per context selector.
5687The disable extensions remove default effects of the ``begin declare variant``
5688applied to a definition. If ``disable_implicit_base`` is given, we will not
5689introduce an implicit base function for a variant if no base function was
5690found. The variant is still generated but will never be called, due to the
5691absence of a base function and consequently calls to a base function.
5692The allow extensions change when the ``begin declare variant`` effect is
5693applied to a definition. If ``allow_templates`` is given, template function
5694definitions are considered as specializations of existing or assumed template
5695declarations with the same name. The template parameters for the base functions
5696are used to instantiate the specialization. If ``bind_to_declaration`` is given,
5697apply the same variant rules to function declarations. This allows the user to
5698override declarations with only a function declaration.)reST";
5699
5700static const char AttrDoc_OMPGroupPrivateDecl[] = R"reST()reST";
5701
5702static const char AttrDoc_OMPReferencedVar[] = R"reST()reST";
5703
5704static const char AttrDoc_OMPTargetIndirectCall[] = R"reST()reST";
5705
5706static const char AttrDoc_OMPThreadPrivateDecl[] = R"reST()reST";
5707
5708static const char AttrDoc_OSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5709(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5710convention (e.g. functions starting with "get" are assumed to return at
5711``+0``).
5712
5713It can be overridden using a family of the following attributes. In
5714Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5715a function communicates that the object is returned at ``+1``, and the caller
5716is responsible for freeing it.
5717Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5718specifies that the object is returned at ``+0`` and the ownership remains with
5719the callee.
5720The annotation ``__attribute__((ns_consumes_self))`` specifies that
5721the Objective-C method call consumes the reference to ``self``, e.g. by
5722attaching it to a supplied parameter.
5723Additionally, parameters can have an annotation
5724``__attribute__((ns_consumed))``, which specifies that passing an owned object
5725as that parameter effectively transfers the ownership, and the caller is no
5726longer responsible for it.
5727These attributes affect code generation when interacting with ARC code, and
5728they are used by the Clang Static Analyzer.
5729
5730In C programs using CoreFoundation, a similar set of attributes:
5731``__attribute__((cf_returns_not_retained))``,
5732``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5733have the same respective semantics when applied to CoreFoundation objects.
5734These attributes affect code generation when interacting with ARC code, and
5735they are used by the Clang Static Analyzer.
5736
5737Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5738the same attribute family is present:
5739``__attribute__((os_returns_not_retained))``,
5740``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5741with the same respective semantics.
5742Similar to ``__attribute__((ns_consumes_self))``,
5743``__attribute__((os_consumes_this))`` specifies that the method call consumes
5744the reference to "this" (e.g., when attaching it to a different object supplied
5745as a parameter).
5746Out parameters (parameters the function is meant to write into,
5747either via pointers-to-pointers or references-to-pointers)
5748may be annotated with ``__attribute__((os_returns_retained))``
5749or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5750written into the out parameter should (or respectively should not) be released
5751after use.
5752Since often out parameters may or may not be written depending on the exit
5753code of the function,
5754annotations ``__attribute__((os_returns_retained_on_zero))``
5755and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5756an out parameter at ``+1`` is written if and only if the function returns a zero
5757(respectively non-zero) error code.
5758Observe that return-code-dependent out parameter annotations are only
5759available for retained out parameters, as non-retained object do not have to be
5760released by the callee.
5761These attributes are only used by the Clang Static Analyzer.
5762
5763The family of attributes ``X_returns_X_retained`` can be added to functions,
5764C++ methods, and Objective-C methods and properties.
5765Attributes ``X_consumed`` can be added to parameters of methods, functions,
5766and Objective-C methods.)reST";
5767
5768static const char AttrDoc_OSConsumesThis[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5769(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5770convention (e.g. functions starting with "get" are assumed to return at
5771``+0``).
5772
5773It can be overridden using a family of the following attributes. In
5774Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5775a function communicates that the object is returned at ``+1``, and the caller
5776is responsible for freeing it.
5777Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5778specifies that the object is returned at ``+0`` and the ownership remains with
5779the callee.
5780The annotation ``__attribute__((ns_consumes_self))`` specifies that
5781the Objective-C method call consumes the reference to ``self``, e.g. by
5782attaching it to a supplied parameter.
5783Additionally, parameters can have an annotation
5784``__attribute__((ns_consumed))``, which specifies that passing an owned object
5785as that parameter effectively transfers the ownership, and the caller is no
5786longer responsible for it.
5787These attributes affect code generation when interacting with ARC code, and
5788they are used by the Clang Static Analyzer.
5789
5790In C programs using CoreFoundation, a similar set of attributes:
5791``__attribute__((cf_returns_not_retained))``,
5792``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5793have the same respective semantics when applied to CoreFoundation objects.
5794These attributes affect code generation when interacting with ARC code, and
5795they are used by the Clang Static Analyzer.
5796
5797Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5798the same attribute family is present:
5799``__attribute__((os_returns_not_retained))``,
5800``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5801with the same respective semantics.
5802Similar to ``__attribute__((ns_consumes_self))``,
5803``__attribute__((os_consumes_this))`` specifies that the method call consumes
5804the reference to "this" (e.g., when attaching it to a different object supplied
5805as a parameter).
5806Out parameters (parameters the function is meant to write into,
5807either via pointers-to-pointers or references-to-pointers)
5808may be annotated with ``__attribute__((os_returns_retained))``
5809or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5810written into the out parameter should (or respectively should not) be released
5811after use.
5812Since often out parameters may or may not be written depending on the exit
5813code of the function,
5814annotations ``__attribute__((os_returns_retained_on_zero))``
5815and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5816an out parameter at ``+1`` is written if and only if the function returns a zero
5817(respectively non-zero) error code.
5818Observe that return-code-dependent out parameter annotations are only
5819available for retained out parameters, as non-retained object do not have to be
5820released by the callee.
5821These attributes are only used by the Clang Static Analyzer.
5822
5823The family of attributes ``X_returns_X_retained`` can be added to functions,
5824C++ methods, and Objective-C methods and properties.
5825Attributes ``X_consumed`` can be added to parameters of methods, functions,
5826and Objective-C methods.)reST";
5827
5828static const char AttrDoc_OSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5829(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5830convention (e.g. functions starting with "get" are assumed to return at
5831``+0``).
5832
5833It can be overridden using a family of the following attributes. In
5834Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5835a function communicates that the object is returned at ``+1``, and the caller
5836is responsible for freeing it.
5837Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5838specifies that the object is returned at ``+0`` and the ownership remains with
5839the callee.
5840The annotation ``__attribute__((ns_consumes_self))`` specifies that
5841the Objective-C method call consumes the reference to ``self``, e.g. by
5842attaching it to a supplied parameter.
5843Additionally, parameters can have an annotation
5844``__attribute__((ns_consumed))``, which specifies that passing an owned object
5845as that parameter effectively transfers the ownership, and the caller is no
5846longer responsible for it.
5847These attributes affect code generation when interacting with ARC code, and
5848they are used by the Clang Static Analyzer.
5849
5850In C programs using CoreFoundation, a similar set of attributes:
5851``__attribute__((cf_returns_not_retained))``,
5852``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5853have the same respective semantics when applied to CoreFoundation objects.
5854These attributes affect code generation when interacting with ARC code, and
5855they are used by the Clang Static Analyzer.
5856
5857Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5858the same attribute family is present:
5859``__attribute__((os_returns_not_retained))``,
5860``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5861with the same respective semantics.
5862Similar to ``__attribute__((ns_consumes_self))``,
5863``__attribute__((os_consumes_this))`` specifies that the method call consumes
5864the reference to "this" (e.g., when attaching it to a different object supplied
5865as a parameter).
5866Out parameters (parameters the function is meant to write into,
5867either via pointers-to-pointers or references-to-pointers)
5868may be annotated with ``__attribute__((os_returns_retained))``
5869or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5870written into the out parameter should (or respectively should not) be released
5871after use.
5872Since often out parameters may or may not be written depending on the exit
5873code of the function,
5874annotations ``__attribute__((os_returns_retained_on_zero))``
5875and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5876an out parameter at ``+1`` is written if and only if the function returns a zero
5877(respectively non-zero) error code.
5878Observe that return-code-dependent out parameter annotations are only
5879available for retained out parameters, as non-retained object do not have to be
5880released by the callee.
5881These attributes are only used by the Clang Static Analyzer.
5882
5883The family of attributes ``X_returns_X_retained`` can be added to functions,
5884C++ methods, and Objective-C methods and properties.
5885Attributes ``X_consumed`` can be added to parameters of methods, functions,
5886and Objective-C methods.)reST";
5887
5888static const char AttrDoc_OSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5889(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5890convention (e.g. functions starting with "get" are assumed to return at
5891``+0``).
5892
5893It can be overridden using a family of the following attributes. In
5894Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5895a function communicates that the object is returned at ``+1``, and the caller
5896is responsible for freeing it.
5897Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5898specifies that the object is returned at ``+0`` and the ownership remains with
5899the callee.
5900The annotation ``__attribute__((ns_consumes_self))`` specifies that
5901the Objective-C method call consumes the reference to ``self``, e.g. by
5902attaching it to a supplied parameter.
5903Additionally, parameters can have an annotation
5904``__attribute__((ns_consumed))``, which specifies that passing an owned object
5905as that parameter effectively transfers the ownership, and the caller is no
5906longer responsible for it.
5907These attributes affect code generation when interacting with ARC code, and
5908they are used by the Clang Static Analyzer.
5909
5910In C programs using CoreFoundation, a similar set of attributes:
5911``__attribute__((cf_returns_not_retained))``,
5912``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5913have the same respective semantics when applied to CoreFoundation objects.
5914These attributes affect code generation when interacting with ARC code, and
5915they are used by the Clang Static Analyzer.
5916
5917Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5918the same attribute family is present:
5919``__attribute__((os_returns_not_retained))``,
5920``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5921with the same respective semantics.
5922Similar to ``__attribute__((ns_consumes_self))``,
5923``__attribute__((os_consumes_this))`` specifies that the method call consumes
5924the reference to "this" (e.g., when attaching it to a different object supplied
5925as a parameter).
5926Out parameters (parameters the function is meant to write into,
5927either via pointers-to-pointers or references-to-pointers)
5928may be annotated with ``__attribute__((os_returns_retained))``
5929or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5930written into the out parameter should (or respectively should not) be released
5931after use.
5932Since often out parameters may or may not be written depending on the exit
5933code of the function,
5934annotations ``__attribute__((os_returns_retained_on_zero))``
5935and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5936an out parameter at ``+1`` is written if and only if the function returns a zero
5937(respectively non-zero) error code.
5938Observe that return-code-dependent out parameter annotations are only
5939available for retained out parameters, as non-retained object do not have to be
5940released by the callee.
5941These attributes are only used by the Clang Static Analyzer.
5942
5943The family of attributes ``X_returns_X_retained`` can be added to functions,
5944C++ methods, and Objective-C methods and properties.
5945Attributes ``X_consumed`` can be added to parameters of methods, functions,
5946and Objective-C methods.)reST";
5947
5948static const char AttrDoc_OSReturnsRetainedOnNonZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5949(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5950convention (e.g. functions starting with "get" are assumed to return at
5951``+0``).
5952
5953It can be overridden using a family of the following attributes. In
5954Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5955a function communicates that the object is returned at ``+1``, and the caller
5956is responsible for freeing it.
5957Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5958specifies that the object is returned at ``+0`` and the ownership remains with
5959the callee.
5960The annotation ``__attribute__((ns_consumes_self))`` specifies that
5961the Objective-C method call consumes the reference to ``self``, e.g. by
5962attaching it to a supplied parameter.
5963Additionally, parameters can have an annotation
5964``__attribute__((ns_consumed))``, which specifies that passing an owned object
5965as that parameter effectively transfers the ownership, and the caller is no
5966longer responsible for it.
5967These attributes affect code generation when interacting with ARC code, and
5968they are used by the Clang Static Analyzer.
5969
5970In C programs using CoreFoundation, a similar set of attributes:
5971``__attribute__((cf_returns_not_retained))``,
5972``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5973have the same respective semantics when applied to CoreFoundation objects.
5974These attributes affect code generation when interacting with ARC code, and
5975they are used by the Clang Static Analyzer.
5976
5977Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5978the same attribute family is present:
5979``__attribute__((os_returns_not_retained))``,
5980``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5981with the same respective semantics.
5982Similar to ``__attribute__((ns_consumes_self))``,
5983``__attribute__((os_consumes_this))`` specifies that the method call consumes
5984the reference to "this" (e.g., when attaching it to a different object supplied
5985as a parameter).
5986Out parameters (parameters the function is meant to write into,
5987either via pointers-to-pointers or references-to-pointers)
5988may be annotated with ``__attribute__((os_returns_retained))``
5989or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5990written into the out parameter should (or respectively should not) be released
5991after use.
5992Since often out parameters may or may not be written depending on the exit
5993code of the function,
5994annotations ``__attribute__((os_returns_retained_on_zero))``
5995and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5996an out parameter at ``+1`` is written if and only if the function returns a zero
5997(respectively non-zero) error code.
5998Observe that return-code-dependent out parameter annotations are only
5999available for retained out parameters, as non-retained object do not have to be
6000released by the callee.
6001These attributes are only used by the Clang Static Analyzer.
6002
6003The family of attributes ``X_returns_X_retained`` can be added to functions,
6004C++ methods, and Objective-C methods and properties.
6005Attributes ``X_consumed`` can be added to parameters of methods, functions,
6006and Objective-C methods.)reST";
6007
6008static const char AttrDoc_OSReturnsRetainedOnZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6009(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6010convention (e.g. functions starting with "get" are assumed to return at
6011``+0``).
6012
6013It can be overridden using a family of the following attributes. In
6014Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
6015a function communicates that the object is returned at ``+1``, and the caller
6016is responsible for freeing it.
6017Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
6018specifies that the object is returned at ``+0`` and the ownership remains with
6019the callee.
6020The annotation ``__attribute__((ns_consumes_self))`` specifies that
6021the Objective-C method call consumes the reference to ``self``, e.g. by
6022attaching it to a supplied parameter.
6023Additionally, parameters can have an annotation
6024``__attribute__((ns_consumed))``, which specifies that passing an owned object
6025as that parameter effectively transfers the ownership, and the caller is no
6026longer responsible for it.
6027These attributes affect code generation when interacting with ARC code, and
6028they are used by the Clang Static Analyzer.
6029
6030In C programs using CoreFoundation, a similar set of attributes:
6031``__attribute__((cf_returns_not_retained))``,
6032``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
6033have the same respective semantics when applied to CoreFoundation objects.
6034These attributes affect code generation when interacting with ARC code, and
6035they are used by the Clang Static Analyzer.
6036
6037Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6038the same attribute family is present:
6039``__attribute__((os_returns_not_retained))``,
6040``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
6041with the same respective semantics.
6042Similar to ``__attribute__((ns_consumes_self))``,
6043``__attribute__((os_consumes_this))`` specifies that the method call consumes
6044the reference to "this" (e.g., when attaching it to a different object supplied
6045as a parameter).
6046Out parameters (parameters the function is meant to write into,
6047either via pointers-to-pointers or references-to-pointers)
6048may be annotated with ``__attribute__((os_returns_retained))``
6049or ``__attribute__((os_returns_not_retained))`` which specifies that the object
6050written into the out parameter should (or respectively should not) be released
6051after use.
6052Since often out parameters may or may not be written depending on the exit
6053code of the function,
6054annotations ``__attribute__((os_returns_retained_on_zero))``
6055and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
6056an out parameter at ``+1`` is written if and only if the function returns a zero
6057(respectively non-zero) error code.
6058Observe that return-code-dependent out parameter annotations are only
6059available for retained out parameters, as non-retained object do not have to be
6060released by the callee.
6061These attributes are only used by the Clang Static Analyzer.
6062
6063The family of attributes ``X_returns_X_retained`` can be added to functions,
6064C++ methods, and Objective-C methods and properties.
6065Attributes ``X_consumed`` can be added to parameters of methods, functions,
6066and Objective-C methods.)reST";
6067
6068static const char AttrDoc_ObjCBoxable[] = R"reST(Structs and unions marked with the ``objc_boxable`` attribute can be used
6069with the Objective-C boxed expression syntax, ``@(...)``.
6070
6071**Usage**: ``__attribute__((objc_boxable))``. This attribute
6072can only be placed on a declaration of a trivially-copyable struct or union:
6073
6074.. code-block:: objc
6075
6076 struct __attribute__((objc_boxable)) some_struct {
6077 int i;
6078 };
6079 union __attribute__((objc_boxable)) some_union {
6080 int i;
6081 float f;
6082 };
6083 typedef struct __attribute__((objc_boxable)) _some_struct some_struct;
6084
6085 // ...
6086
6087 some_struct ss;
6088 NSValue *boxed = @(ss);)reST";
6089
6090static const char AttrDoc_ObjCBridge[] = R"reST(No documentation.)reST";
6091
6092static const char AttrDoc_ObjCBridgeMutable[] = R"reST(No documentation.)reST";
6093
6094static const char AttrDoc_ObjCBridgeRelated[] = R"reST(No documentation.)reST";
6095
6096static const char AttrDoc_ObjCClassStub[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
6097instantiated at runtime.
6098
6099Unlike ``__attribute__((objc_runtime_visible))``, a class having this attribute
6100still has a "class stub" that is visible to the linker. This allows categories
6101to be defined. Static message sends with the class as a receiver use a special
6102access pattern to ensure the class is lazily instantiated from the class stub.
6103
6104Classes annotated with this attribute cannot be subclassed and cannot have
6105implementations defined for them. This attribute is intended for use in
6106Swift-generated headers for classes defined in Swift.
6107
6108Adding or removing this attribute to a class is an ABI-breaking change.)reST";
6109
6110static const char AttrDoc_ObjCDesignatedInitializer[] = R"reST(No documentation.)reST";
6111
6112static const char AttrDoc_ObjCDirect[] = R"reST(The ``objc_direct`` attribute can be used to mark an Objective-C method as
6113being *direct*. A direct method is treated statically like an ordinary method,
6114but dynamically it behaves more like a C function. This lowers some of the costs
6115associated with the method but also sacrifices some of the ordinary capabilities
6116of Objective-C methods.
6117
6118A message send of a direct method calls the implementation directly, as if it
6119were a C function, rather than using ordinary Objective-C method dispatch. This
6120is substantially faster and potentially allows the implementation to be inlined,
6121but it also means the method cannot be overridden in subclasses or replaced
6122dynamically, as ordinary Objective-C methods can.
6123
6124Furthermore, a direct method is not listed in the class's method lists. This
6125substantially reduces the code-size overhead of the method but also means it
6126cannot be called dynamically using ordinary Objective-C method dispatch at all;
6127in particular, this means that it cannot override a superclass method or satisfy
6128a protocol requirement.
6129
6130Because a direct method cannot be overridden, it is an error to perform
6131a ``super`` message send of one.
6132
6133Although a message send of a direct method causes the method to be called
6134directly as if it were a C function, it still obeys Objective-C semantics in other
6135ways:
6136
6137- If the receiver is ``nil``, the message send does nothing and returns the zero value
6138 for the return type.
6139
6140- A message send of a direct class method will cause the class to be initialized,
6141 including calling the ``+initialize`` method if present.
6142
6143- The implicit ``_cmd`` parameter containing the method's selector is still defined.
6144 In order to minimize code-size costs, the implementation will not emit a reference
6145 to the selector if the parameter is unused within the method.
6146
6147Symbols for direct method implementations are implicitly given hidden
6148visibility, meaning that they can only be called within the same linkage unit.
6149
6150It is an error to do any of the following:
6151
6152- declare a direct method in a protocol,
6153- declare an override of a direct method with a method in a subclass,
6154- declare an override of a non-direct method with a direct method in a subclass,
6155- declare a method with different directness in different class interfaces, or
6156- implement a non-direct method (as declared in any class interface) with a direct method.
6157
6158If any of these rules would be violated if every method defined in an
6159``@implementation`` within a single linkage unit were declared in an
6160appropriate class interface, the program is ill-formed with no diagnostic
6161required. If a violation of this rule is not diagnosed, behavior remains
6162well-defined; this paragraph is simply reserving the right to diagnose such
6163conflicts in the future, not to treat them as undefined behavior.
6164
6165Additionally, Clang will warn about any ``@selector`` expression that
6166names a selector that is only known to be used for direct methods.
6167
6168For the purpose of these rules, a "class interface" includes a class's primary
6169``@interface`` block, its class extensions, its categories, its declared protocols,
6170and all the class interfaces of its superclasses.
6171
6172An Objective-C property can be declared with the ``direct`` property
6173attribute. If a direct property declaration causes an implicit declaration of
6174a getter or setter method (that is, if the given method is not explicitly
6175declared elsewhere), the method is declared to be direct.
6176
6177Some programmers may wish to make many methods direct at once. In order
6178to simplify this, the ``objc_direct_members`` attribute is provided; see its
6179documentation for more information.)reST";
6180
6181static const char AttrDoc_ObjCDirectMembers[] = R"reST(The ``objc_direct_members`` attribute can be placed on an Objective-C
6182``@interface`` or ``@implementation`` to mark that methods declared
6183therein should be considered direct by default. See the documentation
6184for ``objc_direct`` for more information about direct methods.
6185
6186When ``objc_direct_members`` is placed on an ``@interface`` block, every
6187method in the block is considered to be declared as direct. This includes any
6188implicit method declarations introduced by property declarations. If the method
6189redeclares a non-direct method, the declaration is ill-formed, exactly as if the
6190method was annotated with the ``objc_direct`` attribute.
6191
6192When ``objc_direct_members`` is placed on an ``@implementation`` block,
6193methods defined in the block are considered to be declared as direct unless
6194they have been previously declared as non-direct in any interface of the class.
6195This includes the implicit method definitions introduced by synthesized
6196properties, including auto-synthesized properties.)reST";
6197
6198static const char AttrDoc_ObjCException[] = R"reST(No documentation.)reST";
6199
6200static const char AttrDoc_ObjCExplicitProtocolImpl[] = R"reST(No documentation.)reST";
6201
6202static const char AttrDoc_ObjCExternallyRetained[] = R"reST(The ``objc_externally_retained`` attribute can be applied to strong local
6203variables, functions, methods, or blocks to opt into
6204`externally-retained semantics
6205<https://clang.llvm.org/docs/AutomaticReferenceCounting.html#externally-retained-variables>`_.
6206
6207When applied to the definition of a function, method, or block, every parameter
6208of the function with implicit strong retainable object pointer type is
6209considered externally-retained, and becomes ``const``. By explicitly annotating
6210a parameter with ``__strong``, you can opt back into the default
6211non-externally-retained behavior for that parameter. For instance,
6212``first_param`` is externally-retained below, but not ``second_param``:
6213
6214.. code-block:: objc
6215
6216 __attribute__((objc_externally_retained))
6217 void f(NSArray *first_param, __strong NSArray *second_param) {
6218 // ...
6219 }
6220
6221Likewise, when applied to a strong local variable, that variable becomes
6222``const`` and is considered externally-retained.
6223
6224When compiled without ``-fobjc-arc``, this attribute is ignored.)reST";
6225
6226static const char AttrDoc_ObjCGC[] = R"reST(No documentation.)reST";
6227
6228static const char AttrDoc_ObjCIndependentClass[] = R"reST(No documentation.)reST";
6229
6230static const char AttrDoc_ObjCInertUnsafeUnretained[] = R"reST()reST";
6231
6232static const char AttrDoc_ObjCKindOf[] = R"reST(No documentation.)reST";
6233
6234static const char AttrDoc_ObjCMethodFamily[] = R"reST(Many methods in Objective-C have conventional meanings determined by their
6235selectors. It is sometimes useful to be able to mark a method as having a
6236particular conventional meaning despite not having the right selector, or as
6237not having the conventional meaning that its selector would suggest. For these
6238use cases, we provide an attribute to specifically describe the "method family"
6239that a method belongs to.
6240
6241**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
6242``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This
6243attribute can only be placed at the end of a method declaration:
6244
6245.. code-block:: objc
6246
6247 - (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
6248
6249Users who do not wish to change the conventional meaning of a method, and who
6250merely want to document its non-standard retain and release semantics, should
6251use the retaining behavior attributes (``ns_returns_retained``,
6252``ns_returns_not_retained``, etc).
6253
6254Query for this feature with ``__has_attribute(objc_method_family)``.)reST";
6255
6256static const char AttrDoc_ObjCNSObject[] = R"reST(No documentation.)reST";
6257
6258static const char AttrDoc_ObjCNonLazyClass[] = R"reST(This attribute can be added to an Objective-C ``@interface`` or
6259``@implementation`` declaration to add the class to the list of non-lazily
6260initialized classes. A non-lazy class will be initialized eagerly when the
6261Objective-C runtime is loaded. This is required for certain system classes which
6262have instances allocated in non-standard ways, such as the classes for blocks
6263and constant strings. Adding this attribute is essentially equivalent to
6264providing a trivial ``+load`` method but avoids the (fairly small) load-time
6265overheads associated with defining and calling such a method.)reST";
6266
6267static const char AttrDoc_ObjCNonRuntimeProtocol[] = R"reST(The ``objc_non_runtime_protocol`` attribute can be used to mark that an
6268Objective-C protocol is only used during static type-checking and doesn't need
6269to be represented dynamically. This avoids several small code-size and run-time
6270overheads associated with handling the protocol's metadata. A non-runtime
6271protocol cannot be used as the operand of a ``@protocol`` expression, and
6272dynamic attempts to find it with ``objc_getProtocol`` will fail.
6273
6274If a non-runtime protocol inherits from any ordinary protocols, classes and
6275derived protocols that declare conformance to the non-runtime protocol will
6276dynamically list their conformance to those bare protocols.)reST";
6277
6278static const char AttrDoc_ObjCOwnership[] = R"reST(No documentation.)reST";
6279
6280static const char AttrDoc_ObjCPreciseLifetime[] = R"reST(No documentation.)reST";
6281
6282static const char AttrDoc_ObjCRequiresPropertyDefs[] = R"reST(No documentation.)reST";
6283
6284static const char AttrDoc_ObjCRequiresSuper[] = R"reST(Some Objective-C classes allow a subclass to override a particular method in a
6285parent class but expect that the overriding method also calls the overridden
6286method in the parent class. For these cases, we provide an attribute to
6287designate that a method requires a "call to ``super``" in the overriding
6288method in the subclass.
6289
6290**Usage**: ``__attribute__((objc_requires_super))``. This attribute can only
6291be placed at the end of a method declaration:
6292
6293.. code-block:: objc
6294
6295 - (void)foo __attribute__((objc_requires_super));
6296
6297This attribute can only be applied the method declarations within a class, and
6298not a protocol. Currently this attribute does not enforce any placement of
6299where the call occurs in the overriding method (such as in the case of
6300``-dealloc`` where the call must appear at the end). It checks only that it
6301exists.
6302
6303Note that on both OS X and iOS that the Foundation framework provides a
6304convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this
6305attribute:
6306
6307.. code-block:: objc
6308
6309 - (void)foo NS_REQUIRES_SUPER;
6310
6311This macro is conditionally defined depending on the compiler's support for
6312this attribute. If the compiler does not support the attribute the macro
6313expands to nothing.
6314
6315Operationally, when a method has this annotation the compiler will warn if the
6316implementation of an override in a subclass does not call super. For example:
6317
6318.. code-block:: objc
6319
6320 warning: method possibly missing a [super AnnotMeth] call
6321 - (void) AnnotMeth{};
6322 ^)reST";
6323
6324static const char AttrDoc_ObjCReturnsInnerPointer[] = R"reST(No documentation.)reST";
6325
6326static const char AttrDoc_ObjCRootClass[] = R"reST(No documentation.)reST";
6327
6328static const char AttrDoc_ObjCRuntimeName[] = R"reST(By default, the Objective-C interface or protocol identifier is used
6329in the metadata name for that object. The ``objc_runtime_name``
6330attribute allows annotated interfaces or protocols to use the
6331specified string argument in the object's metadata name instead of the
6332default name.
6333
6334**Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``. This attribute
6335can only be placed before an @protocol or @interface declaration:
6336
6337.. code-block:: objc
6338
6339 __attribute__((objc_runtime_name("MyLocalName")))
6340 @interface Message
6341 @end)reST";
6342
6343static const char AttrDoc_ObjCRuntimeVisible[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
6344visible to the Objective-C runtime but not to the linker. Classes annotated
6345with this attribute cannot be subclassed and cannot have categories defined for
6346them.)reST";
6347
6348static const char AttrDoc_ObjCSubclassingRestricted[] = R"reST(This attribute can be added to an Objective-C ``@interface`` declaration to
6349ensure that this class cannot be subclassed.)reST";
6350
6351static const char AttrDoc_OpenACCRoutineAnnot[] = R"reST()reST";
6352
6353static const char AttrDoc_OpenACCRoutineDecl[] = R"reST()reST";
6354
6355static const char AttrDoc_OpenCLAccess[] = R"reST(The access qualifiers must be used with image object arguments or pipe arguments
6356to declare if they are being read or written by a kernel or function.
6357
6358The read_only/__read_only, write_only/__write_only and read_write/__read_write
6359names are reserved for use as access qualifiers and shall not be used otherwise.
6360
6361.. code-block:: c
6362
6363 kernel void
6364 foo (read_only image2d_t imageA,
6365 write_only image2d_t imageB) {
6366 ...
6367 }
6368
6369In the above example imageA is a read-only 2D image object, and imageB is a
6370write-only 2D image object.
6371
6372The read_write (or __read_write) qualifier can not be used with pipe.
6373
6374More details can be found in the OpenCL C language Spec v2.0, Section 6.6.)reST";
6375
6376static const char AttrDoc_OpenCLConstantAddressSpace[] = R"reST(The constant address space attribute signals that an object is located in
6377a constant (non-modifiable) memory region. It is available to all work items.
6378Any type can be annotated with the constant address space attribute. Objects
6379with the constant address space qualifier can be declared in any scope and must
6380have an initializer.)reST";
6381
6382static const char AttrDoc_OpenCLGenericAddressSpace[] = R"reST(The generic address space attribute is only available with OpenCL v2.0 and later.
6383It can be used with pointer types. Variables in global and local scope and
6384function parameters in non-kernel functions can have the generic address space
6385type attribute. It is intended to be a placeholder for any other address space
6386except for '__constant' in OpenCL code which can be used with multiple address
6387spaces.)reST";
6388
6389static const char AttrDoc_OpenCLGlobalAddressSpace[] = R"reST(The global address space attribute specifies that an object is allocated in
6390global memory, which is accessible by all work items. The content stored in this
6391memory area persists between kernel executions. Pointer types to the global
6392address space are allowed as function parameters or local variables. Starting
6393with OpenCL v2.0, the global address space can be used with global (program
6394scope) variables and static local variable as well.)reST";
6395
6396static const char AttrDoc_OpenCLGlobalDeviceAddressSpace[] = R"reST(The ``global_device`` and ``global_host`` address space attributes specify that
6397an object is allocated in global memory on the device/host. It helps to
6398distinguish USM (Unified Shared Memory) pointers that access global device
6399memory from those that access global host memory. These new address spaces are
6400a subset of the ``__global/opencl_global`` address space, the full address space
6401set model for OpenCL 2.0 with the extension looks as follows:
6402
6403 | generic->global->host
6404 | ->device
6405 | ->private
6406 | ->local
6407 | constant
6408
6409As ``global_device`` and ``global_host`` are a subset of
6410``__global/opencl_global`` address spaces it is allowed to convert
6411``global_device`` and ``global_host`` address spaces to
6412``__global/opencl_global`` address spaces (following ISO/IEC TR 18037 5.1.3
6413"Address space nesting and rules for pointers").)reST";
6414
6415static const char AttrDoc_OpenCLGlobalHostAddressSpace[] = R"reST(The ``global_device`` and ``global_host`` address space attributes specify that
6416an object is allocated in global memory on the device/host. It helps to
6417distinguish USM (Unified Shared Memory) pointers that access global device
6418memory from those that access global host memory. These new address spaces are
6419a subset of the ``__global/opencl_global`` address space, the full address space
6420set model for OpenCL 2.0 with the extension looks as follows:
6421
6422 | generic->global->host
6423 | ->device
6424 | ->private
6425 | ->local
6426 | constant
6427
6428As ``global_device`` and ``global_host`` are a subset of
6429``__global/opencl_global`` address spaces it is allowed to convert
6430``global_device`` and ``global_host`` address spaces to
6431``__global/opencl_global`` address spaces (following ISO/IEC TR 18037 5.1.3
6432"Address space nesting and rules for pointers").)reST";
6433
6434static const char AttrDoc_OpenCLIntelReqdSubGroupSize[] = R"reST(The optional attribute intel_reqd_sub_group_size can be used to indicate that
6435the kernel must be compiled and executed with the specified subgroup size. When
6436this attribute is present, get_max_sub_group_size() is guaranteed to return the
6437specified integer value. This is important for the correctness of many subgroup
6438algorithms, and in some cases may be used by the compiler to generate more optimal
6439code. See `cl_intel_required_subgroup_size
6440<https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.txt>`
6441for details.)reST";
6442
6443static const char AttrDoc_OpenCLLocalAddressSpace[] = R"reST(The local address space specifies that an object is allocated in the local (work
6444group) memory area, which is accessible to all work items in the same work
6445group. The content stored in this memory region is not accessible after
6446the kernel execution ends. In a kernel function scope, any variable can be in
6447the local address space. In other scopes, only pointer types to the local address
6448space are allowed. Local address space variables cannot have an initializer.)reST";
6449
6450static const char AttrDoc_OpenCLPrivateAddressSpace[] = R"reST(The private address space specifies that an object is allocated in the private
6451(work item) memory. Other work items cannot access the same memory area and its
6452content is destroyed after work item execution ends. Local variables can be
6453declared in the private address space. Function arguments are always in the
6454private address space. Kernel function arguments of a pointer or an array type
6455cannot point to the private address space.)reST";
6456
6457static const char AttrDoc_OpenCLUnrollHint[] = R"reST(The opencl_unroll_hint attribute qualifier can be used to specify that a loop
6458(for, while and do loops) can be unrolled. This attribute qualifier can be
6459used to specify full unrolling or partial unrolling by a specified amount.
6460This is a compiler hint and the compiler may ignore this directive. See
6461`OpenCL v2.0 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf>`_
6462s6.11.5 for details.)reST";
6463
6464static const char AttrDoc_OptimizeNone[] = R"reST(The ``optnone`` attribute suppresses essentially all optimizations
6465on a function or method, regardless of the optimization level applied to
6466the compilation unit as a whole. This is particularly useful when you
6467need to debug a particular function, but it is infeasible to build the
6468entire application without optimization. Avoiding optimization on the
6469specified function can improve the quality of the debugging information
6470for that function.
6471
6472This attribute is incompatible with the ``always_inline`` and ``minsize``
6473attributes.
6474
6475Note that this attribute does not apply recursively to nested functions such as
6476lambdas or blocks when using declaration-specific attribute syntaxes such as double
6477square brackets (``[[]]``) or ``__attribute__``. The ``#pragma`` syntax can be
6478used to apply the attribute to all functions, including nested functions, in a
6479range of source code.)reST";
6480
6481static const char AttrDoc_OverflowBehavior[] = R"reST(No documentation.)reST";
6482
6483static const char AttrDoc_Overloadable[] = R"reST(Clang provides support for C++ function overloading in C. Function overloading
6484in C is introduced using the ``overloadable`` attribute. For example, one
6485might provide several overloaded versions of a ``tgsin`` function that invokes
6486the appropriate standard function computing the sine of a value with ``float``,
6487``double``, or ``long double`` precision:
6488
6489.. code-block:: c
6490
6491 #include <math.h>
6492 float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
6493 double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
6494 long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
6495
6496Given these declarations, one can call ``tgsin`` with a ``float`` value to
6497receive a ``float`` result, with a ``double`` to receive a ``double`` result,
6498etc. Function overloading in C follows the rules of C++ function overloading
6499to pick the best overload given the call arguments, with a few C-specific
6500semantics:
6501
6502* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
6503 floating-point promotion (per C99) rather than as a floating-point conversion
6504 (as in C++).
6505
6506* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
6507 considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
6508 compatible types.
6509
6510* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
6511 and ``U`` are compatible types. This conversion is given "conversion" rank.
6512
6513* If no viable candidates are otherwise available, we allow a conversion from a
6514 pointer of type ``T*`` to a pointer of type ``U*``, where ``T`` and ``U`` are
6515 incompatible. This conversion is ranked below all other types of conversions.
6516 Please note: ``U`` lacking qualifiers that are present on ``T`` is sufficient
6517 for ``T`` and ``U`` to be incompatible.
6518
6519The declaration of ``overloadable`` functions is restricted to function
6520declarations and definitions. If a function is marked with the ``overloadable``
6521attribute, then all declarations and definitions of functions with that name,
6522except for at most one (see the note below about unmarked overloads), must have
6523the ``overloadable`` attribute. In addition, redeclarations of a function with
6524the ``overloadable`` attribute must have the ``overloadable`` attribute, and
6525redeclarations of a function without the ``overloadable`` attribute must *not*
6526have the ``overloadable`` attribute. e.g.,
6527
6528.. code-block:: c
6529
6530 int f(int) __attribute__((overloadable));
6531 float f(float); // error: declaration of "f" must have the "overloadable" attribute
6532 int f(int); // error: redeclaration of "f" must have the "overloadable" attribute
6533
6534 int g(int) __attribute__((overloadable));
6535 int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
6536
6537 int h(int);
6538 int h(int) __attribute__((overloadable)); // error: declaration of "h" must not
6539 // have the "overloadable" attribute
6540
6541Functions marked ``overloadable`` must have prototypes. Therefore, the
6542following code is ill-formed:
6543
6544.. code-block:: c
6545
6546 int h() __attribute__((overloadable)); // error: h does not have a prototype
6547
6548However, ``overloadable`` functions are allowed to use a ellipsis even if there
6549are no named parameters (as is permitted in C++). This feature is particularly
6550useful when combined with the ``unavailable`` attribute:
6551
6552.. code-block:: c++
6553
6554 void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
6555
6556Functions declared with the ``overloadable`` attribute have their names mangled
6557according to the same rules as C++ function names. For example, the three
6558``tgsin`` functions in our motivating example get the mangled names
6559``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two
6560caveats to this use of name mangling:
6561
6562* Future versions of Clang may change the name mangling of functions overloaded
6563 in C, so you should not depend on an specific mangling. To be completely
6564 safe, we strongly urge the use of ``static inline`` with ``overloadable``
6565 functions.
6566
6567* The ``overloadable`` attribute has almost no meaning when used in C++,
6568 because names will already be mangled and functions are already overloadable.
6569 However, when an ``overloadable`` function occurs within an ``extern "C"``
6570 linkage specification, its name *will* be mangled in the same way as it
6571 would in C.
6572
6573For the purpose of backwards compatibility, at most one function with the same
6574name as other ``overloadable`` functions may omit the ``overloadable``
6575attribute. In this case, the function without the ``overloadable`` attribute
6576will not have its name mangled.
6577
6578For example:
6579
6580.. code-block:: c
6581
6582 // Notes with mangled names assume Itanium mangling.
6583 int f(int);
6584 int f(double) __attribute__((overloadable));
6585 void foo() {
6586 f(5); // Emits a call to f (not _Z1fi, as it would with an overload that
6587 // was marked with overloadable).
6588 f(1.0); // Emits a call to _Z1fd.
6589 }
6590
6591Support for unmarked overloads is not present in some versions of clang. You may
6592query for it using ``__has_extension(overloadable_unmarked)``.
6593
6594Query for this attribute with ``__has_attribute(overloadable)``.)reST";
6595
6596static const char AttrDoc_Override[] = R"reST()reST";
6597
6598static const char AttrDoc_Owner[] = R"reST(.. Note:: This attribute is experimental and its effect on analysis is subject to change in
6599 a future version of clang.
6600
6601The attribute ``[[gsl::Owner(T)]]`` applies to structs and classes that own an
6602object of type ``T``:
6603
6604.. code::
6605
6606 class [[gsl::Owner(int)]] IntOwner {
6607 private:
6608 int value;
6609 public:
6610 int *getInt() { return &value; }
6611 };
6612
6613The argument ``T`` is optional and is ignored.
6614This attribute may be used by analysis tools and has no effect on code
6615generation. A ``void`` argument means that the class can own any type.
6616
6617See Pointer_ for an example.)reST";
6618
6619static const char AttrDoc_Ownership[] = R"reST(.. note::
6620
6621 In order for the Clang Static Analyzer to acknowledge these attributes, the
6622 ``Optimistic`` config needs to be set to true for the checker
6623 ``unix.DynamicMemoryModeling``:
6624
6625 ``-Xclang -analyzer-config -Xclang unix.DynamicMemoryModeling:Optimistic=true``
6626
6627These attributes are used by the Clang Static Analyzer's dynamic memory modeling
6628facilities to mark custom allocating/deallocating functions.
6629
6630All 3 attributes' first parameter of type string is the type of the allocation:
6631``malloc``, ``new``, etc. to allow for catching :ref:`mismatched deallocation
6632<unix-MismatchedDeallocator>` bugs. The allocation type can be any string, e.g.
6633a function annotated with
6634returning a piece of memory of type ``lasagna`` but freed with a function
6635annotated to release ``cheese`` typed memory will result in mismatched
6636deallocation warning.
6637
6638The (currently) only allocation type having special meaning is ``malloc`` --
6639the Clang Static Analyzer makes sure that allocating functions annotated with
6640``malloc`` are treated like they used the standard ``malloc()``, and can be
6641safely deallocated with the standard ``free()``.
6642
6643* Use ``ownership_returns`` to mark a function as an allocating function. Takes
6644 1 parameter to denote the allocation type.
6645* Use ``ownership_takes`` to mark a function as a deallocating function. Takes 2
6646 parameters: the allocation type, and the index of the parameter that is being
6647 deallocated (counting from 1).
6648* Use ``ownership_holds`` to mark that a function takes over the ownership of a
6649 piece of memory and will free it at some unspecified point in the future. Like
6650 ``ownership_takes``, this takes 2 parameters: the allocation type, and the
6651 index of the parameter whose ownership will be taken over (counting from 1).
6652
6653The annotations ``ownership_takes`` and ``ownership_holds`` both prevent memory
6654leak reports (concerning the specified argument); the difference between them
6655is that using taken memory is a use-after-free error, while using held memory
6656is assumed to be legitimate.
6657
6658Example:
6659
6660.. code-block:: c
6661
6662 // Denotes that my_malloc will return with a dynamically allocated piece of
6663 // memory using malloc().
6664 void __attribute((ownership_returns(malloc))) *my_malloc(size_t);
6665
6666 // Denotes that my_free will deallocate its parameter using free().
6667 void __attribute((ownership_takes(malloc, 1))) my_free(void *);
6668
6669 // Denotes that my_hold will take over the ownership of its parameter that was
6670 // allocated via malloc().
6671 void __attribute((ownership_holds(malloc, 1))) my_hold(void *);
6672
6673Further reading about dynamic memory modeling in the Clang Static Analyzer is
6674found in these checker docs:
6675:ref:`unix.Malloc <unix-Malloc>`, :ref:`unix.MallocSizeof <unix-MallocSizeof>`,
6676:ref:`unix.MismatchedDeallocator <unix-MismatchedDeallocator>`,
6677:ref:`cplusplus.NewDelete <cplusplus-NewDelete>`,
6678:ref:`cplusplus.NewDeleteLeaks <cplusplus-NewDeleteLeaks>`,
6679:ref:`optin.taint.TaintedAlloc <optin-taint-TaintedAlloc>`.
6680Mind that many more checkers are affected by dynamic memory modeling changes to
6681some extent.
6682
6683Further reading for other annotations:
6684`Source Annotations in the Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/user-docs/Annotations.html>`_.)reST";
6685
6686static const char AttrDoc_Packed[] = R"reST(No documentation.)reST";
6687
6688static const char AttrDoc_ParamTypestate[] = R"reST(This attribute specifies expectations about function parameters. Calls to an
6689function with annotated parameters will issue a warning if the corresponding
6690argument isn't in the expected state. The attribute is also used to set the
6691initial state of the parameter when analyzing the function's body.)reST";
6692
6693static const char AttrDoc_Pascal[] = R"reST(No documentation.)reST";
6694
6695static const char AttrDoc_PassObjectSize[] = R"reST(.. Note:: The mangling of functions with parameters that are annotated with
6696 ``pass_object_size`` is subject to change. You can get around this by
6697 using ``__asm__("foo")`` to explicitly name your functions, thus preserving
6698 your ABI; also, non-overloadable C functions with ``pass_object_size`` are
6699 not mangled.
6700
6701The ``pass_object_size(Type)`` attribute can be placed on function parameters to
6702instruct clang to call ``__builtin_object_size(param, Type)`` at each callsite
6703of said function, and implicitly pass the result of this call in as an invisible
6704argument of type ``size_t`` directly after the parameter annotated with
6705``pass_object_size``. Clang will also replace any calls to
6706``__builtin_object_size(param, Type)`` in the function by said implicit
6707parameter.
6708
6709Example usage:
6710
6711.. code-block:: c
6712
6713 int bzero1(char *const p __attribute__((pass_object_size(0))))
6714 __attribute__((noinline)) {
6715 int i = 0;
6716 for (/**/; i < (int)__builtin_object_size(p, 0); ++i) {
6717 p[i] = 0;
6718 }
6719 return i;
6720 }
6721
6722 int main() {
6723 char chars[100];
6724 int n = bzero1(&chars[0]);
6725 assert(n == sizeof(chars));
6726 return 0;
6727 }
6728
6729If successfully evaluating ``__builtin_object_size(param, Type)`` at the
6730callsite is not possible, then the "failed" value is passed in. So, using the
6731definition of ``bzero1`` from above, the following code would exit cleanly:
6732
6733.. code-block:: c
6734
6735 int main2(int argc, char *argv[]) {
6736 int n = bzero1(argv);
6737 assert(n == -1);
6738 return 0;
6739 }
6740
6741``pass_object_size`` plays a part in overload resolution. If two overload
6742candidates are otherwise equally good, then the overload with one or more
6743parameters with ``pass_object_size`` is preferred. This implies that the choice
6744between two identical overloads both with ``pass_object_size`` on one or more
6745parameters will always be ambiguous; for this reason, having two such overloads
6746is illegal. For example:
6747
6748.. code-block:: c++
6749
6750 #define PS(N) __attribute__((pass_object_size(N)))
6751 // OK
6752 void Foo(char *a, char *b); // Overload A
6753 // OK -- overload A has no parameters with pass_object_size.
6754 void Foo(char *a PS(0), char *b PS(0)); // Overload B
6755 // Error -- Same signature (sans pass_object_size) as overload B, and both
6756 // overloads have one or more parameters with the pass_object_size attribute.
6757 void Foo(void *a PS(0), void *b);
6758
6759 // OK
6760 void Bar(void *a PS(0)); // Overload C
6761 // OK
6762 void Bar(char *c PS(1)); // Overload D
6763
6764 void main() {
6765 char known[10], *unknown;
6766 Foo(unknown, unknown); // Calls overload B
6767 Foo(known, unknown); // Calls overload B
6768 Foo(unknown, known); // Calls overload B
6769 Foo(known, known); // Calls overload B
6770
6771 Bar(known); // Calls overload D
6772 Bar(unknown); // Calls overload D
6773 }
6774
6775Currently, ``pass_object_size`` is a bit restricted in terms of its usage:
6776
6777* Only one use of ``pass_object_size`` is allowed per parameter.
6778
6779* It is an error to take the address of a function with ``pass_object_size`` on
6780 any of its parameters. If you wish to do this, you can create an overload
6781 without ``pass_object_size`` on any parameters.
6782
6783* It is an error to apply the ``pass_object_size`` attribute to parameters that
6784 are not pointers. Additionally, any parameter that ``pass_object_size`` is
6785 applied to must be marked ``const`` at its function's definition.
6786
6787Clang also supports the ``pass_dynamic_object_size`` attribute, which behaves
6788identically to ``pass_object_size``, but evaluates a call to
6789``__builtin_dynamic_object_size`` at the callee instead of
6790``__builtin_object_size``. ``__builtin_dynamic_object_size`` provides some extra
6791runtime checks when the object size can't be determined at compile-time. You can
6792read more about ``__builtin_dynamic_object_size`` `here
6793<https://clang.llvm.org/docs/LanguageExtensions.html#evaluating-object-size-dynamically>`_.)reST";
6794
6795static const char AttrDoc_PatchableFunctionEntry[] = R"reST(``__attribute__((patchable_function_entry(N,M,Section)))`` is used to generate M
6796NOPs before the function entry and N-M NOPs after the function entry, with a record of
6797the entry stored in section ``Section``. This attribute takes precedence over the
6798command line option ``-fpatchable-function-entry=N,M,Section``. ``M`` defaults to 0
6799if omitted.``Section`` defaults to the ``-fpatchable-function-entry`` section name if
6800set, or to ``__patchable_function_entries`` otherwise.
6801
6802This attribute is only supported on
6803aarch64/aarch64-be/loongarch32/loongarch64/riscv32/riscv64/i386/x86-64/ppc/ppc64/ppc64le/s390x targets.
6804For ppc/ppc64 targets, AIX is still not supported.)reST";
6805
6806static const char AttrDoc_Pcs[] = R"reST(On ARM targets, this attribute can be used to select calling conventions
6807similar to ``stdcall`` on x86. Valid parameter values are "aapcs" and
6808"aapcs-vfp".)reST";
6809
6810static const char AttrDoc_Personality[] = R"reST(``__attribute__((personality(<routine>)))`` is used to specify a personality
6811routine that is different from the language that is being used to implement the
6812function. This is a targeted, low-level feature aimed at language runtime
6813implementors who write runtime support code in C/C++ but need that code to
6814participate in a foreign language's exception-handling or unwinding model.
6815
6816A personality routine is a language-specific callback attached to each stack
6817frame that the unwinder invokes to determine whether that frame handles a given
6818exception and what cleanup actions to perform. It effectively colors the
6819language-agnostic unwinding mechanism with language-specific semantics, enabling
6820different languages to coexist on the same call stack while each interpreting
6821exceptions according to their own rules.)reST";
6822
6823static const char AttrDoc_Pointer[] = R"reST(.. Note:: This attribute is experimental and its effect on analysis is subject to change in
6824 a future version of clang.
6825
6826The attribute ``[[gsl::Pointer(T)]]`` applies to structs and classes that behave
6827like pointers to an object of type ``T``:
6828
6829.. code::
6830
6831 class [[gsl::Pointer(int)]] IntPointer {
6832 private:
6833 int *valuePointer;
6834 public:
6835 IntPointer(const IntOwner&);
6836 int *getInt() { return valuePointer; }
6837 };
6838
6839The argument ``T`` is optional and is ignored.
6840This attribute may be used by analysis tools and has no effect on code
6841generation. A ``void`` argument means that the pointer can point to any type.
6842
6843Example:
6844When constructing an instance of a class annotated like this (a Pointer) from
6845an instance of a class annotated with ``[[gsl::Owner]]`` (an Owner),
6846then the analysis will consider the Pointer to point inside the Owner.
6847When the Owner's lifetime ends, it will consider the Pointer to be dangling.
6848
6849.. code-block:: c++
6850
6851 int f() {
6852 IntPointer P(IntOwner{}); // P "points into" a temporary IntOwner object
6853 P.getInt(); // P is dangling
6854 }
6855
6856**Transparent Member Functions**
6857
6858The analysis automatically tracks certain member functions of ``[[gsl::Pointer]]`` types
6859that provide transparent access to the pointed-to object. These include:
6860
6861* Dereference operators: ``operator*``, ``operator->``
6862* Data access methods: ``data()``, ``c_str()``, ``get()``
6863* Iterator methods: ``begin()``, ``end()``, ``rbegin()``, ``rend()``, ``cbegin()``, ``cend()``, ``crbegin()``, ``crend()``
6864
6865When these methods return pointers, view types, or references, the analysis treats them as
6866transparently borrowing from the same object that the pointer itself borrows from,
6867enabling detection of use-after-free through these access patterns:
6868
6869.. code-block:: c++
6870
6871 // For example, .data() here returns a borrow to 's' instead of 'v'.
6872 const char* f() {
6873 std::string s = "hello";
6874 std::string_view v = s; // warning: address of stack memory returned
6875 return v.data(); // note: returned here
6876 }
6877
6878 const MyObj& g(MyObj obj) {
6879 View v = obj; // warning: address of stack memory returned
6880 return *v; // note: returned here
6881 }
6882
6883This tracking also applies to range-based for loops, where the ``begin()`` and ``end()``
6884iterators are used to access elements:
6885
6886.. code-block:: c++
6887
6888 std::string_view f(std::vector<std::string> vec) {
6889 for (const std::string& s : vec) { // warning: address of stack memory returned
6890 return s; // note: returned here
6891 }
6892 }
6893
6894**Container Template Specialization**
6895
6896If a template class is annotated with ``[[gsl::Owner]]``, and the first
6897instantiated template argument is a pointer type (raw pointer, or ``[[gsl::Pointer]]``),
6898the analysis will consider the instantiated class as a container of the pointer.
6899When constructing such an object from a GSL owner object, the analysis will
6900assume that the container holds a pointer to the owner object. Consequently,
6901when the owner object is destroyed, the pointer will be considered dangling.
6902
6903.. code-block:: c++
6904
6905 int f() {
6906 std::vector<std::string_view> v = {std::string()}; // v holds a dangling pointer.
6907 std::optional<std::string_view> o = std::string(); // o holds a dangling pointer.
6908 })reST";
6909
6910static const char AttrDoc_PointerAuth[] = R"reST(The ``__ptrauth`` qualifier allows the programmer to directly control
6911how pointers are signed when they are stored in a particular variable.
6912This can be used to strengthen the default protections of pointer
6913authentication and make it more difficult for an attacker to escalate
6914an ability to alter memory into full control of a process.
6915
6916.. code-block:: c
6917
6918 #include <ptrauth.h>
6919
6920 typedef void (*my_callback)(const void*);
6921 my_callback __ptrauth(ptrauth_key_process_dependent_code, 1, 0xe27a) callback;
6922
6923The first argument to ``__ptrauth`` is the name of the signing key.
6924Valid key names for the target are defined in ``<ptrauth.h>``.
6925
6926The second argument to ``__ptrauth`` is a flag (0 or 1) specifying whether
6927the object should use address discrimination.
6928
6929The third argument to ``__ptrauth`` is a 16-bit non-negative integer which
6930allows additional discrimination between objects.)reST";
6931
6932static const char AttrDoc_PointerFieldProtection[] = R"reST(No documentation.)reST";
6933
6934static const char AttrDoc_PragmaClangBSSSection[] = R"reST()reST";
6935
6936static const char AttrDoc_PragmaClangDataSection[] = R"reST()reST";
6937
6938static const char AttrDoc_PragmaClangRelroSection[] = R"reST()reST";
6939
6940static const char AttrDoc_PragmaClangRodataSection[] = R"reST()reST";
6941
6942static const char AttrDoc_PragmaClangTextSection[] = R"reST()reST";
6943
6944static const char AttrDoc_PreferredName[] = R"reST(The ``preferred_name`` attribute can be applied to a class template, and
6945specifies a preferred way of naming a specialization of the template. The
6946preferred name will be used whenever the corresponding template specialization
6947would otherwise be printed in a diagnostic or similar context.
6948
6949The preferred name must be a typedef or type alias declaration that refers to a
6950specialization of the class template (not including any type qualifiers). In
6951general this requires the template to be declared at least twice. For example:
6952
6953.. code-block:: c++
6954
6955 template<typename T> struct basic_string;
6956 using string = basic_string<char>;
6957 using wstring = basic_string<wchar_t>;
6958 template<typename T> struct [[clang::preferred_name(string),
6959 clang::preferred_name(wstring)]] basic_string {
6960 // ...
6961 };
6962
6963
6964Note that the ``preferred_name`` attribute will be ignored when the compiler
6965writes a C++20 Module interface now. This is due to a compiler issue
6966(https://github.com/llvm/llvm-project/issues/56490) that blocks users to modularize
6967declarations with `preferred_name`. This is intended to be fixed in the future.)reST";
6968
6969static const char AttrDoc_PreferredType[] = R"reST(This attribute allows adjusting the type of a bit-field in debug information.
6970This can be helpful when a bit-field is intended to store an enumeration value,
6971but has to be specified as having the enumeration's underlying type in order to
6972facilitate compiler optimizations or bit-field packing behavior. Normally, the
6973underlying type is what is emitted in debug information, which can make it hard
6974for debuggers to know to map a bit-field's value back to a particular enumeration.
6975
6976.. code-block:: c++
6977
6978 enum Colors { Red, Green, Blue };
6979
6980 struct S {
6981 [[clang::preferred_type(Colors)]] unsigned ColorVal : 2;
6982 [[clang::preferred_type(bool)]] unsigned UseAlternateColorSpace : 1;
6983 } s = { Green, false };
6984
6985Without the attribute, a debugger is likely to display the value ``1`` for ``ColorVal``
6986and ``0`` for ``UseAlternateColorSpace``. With the attribute, the debugger may now
6987display ``Green`` and ``false`` instead.
6988
6989This can be used to map a bit-field to an arbitrary type that isn't integral
6990or an enumeration type. For example:
6991
6992.. code-block:: c++
6993
6994 struct A {
6995 short a1;
6996 short a2;
6997 };
6998
6999 struct B {
7000 [[clang::preferred_type(A)]] unsigned b1 : 32 = 0x000F'000C;
7001 };
7002
7003will associate the type ``A`` with the ``b1`` bit-field and is intended to display
7004something like this in the debugger:
7005
7006.. code-block:: text
7007
7008 Process 2755547 stopped
7009 * thread #1, name = 'test-preferred-', stop reason = step in
7010 frame #0: 0x0000555555555148 test-preferred-type`main at test.cxx:13:14
7011 10 int main()
7012 11 {
7013 12 B b;
7014 -> 13 return b.b1;
7015 14 }
7016 (lldb) v -T
7017 (B) b = {
7018 (A:32) b1 = {
7019 (short) a1 = 12
7020 (short) a2 = 15
7021 }
7022 }
7023
7024Note that debuggers may not be able to handle more complex mappings, and so
7025this usage is debugger-dependent.)reST";
7026
7027static const char AttrDoc_PreserveAll[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
7028a function. The ``preserve_all`` calling convention attempts to make the code
7029in the caller even less intrusive than the ``preserve_most`` calling convention.
7030This calling convention also behaves identical to the ``C`` calling convention
7031on how arguments and return values are passed, but it uses a different set of
7032caller/callee-saved registers. This removes the burden of saving and
7033recovering a large register set before and after the call in the caller. If
7034the arguments are passed in callee-saved registers, then they will be
7035preserved by the callee across the call. This doesn't apply for values
7036returned in callee-saved registers.
7037
7038- On X86-64 the callee preserves all general purpose registers, except for
7039 R11. R11 can be used as a scratch register. Furthermore it also preserves
7040 all floating-point registers (XMMs/YMMs).
7041
7042- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
7043 X16-X18. Furthermore it also preserves lower 128 bits of V8-V31 SIMD - floating
7044 point registers.
7045
7046The idea behind this convention is to support calls to runtime functions
7047that don't need to call out to any other functions.
7048
7049This calling convention, like the ``preserve_most`` calling convention, will be
7050used by a future version of the Objective-C runtime and should be considered
7051experimental at this time.)reST";
7052
7053static const char AttrDoc_PreserveMost[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
7054a function. The ``preserve_most`` calling convention attempts to make the code
7055in the caller as unintrusive as possible. This convention behaves identically
7056to the ``C`` calling convention on how arguments and return values are passed,
7057but it uses a different set of caller/callee-saved registers. This alleviates
7058the burden of saving and recovering a large register set before and after the
7059call in the caller. If the arguments are passed in callee-saved registers,
7060then they will be preserved by the callee across the call. This doesn't
7061apply for values returned in callee-saved registers.
7062
7063- On X86-64 the callee preserves all general purpose registers, except for
7064 R11. R11 can be used as a scratch register. Floating-point registers
7065 (XMMs/YMMs) are not preserved and need to be saved by the caller.
7066
7067- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
7068 X16-X18.
7069
7070The idea behind this convention is to support calls to runtime functions
7071that have a hot path and a cold path. The hot path is usually a small piece
7072of code that doesn't use many registers. The cold path might need to call out to
7073another function and therefore only needs to preserve the caller-saved
7074registers, which haven't already been saved by the caller. The
7075``preserve_most`` calling convention is very similar to the ``cold`` calling
7076convention in terms of caller/callee-saved registers, but they are used for
7077different types of function calls. ``coldcc`` is for function calls that are
7078rarely executed, whereas ``preserve_most`` function calls are intended to be
7079on the hot path and definitely executed a lot. Furthermore ``preserve_most``
7080doesn't prevent the inliner from inlining the function call.
7081
7082This calling convention will be used by a future version of the Objective-C
7083runtime and should therefore still be considered experimental at this time.
7084Although this convention was created to optimize certain runtime calls to
7085the Objective-C runtime, it is not limited to this runtime and might be used
7086by other runtimes in the future too. The current implementation only
7087supports X86-64 and AArch64, but the intention is to support more architectures
7088in the future.)reST";
7089
7090static const char AttrDoc_PreserveNone[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of a function.
7091The ``preserve_none`` calling convention tries to preserve as few general
7092registers as possible. So all general registers are caller saved registers. It
7093also uses more general registers to pass arguments. This attribute doesn't
7094impact floating-point registers. ``preserve_none``'s ABI is still unstable, and
7095may be changed in the future.
7096
7097- On X86-64, only RSP and RBP are preserved by the callee.
7098 Registers R12, R13, R14, R15, RDI, RSI, RDX, RCX, R8, R9, R11, and RAX now can
7099 be used to pass function arguments. Floating-point registers (XMMs/YMMs) still
7100 follow the C calling convention.
7101- On AArch64, only LR and FP are preserved by the callee.
7102 Registers X20-X28, X0-X7, and X9-X14 are used to pass function arguments.
7103 X8, X16-X19, SIMD and floating-point registers follow the AAPCS calling
7104 convention. X15 is not available for argument passing on Windows, but is
7105 used to pass arguments on other platforms.)reST";
7106
7107static const char AttrDoc_PtGuardedBy[] = R"reST(No documentation.)reST";
7108
7109static const char AttrDoc_PtGuardedVar[] = R"reST(No documentation.)reST";
7110
7111static const char AttrDoc_Ptr32[] = R"reST(The ``__ptr32`` qualifier represents a native pointer on a 32-bit system. On a
711264-bit system, a pointer with ``__ptr32`` is extended to a 64-bit pointer. The
7113``__sptr`` and ``__uptr`` qualifiers can be used to specify whether the pointer
7114is sign extended or zero extended. This qualifier is enabled under
7115``-fms-extensions``.)reST";
7116
7117static const char AttrDoc_Ptr64[] = R"reST(The ``__ptr64`` qualifier represents a native pointer on a 64-bit system. On a
711832-bit system, a ``__ptr64`` pointer is truncated to a 32-bit pointer. This
7119qualifier is enabled under ``-fms-extensions``.)reST";
7120
7121static const char AttrDoc_Pure[] = R"reST(No documentation.)reST";
7122
7123static const char AttrDoc_RISCVInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt))`` attribute on RISCV
7124targets. This attribute may be attached to a function definition and instructs
7125the backend to generate appropriate function entry/exit code so that it can be
7126used directly as an interrupt service routine.
7127
7128Permissible values for this parameter are ``machine``, ``supervisor``,
7129``rnmi``, ``qci-nest``, ``qci-nonest``, ``SiFive-CLIC-preemptible``, and
7130``SiFive-CLIC-stack-swap``. If there is no parameter, then it defaults to
7131``machine``.
7132
7133The ``rnmi`` value is used for resumable non-maskable interrupts. It requires the
7134standard Smrnmi extension.
7135
7136The ``qci-nest`` and ``qci-nonest`` values require Qualcomm's Xqciint extension
7137and are used for Machine-mode Interrupts and Machine-mode Non-maskable
7138interrupts. These use the following instructions from Xqciint to save and
7139restore interrupt state to the stack -- the ``qci-nest`` value will use
7140``qc.c.mienter.nest`` and the ``qci-nonest`` value will use ``qc.c.mienter`` to
7141begin the interrupt handler. Both of these will use ``qc.c.mileaveret`` to
7142restore the state and return to the previous context.
7143
7144The ``SiFive-CLIC-preemptible`` and ``SiFive-CLIC-stack-swap`` values are used
7145for machine-mode interrupts. For ``SiFive-CLIC-preemptible`` interrupts, the
7146values of ``mcause`` and ``mepc`` are saved onto the stack, and interrupts are
7147re-enabled. For ``SiFive-CLIC-stack-swap`` interrupts, the stack pointer is
7148swapped with ``mscratch`` before its first use and after its last use.
7149
7150The SiFive CLIC values may be combined with each other and with the ``machine``
7151attribute value. Any other combination of different values is not allowed.
7152
7153Repeated interrupt attribute on the same declaration will cause a warning
7154to be emitted. In case of repeated declarations, the last one prevails.
7155
7156Refer to:
7157https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html
7158https://riscv.org/specifications/privileged-isa/
7159The RISC-V Instruction Set Manual Volume II: Privileged Architecture
7160Version 1.10.
7161https://github.com/quic/riscv-unified-db/releases/tag/Xqci-0.13.0
7162https://sifive.cdn.prismic.io/sifive/d1984d2b-c9b9-4c91-8de0-d68a5e64fa0f_sifive-interrupt-cookbook-v1p2.pdf)reST";
7163
7164static const char AttrDoc_RISCVVLSCC[] = R"reST(The ``riscv_vls_cc`` attribute can be applied to a function. Functions
7165declared with this attribute will utilize the standard fixed-length vector
7166calling convention variant instead of the default calling convention defined by
7167the ABI. This variant aims to pass fixed-length vectors via vector registers,
7168if possible, rather than through general-purpose registers.)reST";
7169
7170static const char AttrDoc_RISCVVectorCC[] = R"reST(The ``riscv_vector_cc`` attribute can be applied to a function. It preserves 15
7171registers namely, v1-v7 and v24-v31 as callee-saved. Callers thus don't need
7172to save these registers before function calls, and callees only need to save
7173them if they use them.)reST";
7174
7175static const char AttrDoc_RandomizeLayout[] = R"reST(The attribute ``randomize_layout``, when attached to a C structure, selects it
7176for structure layout field randomization; a compile-time hardening technique. A
7177"seed" value, is specified via the ``-frandomize-layout-seed=`` command line flag.
7178For example:
7179
7180.. code-block:: bash
7181
7182 SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
7183 make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
7184
7185You can also supply the seed in a file with ``-frandomize-layout-seed-file=``.
7186For example:
7187
7188.. code-block:: bash
7189
7190 od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
7191 make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
7192
7193The randomization is deterministic based for a given seed, so the entire
7194program should be compiled with the same seed, but keep the seed safe
7195otherwise.
7196
7197The attribute ``no_randomize_layout``, when attached to a C structure,
7198instructs the compiler that this structure should not have its field layout
7199randomized.)reST";
7200
7201static const char AttrDoc_ReadOnlyPlacement[] = R"reST(This attribute is attached to a structure, class or union declaration.
7202 When attached to a record declaration/definition, it checks if all instances
7203 of this type can be placed in the read-only data segment of the program. If it
7204 finds an instance that can not be placed in a read-only segment, the compiler
7205 emits a warning at the source location where the type was used.
7206
7207 Examples:
7208 * ``struct __attribute__((enforce_read_only_placement)) Foo;``
7209 * ``struct __attribute__((enforce_read_only_placement)) Bar { ... };``
7210
7211 Both ``Foo`` and ``Bar`` types have the ``enforce_read_only_placement`` attribute.
7212
7213 The goal of introducing this attribute is to assist developers with writing secure
7214 code. A ``const``-qualified global is generally placed in the read-only section
7215 of the memory that has additional run time protection from malicious writes. By
7216 attaching this attribute to a declaration, the developer can express the intent
7217 to place all instances of the annotated type in the read-only program memory.
7218
7219 Note 1: The attribute doesn't guarantee that the object will be placed in the
7220 read-only data segment as it does not instruct the compiler to ensure such
7221 a placement. It emits a warning if something in the code can be proven to prevent
7222 an instance from being placed in the read-only data segment.
7223
7224 Note 2: Currently, clang only checks if all global declarations of a given type 'T'
7225 are ``const``-qualified. The following conditions would also prevent the data to be
7226 put into read only segment, but the corresponding warnings are not yet implemented.
7227
7228 1. An instance of type ``T`` is allocated on the heap/stack.
7229 2. Type ``T`` defines/inherits a mutable field.
7230 3. Type ``T`` defines/inherits non-constexpr constructor(s) for initialization.
7231 4. A field of type ``T`` is defined by type ``Q``, which does not bear the
7232 ``enforce_read_only_placement`` attribute.
7233 5. A type ``Q`` inherits from type ``T`` and it does not have the
7234 ``enforce_read_only_placement`` attribute.)reST";
7235
7236static const char AttrDoc_ReentrantCapability[] = R"reST(No documentation.)reST";
7237
7238static const char AttrDoc_RegCall[] = R"reST(On x86 targets, this attribute changes the calling convention to
7239`__regcall`_ convention. This convention aims to pass as many arguments
7240as possible in registers. It also tries to utilize registers for the
7241return value whenever it is possible.
7242
7243.. _`__regcall`: https://www.intel.com/content/www/us/en/docs/dpcpp-cpp-compiler/developer-guide-reference/2023-2/c-c-sycl-calling-conventions.html)reST";
7244
7245static const char AttrDoc_Reinitializes[] = R"reST(The ``reinitializes`` attribute can be applied to a non-static, non-const C++
7246member function to indicate that this member function reinitializes the entire
7247object to a known state, independent of the previous state of the object.
7248
7249This attribute can be interpreted by static analyzers that warn about uses of an
7250object that has been left in an indeterminate state by a move operation. If a
7251member function marked with the ``reinitializes`` attribute is called on a
7252moved-from object, the analyzer can conclude that the object is no longer in an
7253indeterminate state.
7254
7255A typical example where this attribute would be used is on functions that clear
7256a container class:
7257
7258.. code-block:: c++
7259
7260 template <class T>
7261 class Container {
7262 public:
7263 ...
7264 [[clang::reinitializes]] void Clear();
7265 ...
7266 };)reST";
7267
7268static const char AttrDoc_ReleaseCapability[] = R"reST(Marks a function as releasing a capability.)reST";
7269
7270static const char AttrDoc_ReleaseHandle[] = R"reST(If a function parameter is annotated with ``release_handle(tag)`` it is assumed to
7271close the handle. It is also assumed to require an open handle to work with. The
7272attribute requires a string literal argument to identify the handle being released.
7273
7274.. code-block:: c++
7275
7276 zx_status_t zx_handle_close(zx_handle_t handle [[clang::release_handle("tag")]]);)reST";
7277
7278static const char AttrDoc_ReqdWorkGroupSize[] = R"reST(No documentation.)reST";
7279
7280static const char AttrDoc_RequiresCapability[] = R"reST(No documentation.)reST";
7281
7282static const char AttrDoc_Restrict[] = R"reST(The ``malloc`` attribute has two forms with different functionality. The first
7283is when it is used without arguments, where it marks that a function acts like
7284a system memory allocation function, returning a pointer to allocated storage
7285that does not alias storage from any other object accessible to the caller.
7286
7287The second form is when ``malloc`` takes one or two arguments. The first
7288argument names a function that should be associated with this function as its
7289deallocation function. When this form is used, it enables the compiler to
7290diagnose when the incorrect deallocation function is used with this variable.
7291However the associated warning, spelled `-Wmismatched-dealloc` in GCC, is not
7292yet implemented in clang.)reST";
7293
7294static const char AttrDoc_Retain[] = R"reST(This attribute, when attached to a function or variable definition, prevents
7295section garbage collection in the linker. It does not prevent other discard
7296mechanisms, such as archive member selection, and COMDAT group resolution.
7297
7298If the compiler does not emit the definition, e.g. because it was not used in
7299the translation unit or the compiler was able to eliminate all of the uses,
7300this attribute has no effect. This attribute is typically combined with the
7301``used`` attribute to force the definition to be emitted and preserved into the
7302final linked image.
7303
7304This attribute is only necessary on ELF targets; other targets prevent section
7305garbage collection by the linker when using the ``used`` attribute alone.
7306Using the attributes together should result in consistent behavior across
7307targets.
7308
7309This attribute requires the linker to support the ``SHF_GNU_RETAIN`` extension.
7310This support is available in GNU ``ld`` and ``gold`` as of binutils 2.36, as
7311well as in ``ld.lld`` 13.)reST";
7312
7313static const char AttrDoc_ReturnTypestate[] = R"reST(The ``return_typestate`` attribute can be applied to functions or parameters.
7314When applied to a function the attribute specifies the state of the returned
7315value. The function's body is checked to ensure that it always returns a value
7316in the specified state. On the caller side, values returned by the annotated
7317function are initialized to the given state.
7318
7319When applied to a function parameter it modifies the state of an argument after
7320a call to the function returns. The function's body is checked to ensure that
7321the parameter is in the expected state before returning.)reST";
7322
7323static const char AttrDoc_ReturnsNonNull[] = R"reST(The ``returns_nonnull`` attribute indicates that a particular function (or
7324Objective-C method) always returns a non-null pointer. For example, a
7325particular system ``malloc`` might be defined to terminate a process when
7326memory is not available rather than returning a null pointer:
7327
7328 .. code-block:: c
7329
7330 extern void * malloc (size_t size) __attribute__((returns_nonnull));
7331
7332The ``returns_nonnull`` attribute implies that returning a null pointer is
7333undefined behavior, which the optimizer may take advantage of. The ``_Nonnull``
7334type qualifier indicates that a pointer cannot be null in a more general manner
7335(because it is part of the type system) and does not imply undefined behavior,
7336making it more widely applicable)reST";
7337
7338static const char AttrDoc_ReturnsTwice[] = R"reST(No documentation.)reST";
7339
7340static const char AttrDoc_RootSignature[] = R"reST(The ``RootSignature`` attribute applies to HLSL entry functions to define what
7341types of resources are bound to the graphics pipeline.
7342
7343For details about the use and specification of Root Signatures please see here:
7344https://learn.microsoft.com/en-us/windows/win32/direct3d12/root-signatures)reST";
7345
7346static const char AttrDoc_SPtr[] = R"reST(The ``__sptr`` qualifier specifies that a 32-bit pointer should be sign
7347extended when converted to a 64-bit pointer.)reST";
7348
7349static const char AttrDoc_SYCLExternal[] = R"reST(The ``sycl_external`` attribute indicates that a function defined in another
7350translation unit may be called by a device function defined in the current
7351translation unit or, if defined in the current translation unit, the function
7352may be called by device functions defined in other translation units.
7353The attribute is intended for use in the implementation of the ``SYCL_EXTERNAL``
7354macro as specified in section 5.10.1, "SYCL functions and member functions
7355linkage", of the SYCL 2020 specification.
7356
7357The attribute only appertains to functions and only those that meet the
7358following requirements:
7359
7360* Has external linkage
7361* Is not explicitly defined as deleted (the function may be an explicitly
7362 defaulted function that is defined as deleted)
7363
7364The attribute shall be present on the first declaration of a function and
7365may optionally be present on subsequent declarations.
7366
7367When compiling for a SYCL device target that does not support the generic
7368address space, the function shall not specify a raw pointer or reference type
7369as the return type or as a parameter type.
7370See section 5.10, "SYCL offline linking", of the SYCL 2020 specification.
7371The following examples demonstrate the use of this attribute:
7372
7373.. code-block:: c++
7374
7375 [[clang::sycl_external]] void Foo(); // Ok.
7376
7377 [[clang::sycl_external]] void Bar() { /* ... */ } // Ok.
7378
7379 [[clang::sycl_external]] extern void Baz(); // Ok.
7380
7381 [[clang::sycl_external]] static void Quux() { /* ... */ } // error: Quux() has internal linkage.)reST";
7382
7383static const char AttrDoc_SYCLKernel[] = R"reST(The ``sycl_kernel`` attribute specifies that a function template will be used
7384to outline device code and to generate an OpenCL kernel.
7385Here is a code example of the SYCL program, which demonstrates the compiler's
7386outlining job:
7387
7388.. code-block:: c++
7389
7390 int foo(int x) { return ++x; }
7391
7392 using namespace cl::sycl;
7393 queue Q;
7394 buffer<int, 1> a(range<1>{1024});
7395 Q.submit([&](handler& cgh) {
7396 auto A = a.get_access<access::mode::write>(cgh);
7397 cgh.parallel_for<init_a>(range<1>{1024}, [=](id<1> index) {
7398 A[index] = index[0] + foo(42);
7399 });
7400 }
7401
7402A C++ function object passed to the ``parallel_for`` is called a "SYCL kernel".
7403A SYCL kernel defines the entry point to the "device part" of the code. The
7404compiler will emit all symbols accessible from a "kernel". In this code
7405example, the compiler will emit "foo" function. More details about the
7406compilation of functions for the device part can be found in the SYCL 1.2.1
7407specification Section 6.4.
7408To show to the compiler entry point to the "device part" of the code, the SYCL
7409runtime can use the ``sycl_kernel`` attribute in the following way:
7410
7411.. code-block:: c++
7412
7413 namespace cl {
7414 namespace sycl {
7415 class handler {
7416 template <typename KernelName, typename KernelType/*, ...*/>
7417 __attribute__((sycl_kernel)) void sycl_kernel_function(KernelType KernelFuncObj) {
7418 // ...
7419 KernelFuncObj();
7420 }
7421
7422 template <typename KernelName, typename KernelType, int Dims>
7423 void parallel_for(range<Dims> NumWorkItems, KernelType KernelFunc) {
7424 #ifdef __SYCL_DEVICE_ONLY__
7425 sycl_kernel_function<KernelName, KernelType, Dims>(KernelFunc);
7426 #else
7427 // Host implementation
7428 #endif
7429 }
7430 };
7431 } // namespace sycl
7432 } // namespace cl
7433
7434The compiler will also generate an OpenCL kernel using the function marked with
7435the ``sycl_kernel`` attribute.
7436Here is the list of SYCL device compiler expectations with regard to the
7437function marked with the ``sycl_kernel`` attribute:
7438
7439- The function must be a template with at least two type template parameters.
7440 The compiler generates an OpenCL kernel and uses the first template parameter
7441 as a unique name for the generated OpenCL kernel. The host application uses
7442 this unique name to invoke the OpenCL kernel generated for the SYCL kernel
7443 specialized by this name and second template parameter ``KernelType`` (which
7444 might be an unnamed function object type).
7445- The function must have at least one parameter. The first parameter is
7446 required to be a function object type (named or unnamed i.e. lambda). The
7447 compiler uses function object type fields to generate OpenCL kernel
7448 parameters.
7449- The function must return void. The compiler reuses the body of marked functions to
7450 generate the OpenCL kernel body, and the OpenCL kernel must return ``void``.
7451
7452The SYCL kernel in the previous code sample meets these expectations.)reST";
7453
7454static const char AttrDoc_SYCLKernelEntryPoint[] = R"reST(The ``sycl_kernel_entry_point`` attribute facilitates the launch of a SYCL
7455kernel and the generation of an offload kernel entry point, sometimes called
7456a SYCL kernel caller function, suitable for invoking a SYCL kernel on an
7457offload device. The attribute is intended for use in the implementation of
7458SYCL kernel invocation functions like the ``single_task`` and ``parallel_for``
7459member functions of the ``sycl::handler`` class specified in section 4.9.4,
7460"Command group ``handler`` class", of the SYCL 2020 specification.
7461
7462The attribute requires a single type argument that meets the requirements for
7463a SYCL kernel name as described in section 5.2, "Naming of kernels", of the
7464SYCL 2020 specification. A unique kernel name type is required for each
7465function declared with the attribute. The attribute may not first appear on a
7466declaration that follows a definition of the function.
7467
7468The attribute only appertains to functions and only those that meet the
7469following requirements.
7470
7471* Has a non-deduced ``void`` return type.
7472* Is not a constructor or destructor.
7473* Is not a non-static member function with an explicit object parameter.
7474* Is not a C variadic function.
7475* Is not a coroutine.
7476* Is not defined as deleted or as defaulted.
7477* Is not defined with a function try block.
7478* Is not declared with the ``constexpr`` or ``consteval`` specifiers.
7479* Is not declared with the ``[[noreturn]]`` attribute.
7480
7481Use in the implementation of a SYCL kernel invocation function might look as
7482follows.
7483
7484.. code-block:: c++
7485
7486 namespace sycl {
7487 class handler {
7488 template<typename KernelName, typename... Ts>
7489 void sycl_kernel_launch(const char* kernelSymbol, Ts&&... kernelArgs) {
7490 // This code will run on the host and is responsible for calling functions
7491 // appropriate for the desired offload backend (OpenCL, CUDA, HIP,
7492 // Level Zero, etc...) to copy the kernel arguments denoted by kernelArgs
7493 // to a device and to schedule an invocation of the offload kernel entry
7494 // point denoted by kernelSymbol with the copied arguments.
7495 }
7496
7497 template<typename KernelName, typename KernelType>
7498 [[ clang::sycl_kernel_entry_point(KernelName) ]]
7499 void kernel_entry_point(KernelType kernelFunc) {
7500 // This code will run on the device. The call to kernelFunc() invokes
7501 // the SYCL kernel.
7502 kernelFunc();
7503 }
7504
7505 public:
7506 template<typename KernelName, typename KernelType>
7507 void single_task(const KernelType& kernelFunc) {
7508 // This code will run on the host. kernel_entry_point() is called to
7509 // trigger generation of an offload kernel entry point and to schedule
7510 // an invocation of it on a device with kernelFunc (a SYCL kernel object)
7511 // passed as a kernel argument. This call will result in an implicit call
7512 // to sycl_kernel_launch() with the symbol name for the generated offload
7513 // kernel entry point passed as the first function argument followed by
7514 // kernelFunc.
7515 kernel_entry_point<KernelName>(kernelFunc);
7516 }
7517 };
7518 } // namespace sycl
7519
7520A SYCL kernel object is a callable object of class type that is constructed on
7521a host, often via a lambda expression, and then passed to a SYCL kernel
7522invocation function to be executed on an offload device. The ``kernelFunc``
7523parameters in the example code above correspond to SYCL kernel objects.
7524
7525A SYCL kernel object type is required to satisfy the device copyability
7526requirements specified in section 3.13.1, "Device copyable", of the SYCL 2020
7527specification. Additionally, any data members of the kernel object type are
7528required to satisfy section 4.12.4, "Rules for parameter passing to kernels".
7529For most types, these rules require that the type is trivially copyable.
7530However, the SYCL specification mandates that certain special SYCL types, such
7531as ``sycl::accessor`` and ``sycl::stream``, be device copyable even if they are
7532not trivially copyable. These types require special handling because they cannot
7533necessarily be copied to device memory as if by ``memcpy()``.
7534
7535The SYCL kernel object and its data members constitute the parameters of an
7536offload kernel. An offload kernel consists of an offload entry point function
7537and the set of all functions and variables that are directly or indirectly used
7538by the entry point function.
7539
7540A SYCL kernel invocation function is responsible for performing the following
7541tasks (likely with the help of an offload backend like OpenCL):
7542
7543#. Identifying the offload kernel entry point to be used for the SYCL kernel.
7544
7545#. Validating that the SYCL kernel object type and its data members meet the
7546 SYCL device copyability and kernel parameter requirements noted above.
7547
7548#. Copying the SYCL kernel object and any other kernel arguments to device
7549 memory including any special handling required for SYCL special types.
7550
7551#. Initiating execution of the offload kernel entry point.
7552
7553The offload kernel entry point for a SYCL kernel performs the following tasks:
7554
7555#. Calling the ``operator()`` member function of the SYCL kernel object.
7556
7557The ``sycl_kernel_entry_point`` attribute facilitates or automates these tasks
7558by providing generation of an offload kernel entry point with a unique symbol
7559name, type checking of kernel argument requirements, and initiation of kernel
7560execution via synthesized calls to a ``sycl_kernel_launch`` template.
7561
7562A function declared with the ``sycl_kernel_entry_point`` attribute specifies
7563the parameters and body of an offload entry point function. Consider the
7564following call to the ``single_task()`` SYCL kernel invocation function assuming
7565an implementation similar to the one shown above.
7566
7567.. code-block:: c++
7568
7569 struct S { int i; };
7570 void f(sycl::handler &handler, sycl::stream &sout, S s) {
7571 handler.single_task<struct KN>([=] {
7572 sout << "The value of s.i is " << s.i << "\n";
7573 });
7574 }
7575
7576The SYCL kernel object is the result of the lambda expression. The call to
7577``kernel_entry_point()`` via the call to ``single_task()`` triggers the
7578generation of an offload kernel entry point function that looks approximately
7579as follows.
7580
7581.. code-block:: c++
7582
7583 void sycl-kernel-caller-for-KN(kernel-type kernelFunc) {
7584 kernelFunc();
7585 }
7586
7587There are a few items worthy of note:
7588
7589#. ``sycl-kernel-caller-for-KN`` is an exposition only name; the actual name
7590 generated for an entry point is an implementation detail and subject to
7591 change. However, the name will incorporate the SYCL kernel name, ``KN``,
7592 that was passed as the ``KernelName`` template parameter to
7593 ``single_task()`` and eventually provided as the argument to the
7594 ``sycl_kernel_entry_point`` attribute in order to ensure that a unique
7595 name is generated for each entry point. There is a one-to-one correspondence
7596 between SYCL kernel names and offload kernel entry points.
7597
7598#. The SYCL kernel is a lambda closure type and therefore has no name;
7599 ``kernel-type`` is substituted above and corresponds to the ``KernelType``
7600 template parameter deduced in the call to ``single_task()``.
7601
7602#. The parameter and the call to ``kernelFunc()`` in the function body
7603 correspond to the definition of ``kernel_entry_point()`` as called by
7604 ``single_task()``.
7605
7606#. The parameter is type checked for conformance with the SYCL device
7607 copyability and kernel parameter requirements.
7608
7609Within ``single_task()``, the call to ``kernel_entry_point()`` is effectively
7610replaced with a synthesized call to a ''sycl_kernel_launch`` template that
7611looks approximately as follows.
7612
7613.. code-block:: c++
7614
7615 sycl_kernel_launch<KN>("sycl-kernel-caller-for-KN", kernelFunc);
7616
7617There are a few items worthy of note:
7618
7619#. Lookup for the ``sycl_kernel_launch`` template is performed as if from the
7620 body of the (possibly instantiated) definition of ``kernel_entry_point()``.
7621 If name lookup or overload resolution fails, the program is ill-formed.
7622 If the selected overload is a non-static member function, then ``this`` is
7623 passed as the implicit object parameter.
7624
7625#. Function arguments passed to ``sycl_kernel_launch()`` are passed
7626 as if by ``std::move(x)``.
7627
7628#. The ``sycl_kernel_launch`` template is expected to be provided by the SYCL
7629 library implementation. It is responsible for copying the kernel arguments
7630 to device memory and for scheduling execution of the generated offload
7631 kernel entry point identified by the symbol name passed as the first
7632 function argument. ``sycl-kernel-caller-for-KN`` is substituted above for
7633 the actual symbol name that would be generated for the offload kernel entry
7634 point.
7635
7636It is not necessary for a function declared with the ``sycl_kernel_entry_point``
7637attribute to be called for the offload kernel entry point to be emitted. For
7638inline functions and function templates, any ODR-use will suffice. For other
7639functions, an ODR-use is not required; the offload kernel entry point will be
7640emitted if the function is defined. In any case, a call to the function is
7641required for the synthesized call to ``sycl_kernel_launch()`` to occur.
7642
7643A function declared with the ``sycl_kernel_entry_point`` attribute may include
7644an exception specification. If a non-throwing exception specification is
7645present, an exception propagating from the implicit call to the
7646``sycl_kernel_launch`` template will result in a call to ``std::terminate()``.
7647Otherwise, such an exception will propagate normally.
7648
7649Functions declared with the ``sycl_kernel_entry_point`` attribute are not
7650limited to the simple example shown above. They may have additional template
7651parameters, declare additional function parameters, and have complex control
7652flow in the function body. The function must abide by the language feature
7653restrictions described in section 5.4, "Language restrictions for device
7654functions" in the SYCL 2020 specification. If the function is a non-static
7655member function, ``this`` shall not be used in a potentially evaluated
7656expression.)reST";
7657
7658static const char AttrDoc_SYCLSpecialClass[] = R"reST(SYCL defines some special classes (accessor, sampler, and stream) which require
7659specific handling during the generation of the SPIR entry point.
7660The ``__attribute__((sycl_special_class))`` attribute is used in SYCL
7661headers to indicate that a class or a struct needs a specific handling when
7662it is passed from host to device.
7663Special classes will have a mandatory ``__init`` method and an optional
7664``__finalize`` method (the ``__finalize`` method is used only with the
7665``stream`` type). Kernel parameters types are extract from the ``__init`` method
7666parameters. The kernel function arguments list is derived from the
7667arguments of the ``__init`` method. The arguments of the ``__init`` method are
7668copied into the kernel function argument list and the ``__init`` and
7669``__finalize`` methods are called at the beginning and the end of the kernel,
7670respectively.
7671The ``__init`` and ``__finalize`` methods must be defined inside the
7672special class.
7673Please note that this is an attribute that is used as an internal
7674implementation detail and not intended to be used by external users.
7675
7676The syntax of the attribute is as follows:
7677
7678.. code-block:: text
7679
7680 class __attribute__((sycl_special_class)) accessor {};
7681 class [[clang::sycl_special_class]] accessor {};
7682
7683This is a code example that illustrates the use of the attribute:
7684
7685.. code-block:: c++
7686
7687 class __attribute__((sycl_special_class)) SpecialType {
7688 int F1;
7689 int F2;
7690 void __init(int f1) {
7691 F1 = f1;
7692 F2 = f1;
7693 }
7694 void __finalize() {}
7695 public:
7696 SpecialType() = default;
7697 int getF2() const { return F2; }
7698 };
7699
7700 int main () {
7701 SpecialType T;
7702 cgh.single_task([=] {
7703 T.getF2();
7704 });
7705 }
7706
7707This would trigger the following kernel entry point in the AST:
7708
7709.. code-block:: c++
7710
7711 void __sycl_kernel(int f1) {
7712 SpecialType T;
7713 T.__init(f1);
7714 ...
7715 T.__finalize()
7716 })reST";
7717
7718static const char AttrDoc_ScopedLockable[] = R"reST(No documentation.)reST";
7719
7720static const char AttrDoc_Section[] = R"reST(The ``section`` attribute allows you to specify a specific section a
7721global variable or function should be in after translation.)reST";
7722
7723static const char AttrDoc_SelectAny[] = R"reST(This attribute appertains to a global symbol, causing it to have a weak
7724definition (
7725`linkonce <https://llvm.org/docs/LangRef.html#linkage-types>`_
7726), allowing the linker to select any definition.
7727
7728For more information see
7729`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html>`_
7730or `msvc documentation <https://docs.microsoft.com/pl-pl/cpp/cpp/selectany>`_.)reST";
7731
7732static const char AttrDoc_Sentinel[] = R"reST(No documentation.)reST";
7733
7734static const char AttrDoc_SetTypestate[] = R"reST(Annotate methods that transition an object into a new state with
7735``__attribute__((set_typestate(new_state)))``. The new state must be
7736unconsumed, consumed, or unknown.)reST";
7737
7738static const char AttrDoc_SizedBy[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
7739structure in C. The argument for the attribute is the name of a field member
7740holding the count of elements in the flexible array. This information can be
7741used to improve the results of the array bound sanitizer and the
7742``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
7743within the same non-anonymous, enclosing struct as the flexible array member.
7744
7745This example specifies that the flexible array member ``array`` has the number
7746of elements allocated for it in ``count``:
7747
7748.. code-block:: c
7749
7750 struct bar;
7751
7752 struct foo {
7753 size_t count;
7754 char other;
7755 struct bar *array[] __attribute__((counted_by(count)));
7756 };
7757
7758This establishes a relationship between ``array`` and ``count``. Specifically,
7759``array`` must have at least ``count`` number of elements available. It's the
7760user's responsibility to ensure that this relationship is maintained through
7761changes to the structure.
7762
7763In the following example, the allocated array erroneously has fewer elements
7764than what's specified by ``p->count``. This would result in an out-of-bounds
7765access not being detected.
7766
7767.. code-block:: c
7768
7769 #define SIZE_INCR 42
7770
7771 struct foo *p;
7772
7773 void foo_alloc(size_t count) {
7774 p = malloc(MAX(sizeof(struct foo),
7775 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
7776 p->count = count + SIZE_INCR;
7777 }
7778
7779The next example updates ``p->count``, but breaks the relationship requirement
7780that ``p->array`` must have at least ``p->count`` number of elements available:
7781
7782.. code-block:: c
7783
7784 #define SIZE_INCR 42
7785
7786 struct foo *p;
7787
7788 void foo_alloc(size_t count) {
7789 p = malloc(MAX(sizeof(struct foo),
7790 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
7791 p->count = count;
7792 }
7793
7794 void use_foo(int index, int val) {
7795 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
7796 p->array[index] = val; /* The sanitizer can't properly check this access. */
7797 }
7798
7799In this example, an update to ``p->count`` maintains the relationship
7800requirement:
7801
7802.. code-block:: c
7803
7804 void use_foo(int index, int val) {
7805 if (p->count == 0)
7806 return;
7807 --p->count;
7808 p->array[index] = val;
7809 })reST";
7810
7811static const char AttrDoc_SizedByOrNull[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
7812structure in C. The argument for the attribute is the name of a field member
7813holding the count of elements in the flexible array. This information can be
7814used to improve the results of the array bound sanitizer and the
7815``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
7816within the same non-anonymous, enclosing struct as the flexible array member.
7817
7818This example specifies that the flexible array member ``array`` has the number
7819of elements allocated for it in ``count``:
7820
7821.. code-block:: c
7822
7823 struct bar;
7824
7825 struct foo {
7826 size_t count;
7827 char other;
7828 struct bar *array[] __attribute__((counted_by(count)));
7829 };
7830
7831This establishes a relationship between ``array`` and ``count``. Specifically,
7832``array`` must have at least ``count`` number of elements available. It's the
7833user's responsibility to ensure that this relationship is maintained through
7834changes to the structure.
7835
7836In the following example, the allocated array erroneously has fewer elements
7837than what's specified by ``p->count``. This would result in an out-of-bounds
7838access not being detected.
7839
7840.. code-block:: c
7841
7842 #define SIZE_INCR 42
7843
7844 struct foo *p;
7845
7846 void foo_alloc(size_t count) {
7847 p = malloc(MAX(sizeof(struct foo),
7848 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
7849 p->count = count + SIZE_INCR;
7850 }
7851
7852The next example updates ``p->count``, but breaks the relationship requirement
7853that ``p->array`` must have at least ``p->count`` number of elements available:
7854
7855.. code-block:: c
7856
7857 #define SIZE_INCR 42
7858
7859 struct foo *p;
7860
7861 void foo_alloc(size_t count) {
7862 p = malloc(MAX(sizeof(struct foo),
7863 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
7864 p->count = count;
7865 }
7866
7867 void use_foo(int index, int val) {
7868 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
7869 p->array[index] = val; /* The sanitizer can't properly check this access. */
7870 }
7871
7872In this example, an update to ``p->count`` maintains the relationship
7873requirement:
7874
7875.. code-block:: c
7876
7877 void use_foo(int index, int val) {
7878 if (p->count == 0)
7879 return;
7880 --p->count;
7881 p->array[index] = val;
7882 })reST";
7883
7884static const char AttrDoc_SpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
7885 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_
7886 should be enabled for the function body. This can also be applied to a method
7887 in Objective C. This attribute will take precedence over the command line flag in
7888 the case where `-mno-speculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified.
7889
7890 Speculative Load Hardening is a best-effort mitigation against
7891 information leak attacks that make use of control flow
7892 miss-speculation - specifically miss-speculation of whether a branch
7893 is taken or not. Typically vulnerabilities enabling such attacks are
7894 classified as "Spectre variant #1". Notably, this does not attempt to
7895 mitigate against miss-speculation of branch target, classified as
7896 "Spectre variant #2" vulnerabilities.
7897
7898 When inlining, the attribute is sticky. Inlining a function that
7899 carries this attribute will cause the caller to gain the
7900 attribute. This is intended to provide a maximally conservative model
7901 where the code in a function annotated with this attribute will always
7902 (even after inlining) end up hardened.)reST";
7903
7904static const char AttrDoc_StackProtectorIgnore[] = R"reST(The ``stack_protector_ignore`` attribute skips analysis of the given local
7905variable when determining if a function should use a stack protector.
7906
7907The ``-fstack-protector`` option uses a heuristic to only add stack protectors
7908to functions which contain variables or buffers over some size threshold. This
7909attribute overrides that heuristic for the attached variable, opting
7910them out. If this results in no variables or buffers remaining over the stack
7911protector threshold, then the function will no longer use a stack protector.)reST";
7912
7913static const char AttrDoc_StandaloneDebug[] = R"reST(The ``standalone_debug`` attribute causes debug info to be emitted for a record
7914type regardless of the debug info optimizations that are enabled with
7915-fno-standalone-debug. This attribute only has an effect when debug info
7916optimizations are enabled (e.g. with -fno-standalone-debug), and is C++-only.)reST";
7917
7918static const char AttrDoc_StdCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
7919function to clear parameters off of the stack on return. This convention does
7920not support variadic calls or unprototyped functions in C, and has no effect on
7921x86_64 targets. This calling convention is used widely by the Windows API and
7922COM applications. See the documentation for `__stdcall`_ on MSDN.
7923
7924.. _`__stdcall`: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx)reST";
7925
7926static const char AttrDoc_StrictFP[] = R"reST()reST";
7927
7928static const char AttrDoc_StrictGuardStackCheck[] = R"reST(Clang supports the Microsoft style ``__declspec((strict_gs_check))`` attribute
7929which upgrades the stack protector check from ``-fstack-protector`` to
7930``-fstack-protector-strong``.
7931
7932For example, it upgrades the stack protector for the function ``foo`` to
7933``-fstack-protector-strong`` but function ``bar`` will still be built with the
7934stack protector with the ``-fstack-protector`` option.
7935
7936.. code-block:: c
7937
7938 __declspec((strict_gs_check))
7939 int foo(int x); // stack protection will be upgraded for foo.
7940
7941 int bar(int y); // bar can be built with the standard stack protector checks.)reST";
7942
7943static const char AttrDoc_Suppress[] = R"reST(The ``suppress`` attribute suppresses unwanted warnings coming from static
7944analysis tools such as the Clang Static Analyzer. The tool will not report
7945any issues in source code annotated with the attribute.
7946
7947The attribute cannot be used to suppress traditional Clang warnings, because
7948many such warnings are emitted before the attribute is fully parsed.
7949Consider using ``#pragma clang diagnostic`` to control such diagnostics,
7950as described in `Controlling Diagnostics via Pragmas
7951<https://clang.llvm.org/docs/UsersManual.html#controlling-diagnostics-via-pragmas>`_.
7952
7953The ``suppress`` attribute can be placed on an individual statement in order to
7954suppress warnings about undesirable behavior occurring at that statement:
7955
7956.. code-block:: c++
7957
7958 int foo() {
7959 int *x = nullptr;
7960 ...
7961 [[clang::suppress]]
7962 return *x; // null pointer dereference warning suppressed here
7963 }
7964
7965Putting the attribute on a compound statement suppresses all warnings in scope:
7966
7967.. code-block:: c++
7968
7969 int foo() {
7970 [[clang::suppress]] {
7971 int *x = nullptr;
7972 ...
7973 return *x; // warnings suppressed in the entire scope
7974 }
7975 }
7976
7977The attribute can also be placed on entire declarations of functions, classes,
7978variables, member variables, and so on, to suppress warnings related
7979to the declarations themselves. When used this way, the attribute additionally
7980suppresses all warnings in the lexical scope of the declaration:
7981
7982.. code-block:: c++
7983
7984 class [[clang::suppress]] C {
7985 int foo() {
7986 int *x = nullptr;
7987 ...
7988 return *x; // warnings suppressed in the entire class scope
7989 }
7990
7991 int bar();
7992 };
7993
7994 int C::bar() {
7995 int *x = nullptr;
7996 ...
7997 return *x; // warning NOT suppressed! - not lexically nested in 'class C{}'
7998 }
7999
8000Some static analysis warnings are accompanied by one or more notes, and the
8001line of code against which the warning is emitted isn't necessarily the best
8002for suppression purposes. In such cases the tools are allowed to implement
8003additional ways to suppress specific warnings based on the attribute attached
8004to a note location.
8005
8006For example, the Clang Static Analyzer suppresses memory leak warnings when
8007the suppression attribute is placed at the allocation site (highlited by
8008a "note: memory is allocated"), which may be different from the line of code
8009at which the program "loses track" of the pointer (where the warning
8010is ultimately emitted):
8011
8012.. code-block:: c
8013
8014 int bar1(bool coin_flip) {
8015 __attribute__((suppress))
8016 int *result = (int *)malloc(sizeof(int));
8017 if (coin_flip)
8018 return 1; // warning about this leak path is suppressed
8019
8020 return *result; // warning about this leak path is also suppressed
8021 }
8022
8023 int bar2(bool coin_flip) {
8024 int *result = (int *)malloc(sizeof(int));
8025 if (coin_flip)
8026 return 1; // leak warning on this path NOT suppressed
8027
8028 __attribute__((suppress))
8029 return *result; // leak warning is suppressed only on this path
8030 }
8031
8032
8033When written as ``[[gsl::suppress]]``, this attribute suppresses specific
8034clang-tidy diagnostics for rules of the `C++ Core Guidelines`_ in a portable
8035way. The attribute can be attached to declarations, statements, and at
8036namespace scope.
8037
8038.. code-block:: c++
8039
8040 [[gsl::suppress("Rh-public")]]
8041 void f_() {
8042 int *p;
8043 [[gsl::suppress("type")]] {
8044 p = reinterpret_cast<int*>(7);
8045 }
8046 }
8047 namespace N {
8048 [[clang::suppress("type", "bounds")]];
8049 ...
8050 }
8051
8052.. _`C++ Core Guidelines`: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement)reST";
8053
8054static const char AttrDoc_SwiftAsync[] = R"reST(The ``swift_async`` attribute specifies if and how a particular function or
8055Objective-C method is imported into a swift async method. For instance:
8056
8057.. code-block:: objc
8058
8059 @interface MyClass : NSObject
8060 -(void)notActuallyAsync:(int)p1 withCompletionHandler:(void (^)())handler
8061 __attribute__((swift_async(none)));
8062
8063 -(void)actuallyAsync:(int)p1 callThisAsync:(void (^)())fun
8064 __attribute__((swift_async(swift_private, 1)));
8065 @end
8066
8067Here, ``notActuallyAsync:withCompletionHandler`` would have been imported as
8068``async`` (because it's last parameter's selector piece is
8069``withCompletionHandler``) if not for the ``swift_async(none)`` attribute.
8070Conversely, ``actuallyAsync:callThisAsync`` wouldn't have been imported as
8071``async`` if not for the ``swift_async`` attribute because it doesn't match the
8072naming convention.
8073
8074When using ``swift_async`` to enable importing, the first argument to the
8075attribute is either ``swift_private`` or ``not_swift_private`` to indicate
8076whether the function/method is private to the current framework, and the second
8077argument is the index of the completion handler parameter.)reST";
8078
8079static const char AttrDoc_SwiftAsyncCall[] = R"reST(The ``swiftasynccall`` attribute indicates that a function is
8080compatible with the low-level conventions of Swift async functions,
8081provided it declares the right formal arguments.
8082
8083In most respects, this is similar to the ``swiftcall`` attribute, except for
8084the following:
8085
8086- A parameter may be marked ``swift_async_context``, ``swift_context``
8087 or ``swift_indirect_result`` (with the same restrictions on parameter
8088 ordering as ``swiftcall``) but the parameter attribute
8089 ``swift_error_result`` is not permitted.
8090
8091- A ``swiftasynccall`` function must have return type ``void``.
8092
8093- Within a ``swiftasynccall`` function, a call to a ``swiftasynccall``
8094 function that is the immediate operand of a ``return`` statement is
8095 guaranteed to be performed as a tail call. This syntax is allowed even
8096 in C as an extension (a call to a void-returning function cannot be a
8097 return operand in standard C). If something in the calling function would
8098 semantically be performed after a guaranteed tail call, such as the
8099 non-trivial destruction of a local variable or temporary,
8100 then the program is ill-formed.
8101
8102Query for this attribute with ``__has_attribute(swiftasynccall)``. Query if
8103the target supports the calling convention with
8104``__has_extension(swiftasynccc)``.)reST";
8105
8106static const char AttrDoc_SwiftAsyncContext[] = R"reST(The ``swift_async_context`` attribute marks a parameter of a ``swiftasynccall``
8107function as having the special asynchronous context-parameter ABI treatment.
8108
8109If the function is not ``swiftasynccall``, this attribute only generates
8110extended frame information.
8111
8112A context parameter must have pointer or reference type.)reST";
8113
8114static const char AttrDoc_SwiftAsyncError[] = R"reST(The ``swift_async_error`` attribute specifies how an error state will be
8115represented in a swift async method. It's a bit analogous to the ``swift_error``
8116attribute for the generated async method. The ``swift_async_error`` attribute
8117can indicate a variety of different ways of representing an error.
8118
8119- ``__attribute__((swift_async_error(zero_argument, N)))``, specifies that the
8120 async method is considered to have failed if the Nth argument to the
8121 completion handler is zero.
8122
8123- ``__attribute__((swift_async_error(nonzero_argument, N)))``, specifies that
8124 the async method is considered to have failed if the Nth argument to the
8125 completion handler is non-zero.
8126
8127- ``__attribute__((swift_async_error(nonnull_error)))``, specifies that the
8128 async method is considered to have failed if the ``NSError *`` argument to the
8129 completion handler is non-null.
8130
8131- ``__attribute__((swift_async_error(none)))``, specifies that the async method
8132 cannot fail.
8133
8134
8135For instance:
8136
8137.. code-block:: objc
8138
8139 @interface MyClass : NSObject
8140 -(void)asyncMethod:(void (^)(char, int, float))handler
8141 __attribute__((swift_async(swift_private, 1)))
8142 __attribute__((swift_async_error(zero_argument, 2)));
8143 @end
8144
8145Here, the ``swift_async`` attribute specifies that ``handler`` is the completion
8146handler for this method, and the ``swift_async_error`` attribute specifies that
8147the ``int`` parameter is the one that represents the error.)reST";
8148
8149static const char AttrDoc_SwiftAsyncName[] = R"reST(The ``swift_async_name`` attribute provides the name of the ``async`` overload for
8150the given declaration in Swift. If this attribute is absent, the name is
8151transformed according to the algorithm built into the Swift compiler.
8152
8153The argument is a string literal that contains the Swift name of the function or
8154method. The name may be a compound Swift name. The function or method with such
8155an attribute must have more than zero parameters, as its last parameter is
8156assumed to be a callback that's eliminated in the Swift ``async`` name.
8157
8158 .. code-block:: objc
8159
8160 @interface URL
8161 + (void) loadContentsFrom:(URL *)url callback:(void (^)(NSData *))data __attribute__((__swift_async_name__("URL.loadContentsFrom(_:)")))
8162 @end)reST";
8163
8164static const char AttrDoc_SwiftAttr[] = R"reST(The ``swift_attr`` provides a Swift-specific annotation for the declaration
8165or type to which the attribute appertains to. It can be used on any declaration
8166or type in Clang. This kind of annotation is ignored by Clang as it doesn't have any
8167semantic meaning in languages supported by Clang. The Swift compiler can
8168interpret these annotations according to its own rules when importing C or
8169Objective-C declarations.)reST";
8170
8171static const char AttrDoc_SwiftBridge[] = R"reST(The ``swift_bridge`` attribute indicates that the declaration to which the
8172attribute appertains is bridged to the named Swift type.
8173
8174 .. code-block:: objc
8175
8176 __attribute__((__objc_root__))
8177 @interface Base
8178 - (instancetype)init;
8179 @end
8180
8181 __attribute__((__swift_bridge__("BridgedI")))
8182 @interface I : Base
8183 @end
8184
8185In this example, the Objective-C interface ``I`` will be made available to Swift
8186with the name ``BridgedI``. It would be possible for the compiler to refer to
8187``I`` still in order to bridge the type back to Objective-C.)reST";
8188
8189static const char AttrDoc_SwiftBridgedTypedef[] = R"reST(The ``swift_bridged_typedef`` attribute indicates that when the typedef to which
8190the attribute appertains is imported into Swift, it should refer to the bridged
8191Swift type (e.g. Swift's ``String``) rather than the Objective-C type as written
8192(e.g. ``NSString``).
8193
8194 .. code-block:: objc
8195
8196 @interface NSString;
8197 typedef NSString *AliasedString __attribute__((__swift_bridged_typedef__));
8198
8199 extern void acceptsAliasedString(AliasedString _Nonnull parameter);
8200
8201In this case, the function ``acceptsAliasedString`` will be imported into Swift
8202as a function which accepts a ``String`` type parameter.)reST";
8203
8204static const char AttrDoc_SwiftCall[] = R"reST(The ``swiftcall`` attribute indicates that a function should be called
8205using the Swift calling convention for a function or function pointer.
8206
8207The lowering for the Swift calling convention, as described by the Swift
8208ABI documentation, occurs in multiple phases. The first, "high-level"
8209phase breaks down the formal parameters and results into innately direct
8210and indirect components, adds implicit parameters for the generic
8211signature, and assigns the context and error ABI treatments to parameters
8212where applicable. The second phase breaks down the direct parameters
8213and results from the first phase and assigns them to registers or the
8214stack. The ``swiftcall`` convention only handles this second phase of
8215lowering; the C function type must accurately reflect the results
8216of the first phase, as follows:
8217
8218- Results classified as indirect by high-level lowering should be
8219 represented as parameters with the ``swift_indirect_result`` attribute.
8220
8221- Results classified as direct by high-level lowering should be represented
8222 as follows:
8223
8224 - First, remove any empty direct results.
8225
8226 - If there are no direct results, the C result type should be ``void``.
8227
8228 - If there is one direct result, the C result type should be a type with
8229 the exact layout of that result type.
8230
8231 - If there are a multiple direct results, the C result type should be
8232 a struct type with the exact layout of a tuple of those results.
8233
8234- Parameters classified as indirect by high-level lowering should be
8235 represented as parameters of pointer type.
8236
8237- Parameters classified as direct by high-level lowering should be
8238 omitted if they are empty types; otherwise, they should be represented
8239 as a parameter type with a layout exactly matching the layout of the
8240 Swift parameter type.
8241
8242- The context parameter, if present, should be represented as a trailing
8243 parameter with the ``swift_context`` attribute.
8244
8245- The error result parameter, if present, should be represented as a
8246 trailing parameter (always following a context parameter) with the
8247 ``swift_error_result`` attribute.
8248
8249``swiftcall`` does not support variadic arguments or unprototyped functions.
8250
8251The parameter ABI treatment attributes are aspects of the function type.
8252A function type which applies an ABI treatment attribute to a
8253parameter is a different type from an otherwise-identical function type
8254that does not. A single parameter may not have multiple ABI treatment
8255attributes.
8256
8257Support for this feature is target-dependent, although it should be
8258supported on every target that Swift supports. Query for this attribute
8259with ``__has_attribute(swiftcall)``. Query if the target supports the
8260calling convention with ``__has_extension(swiftcc)``. This implies
8261support for the ``swift_context``, ``swift_error_result``, and
8262``swift_indirect_result`` attributes.)reST";
8263
8264static const char AttrDoc_SwiftContext[] = R"reST(The ``swift_context`` attribute marks a parameter of a ``swiftcall``
8265or ``swiftasynccall`` function as having the special context-parameter
8266ABI treatment.
8267
8268This treatment generally passes the context value in a special register
8269which is normally callee-preserved.
8270
8271A ``swift_context`` parameter must either be the last parameter or must be
8272followed by a ``swift_error_result`` parameter (which itself must always be
8273the last parameter).
8274
8275A context parameter must have pointer or reference type.)reST";
8276
8277static const char AttrDoc_SwiftError[] = R"reST(The ``swift_error`` attribute controls whether a particular function (or
8278Objective-C method) is imported into Swift as a throwing function, and if so,
8279which dynamic convention it uses.
8280
8281All of these conventions except ``none`` require the function to have an error
8282parameter. Currently, the error parameter is always the last parameter of type
8283``NSError**`` or ``CFErrorRef*``. Swift will remove the error parameter from
8284the imported API. When calling the API, Swift will always pass a valid address
8285initialized to a null pointer.
8286
8287* ``swift_error(none)`` means that the function should not be imported as
8288 throwing. The error parameter and result type will be imported normally.
8289
8290* ``swift_error(null_result)`` means that calls to the function should be
8291 considered to have thrown if they return a null value. The return type must be
8292 a pointer type, and it will be imported into Swift with a non-optional type.
8293 This is the default error convention for Objective-C methods that return
8294 pointers.
8295
8296* ``swift_error(zero_result)`` means that calls to the function should be
8297 considered to have thrown if they return a zero result. The return type must be
8298 an integral type. If the return type would have been imported as ``Bool``, it
8299 is instead imported as ``Void``. This is the default error convention for
8300 Objective-C methods that return a type that would be imported as ``Bool``.
8301
8302* ``swift_error(nonzero_result)`` means that calls to the function should be
8303 considered to have thrown if they return a non-zero result. The return type must
8304 be an integral type. If the return type would have been imported as ``Bool``,
8305 it is instead imported as ``Void``.
8306
8307* ``swift_error(nonnull_error)`` means that calls to the function should be
8308 considered to have thrown if they leave a non-null error in the error parameter.
8309 The return type is left unmodified.)reST";
8310
8311static const char AttrDoc_SwiftErrorResult[] = R"reST(The ``swift_error_result`` attribute marks a parameter of a ``swiftcall``
8312function as having the special error-result ABI treatment.
8313
8314This treatment generally passes the underlying error value in and out of
8315the function through a special register which is normally callee-preserved.
8316This is modeled in C by pretending that the register is addressable memory:
8317
8318- The caller appears to pass the address of a variable of pointer type.
8319 The current value of this variable is copied into the register before
8320 the call; if the call returns normally, the value is copied back into the
8321 variable.
8322
8323- The callee appears to receive the address of a variable. This address
8324 is actually a hidden location in its own stack, initialized with the
8325 value of the register upon entry. When the function returns normally,
8326 the value in that hidden location is written back to the register.
8327
8328A ``swift_error_result`` parameter must be the last parameter, and it must be
8329preceded by a ``swift_context`` parameter.
8330
8331A ``swift_error_result`` parameter must have type ``T**`` or ``T*&`` for some
8332type T. Note that no qualifiers are permitted on the intermediate level.
8333
8334It is undefined behavior if the caller does not pass a pointer or
8335reference to a valid object.
8336
8337The standard convention is that the error value itself (that is, the
8338value stored in the apparent argument) will be null upon function entry,
8339but this is not enforced by the ABI.)reST";
8340
8341static const char AttrDoc_SwiftImportAsNonGeneric[] = R"reST()reST";
8342
8343static const char AttrDoc_SwiftImportPropertyAsAccessors[] = R"reST()reST";
8344
8345static const char AttrDoc_SwiftIndirectResult[] = R"reST(The ``swift_indirect_result`` attribute marks a parameter of a ``swiftcall``
8346or ``swiftasynccall`` function as having the special indirect-result ABI
8347treatment.
8348
8349This treatment gives the parameter the target's normal indirect-result
8350ABI treatment, which may involve passing it differently from an ordinary
8351parameter. However, only the first indirect result will receive this
8352treatment. Furthermore, low-level lowering may decide that a direct result
8353must be returned indirectly; if so, this will take priority over the
8354``swift_indirect_result`` parameters.
8355
8356A ``swift_indirect_result`` parameter must either be the first parameter or
8357follow another ``swift_indirect_result`` parameter.
8358
8359A ``swift_indirect_result`` parameter must have type ``T*`` or ``T&`` for
8360some object type ``T``. If ``T`` is a complete type at the point of
8361definition of a function, it is undefined behavior if the argument
8362value does not point to storage of adequate size and alignment for a
8363value of type ``T``.
8364
8365Making indirect results explicit in the signature allows C functions to
8366directly construct objects into them without relying on language
8367optimizations like C++'s named return value optimization (NRVO).)reST";
8368
8369static const char AttrDoc_SwiftName[] = R"reST(The ``swift_name`` attribute provides the name of the declaration in Swift. If
8370this attribute is absent, the name is transformed according to the algorithm
8371built into the Swift compiler.
8372
8373The argument is a string literal that contains the Swift name of the function,
8374variable, or type. When renaming a function, the name may be a compound Swift
8375name. For a type, enum constant, property, or variable declaration, the name
8376must be a simple or qualified identifier.
8377
8378 .. code-block:: objc
8379
8380 @interface URL
8381 - (void) initWithString:(NSString *)s __attribute__((__swift_name__("URL.init(_:)")))
8382 @end
8383
8384 void __attribute__((__swift_name__("squareRoot()"))) sqrt(double v) {
8385 })reST";
8386
8387static const char AttrDoc_SwiftNewType[] = R"reST(The ``swift_newtype`` attribute indicates that the typedef to which the
8388attribute appertains is imported as a new Swift type of the typedef's name.
8389Previously, the attribute was spelt ``swift_wrapper``. While the behaviour of
8390the attribute is identical with either spelling, ``swift_wrapper`` is
8391deprecated, only exists for compatibility purposes, and should not be used in
8392new code.
8393
8394* ``swift_newtype(struct)`` means that a Swift struct will be created for this
8395 typedef.
8396
8397* ``swift_newtype(enum)`` means that a Swift enum will be created for this
8398 typedef.
8399
8400 .. code-block:: c
8401
8402 // Import UIFontTextStyle as an enum type, with enumerated values being
8403 // constants.
8404 typedef NSString * UIFontTextStyle __attribute__((__swift_newtype__(enum)));
8405
8406 // Import UIFontDescriptorFeatureKey as a structure type, with enumerated
8407 // values being members of the type structure.
8408 typedef NSString * UIFontDescriptorFeatureKey __attribute__((__swift_newtype__(struct)));)reST";
8409
8410static const char AttrDoc_SwiftNullability[] = R"reST()reST";
8411
8412static const char AttrDoc_SwiftObjCMembers[] = R"reST(This attribute indicates that Swift subclasses and members of Swift extensions
8413of this class will be implicitly marked with the ``@objcMembers`` Swift
8414attribute, exposing them back to Objective-C.)reST";
8415
8416static const char AttrDoc_SwiftPrivate[] = R"reST(Declarations marked with the ``swift_private`` attribute are hidden from the
8417framework client but are still made available for use within the framework or
8418Swift SDK overlay.
8419
8420The purpose of this attribute is to permit a more idomatic implementation of
8421declarations in Swift while hiding the non-idiomatic one.)reST";
8422
8423static const char AttrDoc_SwiftType[] = R"reST()reST";
8424
8425static const char AttrDoc_SwiftVersionedAddition[] = R"reST()reST";
8426
8427static const char AttrDoc_SwiftVersionedRemoval[] = R"reST()reST";
8428
8429static const char AttrDoc_SysVABI[] = R"reST(On Windows x86_64 targets, this attribute changes the calling convention of a
8430function to match the default convention used on Sys V targets such as Linux,
8431Mac, and BSD. This attribute has no effect on other targets.)reST";
8432
8433static const char AttrDoc_TLSModel[] = R"reST(The ``tls_model`` attribute allows you to specify which thread-local storage
8434model to use. It accepts the following strings:
8435
8436* global-dynamic
8437* local-dynamic
8438* initial-exec
8439* local-exec
8440
8441TLS models are mutually exclusive.)reST";
8442
8443static const char AttrDoc_Target[] = R"reST(Clang supports the GNU style ``__attribute__((target("OPTIONS")))`` attribute.
8444This attribute may be attached to a function definition and instructs
8445the backend to use different code generation options than were passed on the
8446command line.
8447
8448The current set of options correspond to the existing "subtarget features" for
8449the target with or without a "-mno-" in front corresponding to the absence
8450of the feature, as well as ``arch="CPU"`` which will change the default "CPU"
8451for the function.
8452
8453For X86, the attribute also allows ``tune="CPU"`` to optimize the generated
8454code for the given CPU without changing the available instructions.
8455
8456For AArch64, ``arch="Arch"`` will set the architecture, similar to the -march
8457command line options. ``cpu="CPU"`` can be used to select a specific cpu,
8458as per the ``-mcpu`` option, similarly for ``tune=``. The attribute also allows the
8459"branch-protection=<args>" option, where the permissible arguments and their
8460effect on code generation are the same as for the command-line option
8461``-mbranch-protection``.
8462
8463Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
8464"avx", "xop" and largely correspond to the machine specific options handled by
8465the front end.
8466
8467Note that this attribute does not apply transitively to nested functions such
8468as blocks or C++ lambdas.
8469
8470Additionally, this attribute supports function multiversioning for ELF based
8471x86/x86-64 targets, which can be used to create multiple implementations of the
8472same function that will be resolved at runtime based on the priority of their
8473``target`` attribute strings. A function is considered a multiversioned function
8474if either two declarations of the function have different ``target`` attribute
8475strings, or if it has a ``target`` attribute string of ``default``. For
8476example:
8477
8478 .. code-block:: c++
8479
8480 __attribute__((target("arch=atom")))
8481 void foo() {} // will be called on 'atom' processors.
8482 __attribute__((target("default")))
8483 void foo() {} // will be called on any other processors.
8484
8485All multiversioned functions must contain a ``default`` (fallback)
8486implementation, otherwise usages of the function are considered invalid.
8487Additionally, a function may not become multiversioned after its first use.)reST";
8488
8489static const char AttrDoc_TargetClones[] = R"reST(Clang supports the ``target_clones("OPTIONS")`` attribute. This attribute may be
8490attached to a function declaration and causes function multiversioning, where
8491multiple versions of the function will be emitted with different code
8492generation options. Additionally, these versions will be resolved at runtime
8493based on the priority of their attribute options. All ``target_clone`` functions
8494are considered multiversioned functions.
8495
8496For AArch64 target:
8497The attribute contains comma-separated strings of target features joined by "+"
8498sign. For example:
8499
8500 .. code-block:: c++
8501
8502 __attribute__((target_clones("sha2+memtag", "fcma+sve2-pmull128")))
8503 void foo() {}
8504
8505For every multiversioned function a ``default`` (fallback) implementation
8506always generated if not specified directly.
8507
8508For x86/x86-64 targets:
8509All multiversioned functions must contain a ``default`` (fallback)
8510implementation, otherwise usages of the function are considered invalid.
8511Additionally, a function may not become multiversioned after its first use.
8512
8513The options to ``target_clones`` can either be a target-specific architecture
8514(specified as ``arch=CPU``), or one of a list of subtarget features.
8515
8516Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
8517"avx", "xop" and largely correspond to the machine specific options handled by
8518the front end.
8519
8520The versions can either be listed as a comma-separated sequence of string
8521literals or as a single string literal containing a comma-separated list of
8522versions. For compatibility with GCC, the two formats can be mixed. For
8523example, the following will emit 4 versions of the function:
8524
8525 .. code-block:: c++
8526
8527 __attribute__((target_clones("arch=atom,avx2","arch=ivybridge","default")))
8528 void foo() {}
8529
8530For targets that support the GNU indirect function (IFUNC) feature, dispatch
8531is performed by emitting an indirect function that is resolved to the appropriate
8532target clone at load time. The indirect function is given the name the
8533multiversioned function would have if it had been declared without the attribute.
8534For backward compatibility with earlier Clang releases, a function alias with an
8535``.ifunc`` suffix is also emitted. The ``.ifunc`` suffixed symbol is a deprecated
8536feature and support for it may be removed in the future.
8537
8538For PowerPC targets, ``target_clones`` is supported on AIX only. Only CPU
8539(specified as ``cpu=CPU``) and ``default`` options are allowed. IFUNC is supported
8540on AIX in Clang, so dispatch is implemented similar to other targets using IFUNC.
8541An FMV function that is only declared in a translation unit is treated as a
8542non-FMV. The resolver and the function clones are given internal linkage.)reST";
8543
8544static const char AttrDoc_TargetVersion[] = R"reST(For AArch64 target clang supports function multiversioning by
8545``__attribute__((target_version("OPTIONS")))`` attribute. When applied to a
8546function it instructs compiler to emit multiple function versions based on
8547``target_version`` attribute strings, which resolved at runtime depend on their
8548priority and target features availability. One of the versions is always
8549( implicitly or explicitly ) the ``default`` (fallback). Attribute strings can
8550contain dependent features names joined by the "+" sign.
8551
8552For targets that support the GNU indirect function (IFUNC) feature, dispatch
8553is performed by emitting an indirect function that is resolved to the appropriate
8554target clone at load time. The indirect function is given the name the
8555multiversioned function would have if it had been declared without the attribute.
8556For backward compatibility with earlier Clang releases, a function alias with an
8557``.ifunc`` suffix is also emitted. The ``.ifunc`` suffixed symbol is a deprecated
8558feature and support for it may be removed in the future.)reST";
8559
8560static const char AttrDoc_TestTypestate[] = R"reST(Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method
8561returns true if the object is in the specified state..)reST";
8562
8563static const char AttrDoc_ThisCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
8564function to use ECX for the first parameter (typically the implicit ``this``
8565parameter of C++ methods) and clear parameters off of the stack on return. This
8566convention does not support variadic calls or unprototyped functions in C, and
8567has no effect on x86_64 targets. See the documentation for `__thiscall`_ on
8568MSDN.
8569
8570.. _`__thiscall`: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx)reST";
8571
8572static const char AttrDoc_Thread[] = R"reST(The ``__declspec(thread)`` attribute declares a variable with thread local
8573storage. It is available under the ``-fms-extensions`` flag for MSVC
8574compatibility. See the documentation for `__declspec(thread)`_ on MSDN.
8575
8576.. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx
8577
8578In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the
8579GNU ``__thread`` keyword. The variable must not have a destructor and must have
8580a constant initializer, if any. The attribute only applies to variables
8581declared with static storage duration, such as globals, class static data
8582members, and static locals.)reST";
8583
8584static const char AttrDoc_TransparentUnion[] = R"reST(This attribute can be applied to a union to change the behavior of calls to
8585functions that have an argument with a transparent union type. The compiler
8586behavior is changed in the following manner:
8587
8588- A value whose type is any member of the transparent union can be passed as an
8589 argument without the need to cast that value.
8590
8591- The argument is passed to the function using the calling convention of the
8592 first member of the transparent union. Consequently, all the members of the
8593 transparent union should have the same calling convention as its first member.
8594
8595Transparent unions are not supported in C++.)reST";
8596
8597static const char AttrDoc_TrivialABI[] = R"reST(The ``trivial_abi`` attribute can be applied to a C++ class, struct, or union.
8598It instructs the compiler to pass and return the type using the C ABI for the
8599underlying type when the type would otherwise be considered non-trivial for the
8600purpose of calls.
8601A class annotated with ``trivial_abi`` can have non-trivial destructors or
8602copy/move constructors without automatically becoming non-trivial for the
8603purposes of calls. For example:
8604
8605 .. code-block:: c++
8606
8607 // A is trivial for the purposes of calls because ``trivial_abi`` makes the
8608 // user-provided special functions trivial.
8609 struct __attribute__((trivial_abi)) A {
8610 ~A();
8611 A(const A &);
8612 A(A &&);
8613 int x;
8614 };
8615
8616 // B's destructor and copy/move constructor are considered trivial for the
8617 // purpose of calls because A is trivial.
8618 struct B {
8619 A a;
8620 };
8621
8622If a type is trivial for the purposes of calls, has a non-trivial destructor,
8623and is passed as an argument by value, the convention is that the callee will
8624destroy the object before returning. The lifetime of the copy of the parameter
8625in the caller ends without a destructor call when the call begins.
8626
8627If a type is trivial for the purpose of calls, it is assumed to be trivially
8628relocatable for the purpose of ``__is_trivially_relocatable`` and
8629``__builtin_is_cpp_trivially_relocatable``.
8630When a type marked with ``[[trivial_abi]]`` is used as a function argument,
8631the compiler may omit the call to the copy constructor.
8632Thus, side effects of the copy constructor are potentially not performed.
8633For example, objects that contain pointers to themselves or otherwise depend
8634on their address (or the address or their subobjects) should not be declared
8635``[[trivial_abi]]``.
8636
8637Attribute ``trivial_abi`` has no effect in the following cases:
8638
8639- The class directly declares a virtual base or virtual methods.
8640- Copy constructors and move constructors of the class are all deleted.
8641- The class has a base class that is non-trivial for the purposes of calls.
8642- The class has a non-static data member whose type is non-trivial for the
8643 purposes of calls, which includes:
8644
8645 - classes that are non-trivial for the purposes of calls
8646 - __weak-qualified types in Objective-C++
8647 - arrays of any of the above)reST";
8648
8649static const char AttrDoc_TryAcquireCapability[] = R"reST(Marks a function that attempts to acquire a capability. This function may fail to
8650actually acquire the capability; they accept a Boolean value determining
8651whether acquiring the capability means success (true), or failing to acquire
8652the capability means success (false).)reST";
8653
8654static const char AttrDoc_TypeNonNull[] = R"reST(The ``_Nonnull`` nullability qualifier indicates that null is not a meaningful
8655value for a value of the ``_Nonnull`` pointer type. For example, given a
8656declaration such as:
8657
8658 .. code-block:: c
8659
8660 int fetch(int * _Nonnull ptr);
8661
8662a caller of ``fetch`` should not provide a null value, and the compiler will
8663produce a warning if it sees a literal null value passed to ``fetch``. Note
8664that, unlike the declaration attribute ``nonnull``, the presence of
8665``_Nonnull`` does not imply that passing null is undefined behavior: ``fetch``
8666is free to consider null undefined behavior or (perhaps for
8667backward-compatibility reasons) defensively handle null.)reST";
8668
8669static const char AttrDoc_TypeNullUnspecified[] = R"reST(The ``_Null_unspecified`` nullability qualifier indicates that neither the
8670``_Nonnull`` nor ``_Nullable`` qualifiers make sense for a particular pointer
8671type. It is used primarily to indicate that the role of null with specific
8672pointers in a nullability-annotated header is unclear, e.g., due to
8673overly-complex implementations or historical factors with a long-lived API.)reST";
8674
8675static const char AttrDoc_TypeNullable[] = R"reST(The ``_Nullable`` nullability qualifier indicates that a value of the
8676``_Nullable`` pointer type can be null. For example, given:
8677
8678 .. code-block:: c
8679
8680 int fetch_or_zero(int * _Nullable ptr);
8681
8682a caller of ``fetch_or_zero`` can provide null.
8683
8684The ``_Nullable`` attribute on classes indicates that the given class can
8685represent null values, and so the ``_Nullable``, ``_Nonnull`` etc qualifiers
8686make sense for this type. For example:
8687
8688 .. code-block:: c
8689
8690 class _Nullable ArenaPointer { ... };
8691
8692 ArenaPointer _Nonnull x = ...;
8693 ArenaPointer _Nullable y = nullptr;)reST";
8694
8695static const char AttrDoc_TypeNullableResult[] = R"reST(The ``_Nullable_result`` nullability qualifier means that a value of the
8696``_Nullable_result`` pointer can be ``nil``, just like ``_Nullable``. Where this
8697attribute differs from ``_Nullable`` is when it's used on a parameter to a
8698completion handler in a Swift async method. For instance, here:
8699
8700 .. code-block:: objc
8701
8702 -(void)fetchSomeDataWithID:(int)identifier
8703 completionHandler:(void (^)(Data *_Nullable_result result, NSError *error))completionHandler;
8704
8705This method asynchronously calls ``completionHandler`` when the data is
8706available, or calls it with an error. ``_Nullable_result`` indicates to the
8707Swift importer that this is the uncommon case where ``result`` can get ``nil``
8708even if no error has occurred, and will therefore import it as a Swift optional
8709type. Otherwise, if ``result`` was annotated with ``_Nullable``, the Swift
8710importer will assume that ``result`` will always be non-nil unless an error
8711occurred.)reST";
8712
8713static const char AttrDoc_TypeTagForDatatype[] = R"reST(When declaring a variable, use
8714``__attribute__((type_tag_for_datatype(kind, type)))`` to create a type tag that
8715is tied to the ``type`` argument given to the attribute.
8716
8717In the attribute prototype above:
8718 * ``kind`` is an identifier that should be used when annotating all applicable
8719 type tags.
8720 * ``type`` indicates the name of the type.
8721
8722Clang supports annotating type tags of two forms.
8723
8724 * **Type tag that is a reference to a declared identifier.**
8725 Use ``__attribute__((type_tag_for_datatype(kind, type)))`` when declaring that
8726 identifier:
8727
8728 .. code-block:: c++
8729
8730 typedef int MPI_Datatype;
8731 extern struct mpi_datatype mpi_datatype_int
8732 __attribute__(( type_tag_for_datatype(mpi,int) ));
8733 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
8734 // &mpi_datatype_int is a type tag. It is tied to type "int".
8735
8736 * **Type tag that is an integral literal.**
8737 Declare a ``static const`` variable with an initializer value and attach
8738 ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration:
8739
8740 .. code-block:: c++
8741
8742 typedef int MPI_Datatype;
8743 static const MPI_Datatype mpi_datatype_int
8744 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42;
8745 #define MPI_INT ((MPI_Datatype) 42)
8746 // The number 42 is a type tag. It is tied to type "int".
8747
8748
8749The ``type_tag_for_datatype`` attribute also accepts an optional third argument
8750that determines how the type of the function argument specified by either
8751``arg_idx`` or ``ptr_idx`` is compared against the type associated with the type
8752tag. (Recall that for the ``argument_with_type_tag`` attribute, the type of the
8753function argument specified by ``arg_idx`` is compared against the type
8754associated with the type tag. Also recall that for the ``pointer_with_type_tag``
8755attribute, the pointee type of the function argument specified by ``ptr_idx`` is
8756compared against the type associated with the type tag.) There are two supported
8757values for this optional third argument:
8758
8759 * ``layout_compatible`` will cause types to be compared according to
8760 layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the
8761 layout-compatibility rules for two standard-layout struct types and for two
8762 standard-layout union types). This is useful when creating a type tag
8763 associated with a struct or union type. For example:
8764
8765 .. code-block:: c++
8766
8767 /* In mpi.h */
8768 typedef int MPI_Datatype;
8769 struct internal_mpi_double_int { double d; int i; };
8770 extern struct mpi_datatype mpi_datatype_double_int
8771 __attribute__(( type_tag_for_datatype(mpi,
8772 struct internal_mpi_double_int, layout_compatible) ));
8773
8774 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
8775
8776 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
8777 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
8778
8779 /* In user code */
8780 struct my_pair { double a; int b; };
8781 struct my_pair *buffer;
8782 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the
8783 // layout of my_pair is
8784 // compatible with that of
8785 // internal_mpi_double_int
8786
8787 struct my_int_pair { int a; int b; }
8788 struct my_int_pair *buffer2;
8789 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the
8790 // layout of my_int_pair
8791 // does not match that of
8792 // internal_mpi_double_int
8793
8794 * ``must_be_null`` specifies that the function argument specified by either
8795 ``arg_idx`` (for the ``argument_with_type_tag`` attribute) or ``ptr_idx`` (for
8796 the ``pointer_with_type_tag`` attribute) should be a null pointer constant.
8797 The second argument to the ``type_tag_for_datatype`` attribute is ignored. For
8798 example:
8799
8800 .. code-block:: c++
8801
8802 /* In mpi.h */
8803 typedef int MPI_Datatype;
8804 extern struct mpi_datatype mpi_datatype_null
8805 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
8806
8807 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
8808 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
8809 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
8810
8811 /* In user code */
8812 struct my_pair { double a; int b; };
8813 struct my_pair *buffer;
8814 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
8815 // was specified but buffer
8816 // is not a null pointer)reST";
8817
8818static const char AttrDoc_TypeVisibility[] = R"reST(The ``type_visibility`` attribute allows the visibility of a type and its vague
8819linkage objects (vtable, typeinfo, typeinfo name) to be controlled separately from
8820the visibility of functions and data members of the type.
8821
8822For example, this can be used to give default visibility to the typeinfo and the vtable
8823of a type while still keeping hidden visibility on its member functions and static data
8824members.
8825
8826This attribute can only be applied to types and namespaces.
8827
8828If both ``visibility`` and ``type_visibility`` are applied to a type or a namespace, the
8829visibility specified with the ``type_visibility`` attribute overrides the visibility
8830provided with the regular ``visibility`` attribute.)reST";
8831
8832static const char AttrDoc_UPtr[] = R"reST(The ``__uptr`` qualifier specifies that a 32-bit pointer should be zero
8833extended when converted to a 64-bit pointer.)reST";
8834
8835static const char AttrDoc_Unavailable[] = R"reST(No documentation.)reST";
8836
8837static const char AttrDoc_Uninitialized[] = R"reST(The command-line parameter ``-ftrivial-auto-var-init=*`` can be used to
8838initialize trivial automatic stack variables. By default, trivial automatic
8839stack variables are uninitialized. This attribute is used to override the
8840command-line parameter, forcing variables to remain uninitialized. It has no
8841semantic meaning in that using uninitialized values is undefined behavior,
8842it rather documents the programmer's intent.)reST";
8843
8844static const char AttrDoc_Unlikely[] = R"reST(The ``likely`` and ``unlikely`` attributes are used as compiler hints.
8845The attributes are used to aid the compiler to determine which branch is
8846likely or unlikely to be taken. This is done by marking the branch substatement
8847with one of the two attributes.
8848
8849It isn't allowed to annotate a single statement with both ``likely`` and
8850``unlikely``. Annotating the ``true`` and ``false`` branch of an ``if``
8851statement with the same likelihood attribute will result in a diagnostic and
8852the attributes are ignored on both branches.
8853
8854In a ``switch`` statement it's allowed to annotate multiple ``case`` labels
8855or the ``default`` label with the same likelihood attribute. This makes
8856* all labels without an attribute have a neutral likelihood,
8857* all labels marked ``[[likely]]`` have an equally positive likelihood, and
8858* all labels marked ``[[unlikely]]`` have an equally negative likelihood.
8859The neutral likelihood is the more likely of path execution than the negative
8860likelihood. The positive likelihood is the more likely of path of execution
8861than the neutral likelihood.
8862
8863These attributes have no effect on the generated code when using
8864PGO (Profile-Guided Optimization) or at optimization level 0.
8865
8866In Clang, the attributes will be ignored if they're not placed on
8867* the ``case`` or ``default`` label of a ``switch`` statement,
8868* or on the substatement of an ``if`` or ``else`` statement,
8869* or on the substatement of an ``for`` or ``while`` statement.
8870The C++ Standard recommends to honor them on every statement in the
8871path of execution, but that can be confusing:
8872
8873.. code-block:: c++
8874
8875 if (b) {
8876 [[unlikely]] --b; // Per the standard this is in the path of
8877 // execution, so this branch should be considered
8878 // unlikely. However, Clang ignores the attribute
8879 // here since it is not on the substatement.
8880 }
8881
8882 if (b) {
8883 --b;
8884 if(b)
8885 return;
8886 [[unlikely]] --b; // Not in the path of execution,
8887 } // the branch has no likelihood information.
8888
8889 if (b) {
8890 --b;
8891 foo(b);
8892 // Whether or not the next statement is in the path of execution depends
8893 // on the declaration of foo():
8894 // In the path of execution: void foo(int);
8895 // Not in the path of execution: [[noreturn]] void foo(int);
8896 // This means the likelihood of the branch depends on the declaration
8897 // of foo().
8898 [[unlikely]] --b;
8899 }
8900
8901
8902Below are some example usages of the likelihood attributes and their effects:
8903
8904.. code-block:: c++
8905
8906 if (b) [[likely]] { // Placement on the first statement in the branch.
8907 // The compiler will optimize to execute the code here.
8908 } else {
8909 }
8910
8911 if (b)
8912 [[unlikely]] b++; // Placement on the first statement in the branch.
8913 else {
8914 // The compiler will optimize to execute the code here.
8915 }
8916
8917 if (b) {
8918 [[unlikely]] b++; // Placement on the second statement in the branch.
8919 } // The attribute will be ignored.
8920
8921 if (b) [[likely]] {
8922 [[unlikely]] b++; // No contradiction since the second attribute
8923 } // is ignored.
8924
8925 if (b)
8926 ;
8927 else [[likely]] {
8928 // The compiler will optimize to execute the code here.
8929 }
8930
8931 if (b)
8932 ;
8933 else
8934 // The compiler will optimize to execute the next statement.
8935 [[likely]] b = f();
8936
8937 if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
8938 else [[likely]]; // and the attributes are ignored.
8939
8940 if (b)
8941 [[likely]] int i = 5; // Issues a diagnostic since the attribute
8942 // isn't allowed on a declaration.
8943
8944 switch (i) {
8945 [[likely]] case 1: // This value is likely
8946 ...
8947 break;
8948
8949 [[unlikely]] case 2: // This value is unlikely
8950 ...
8951 [[fallthrough]];
8952
8953 case 3: // No likelihood attribute
8954 ...
8955 [[likely]] break; // No effect
8956
8957 case 4: [[likely]] { // attribute on substatement has no effect
8958 ...
8959 break;
8960 }
8961
8962 [[unlikely]] default: // All other values are unlikely
8963 ...
8964 break;
8965 }
8966
8967 switch (i) {
8968 [[likely]] case 0: // This value and code path is likely
8969 ...
8970 [[fallthrough]];
8971
8972 case 1: // No likelihood attribute, code path is neutral
8973 break; // falling through has no effect on the likelihood
8974
8975 case 2: // No likelihood attribute, code path is neutral
8976 [[fallthrough]];
8977
8978 [[unlikely]] default: // This value and code path are both unlikely
8979 break;
8980 }
8981
8982 for(int i = 0; i != size; ++i) [[likely]] {
8983 ... // The loop is the likely path of execution
8984 }
8985
8986 for(const auto &E : Elements) [[likely]] {
8987 ... // The loop is the likely path of execution
8988 }
8989
8990 while(i != size) [[unlikely]] {
8991 ... // The loop is the unlikely path of execution
8992 } // The generated code will optimize to skip the loop body
8993
8994 while(true) [[unlikely]] {
8995 ... // The attribute has no effect
8996 } // Clang elides the comparison and generates an infinite
8997 // loop)reST";
8998
8999static const char AttrDoc_UnsafeBufferUsage[] = R"reST(The attribute ``[[clang::unsafe_buffer_usage]]`` should be placed on functions
9000that need to be avoided as they are prone to buffer overflows or unsafe buffer
9001struct fields. It is designed to work together with the off-by-default compiler
9002warning ``-Wunsafe-buffer-usage`` to help codebases transition away from raw pointer
9003based buffer management, in favor of safer abstractions such as C++20 ``std::span``.
9004The attribute causes ``-Wunsafe-buffer-usage`` to warn on every use of the function or
9005the field it is attached to, and it may also lead to emission of automatic fix-it
9006hints which would help the user replace the use of unsafe functions(/fields) with safe
9007alternatives, though the attribute can be used even when the fix can't be automated.
9008
9009* Attribute attached to functions: The attribute suppresses all
9010 ``-Wunsafe-buffer-usage`` warnings within the function it is attached to, as the
9011 function is now classified as unsafe. The attribute should be used carefully, as it
9012 will silence all unsafe operation warnings inside the function; including any new
9013 unsafe operations introduced in the future.
9014
9015 The attribute is warranted even if the only way a function can overflow
9016 the buffer is by violating the function's preconditions. For example, it
9017 would make sense to put the attribute on function ``foo()`` below because
9018 passing an incorrect size parameter would cause a buffer overflow:
9019
9020 .. code-block:: c++
9021
9022 [[clang::unsafe_buffer_usage]]
9023 void foo(int *buf, size_t size) {
9024 for (size_t i = 0; i < size; ++i) {
9025 buf[i] = i;
9026 }
9027 }
9028
9029 The attribute is NOT warranted when the function uses safe abstractions,
9030 assuming that these abstractions weren't misused outside the function.
9031 For example, function ``bar()`` below doesn't need the attribute,
9032 because assuming that the container ``buf`` is well-formed (has size that
9033 fits the original buffer it refers to), overflow cannot occur:
9034
9035 .. code-block:: c++
9036
9037 void bar(std::span<int> buf) {
9038 for (size_t i = 0; i < buf.size(); ++i) {
9039 buf[i] = i;
9040 }
9041 }
9042
9043 In this case function ``bar()`` enables the user to keep the buffer
9044 "containerized" in a span for as long as possible. On the other hand,
9045 Function ``foo()`` in the previous example may have internal
9046 consistency, but by accepting a raw buffer it requires the user to unwrap
9047 their span, which is undesirable according to the programming model
9048 behind ``-Wunsafe-buffer-usage``.
9049
9050 The attribute is warranted when a function accepts a raw buffer only to
9051 immediately put it into a span:
9052
9053 .. code-block:: c++
9054
9055 [[clang::unsafe_buffer_usage]]
9056 void baz(int *buf, size_t size) {
9057 std::span<int> sp{ buf, size };
9058 for (size_t i = 0; i < sp.size(); ++i) {
9059 sp[i] = i;
9060 }
9061 }
9062
9063 In this case ``baz()`` does not contain any unsafe operations, but the awkward
9064 parameter type causes the caller to unwrap the span unnecessarily.
9065 Note that regardless of the attribute, code inside ``baz()`` isn't flagged
9066 by ``-Wunsafe-buffer-usage`` as unsafe. It is definitely undesirable,
9067 but if ``baz()`` is on an API surface, there is no way to improve it
9068 to make it as safe as ``bar()`` without breaking the source and binary
9069 compatibility with existing users of the function. In such cases
9070 the proper solution would be to create a different function (possibly
9071 an overload of ``baz()``) that accepts a safe container like ``bar()``,
9072 and then use the attribute on the original ``baz()`` to help the users
9073 update their code to use the new function.
9074
9075* Attribute attached to fields: The attribute should only be attached to
9076 struct fields, if the fields can not be updated to a safe type with bounds
9077 check, such as std::span. In other words, the buffers prone to unsafe accesses
9078 should always be updated to use safe containers/views and attaching the attribute
9079 must be last resort when such an update is infeasible.
9080
9081 The attribute can be placed on individual fields or a set of them as shown below.
9082
9083 .. code-block:: c++
9084
9085 struct A {
9086 [[clang::unsafe_buffer_usage]]
9087 int *ptr1;
9088
9089 [[clang::unsafe_buffer_usage]]
9090 int *ptr2, buf[10];
9091
9092 [[clang::unsafe_buffer_usage]]
9093 size_t sz;
9094 };
9095
9096 Here, every read/write to the fields ptr1, ptr2, buf and sz will trigger a warning
9097 that the field has been explcitly marked as unsafe due to unsafe-buffer operations.)reST";
9098
9099static const char AttrDoc_Unused[] = R"reST(When passing the ``-Wunused`` flag to Clang, entities that are unused by the
9100program may be diagnosed. The ``[[maybe_unused]]`` (or
9101``__attribute__((unused))``) attribute can be used to silence such diagnostics
9102when the entity cannot be removed. For instance, a local variable may exist
9103solely for use in an ``assert()`` statement, which makes the local variable
9104unused when ``NDEBUG`` is defined.
9105
9106The attribute may be applied to the declaration of a class, a typedef, a
9107variable, a function or method, a function parameter, an enumeration, an
9108enumerator, a non-static data member, or a label.
9109
9110.. code-block:: c++
9111
9112 #include <cassert>
9113
9114 [[maybe_unused]] void f([[maybe_unused]] bool thing1,
9115 [[maybe_unused]] bool thing2) {
9116 [[maybe_unused]] bool b = thing1 && thing2;
9117 assert(b);
9118 })reST";
9119
9120static const char AttrDoc_UseHandle[] = R"reST(A function taking a handle by value might close the handle. If a function
9121parameter is annotated with ``use_handle(tag)`` it is assumed to not to change
9122the state of the handle. It is also assumed to require an open handle to work with.
9123The attribute requires a string literal argument to identify the handle being used.
9124
9125.. code-block:: c++
9126
9127 zx_status_t zx_port_wait(zx_handle_t handle [[clang::use_handle("zircon")]],
9128 zx_time_t deadline,
9129 zx_port_packet_t* packet);)reST";
9130
9131static const char AttrDoc_Used[] = R"reST(This attribute, when attached to a function or variable definition, indicates
9132that there may be references to the entity which are not apparent in the source
9133code. For example, it may be referenced from inline ``asm``, or it may be
9134found through a dynamic symbol or section lookup.
9135
9136The compiler must emit the definition even if it appears to be unused, and it
9137must not apply optimizations which depend on fully understanding how the entity
9138is used.
9139
9140Whether this attribute has any effect on the linker depends on the target and
9141the linker. Most linkers support the feature of section garbage collection
9142(``--gc-sections``), also known as "dead stripping" (``ld64 -dead_strip``) or
9143discarding unreferenced sections (``link.exe /OPT:REF``). On COFF and Mach-O
9144targets (Windows and Apple platforms), the `used` attribute prevents symbols
9145from being removed by linker section GC. On ELF targets, it has no effect on its
9146own, and the linker may remove the definition if it is not otherwise referenced.
9147This linker GC can be avoided by also adding the ``retain`` attribute. Note
9148that ``retain`` requires special support from the linker; see that attribute's
9149documentation for further information.)reST";
9150
9151static const char AttrDoc_UsingIfExists[] = R"reST(The ``using_if_exists`` attribute applies to a using-declaration. It allows
9152programmers to import a declaration that potentially does not exist, instead
9153deferring any errors to the point of use. For instance:
9154
9155.. code-block:: c++
9156
9157 namespace empty_namespace {};
9158 __attribute__((using_if_exists))
9159 using empty_namespace::does_not_exist; // no error!
9160
9161 does_not_exist x; // error: use of unresolved 'using_if_exists'
9162
9163The C++ spelling of the attribute (`[[clang::using_if_exists]]`) is also
9164supported as a clang extension, since ISO C++ doesn't support attributes in this
9165position. If the entity referred to by the using-declaration is found by name
9166lookup, the attribute has no effect. This attribute is useful for libraries
9167(primarily, libc++) that wish to redeclare a set of declarations in another
9168namespace, when the availability of those declarations is difficult or
9169impossible to detect at compile time with the preprocessor.)reST";
9170
9171static const char AttrDoc_Uuid[] = R"reST(No documentation.)reST";
9172
9173static const char AttrDoc_VTablePointerAuthentication[] = R"reST(No documentation.)reST";
9174
9175static const char AttrDoc_VecReturn[] = R"reST(No documentation.)reST";
9176
9177static const char AttrDoc_VecTypeHint[] = R"reST(No documentation.)reST";
9178
9179static const char AttrDoc_VectorCall[] = R"reST(On 32-bit x86 *and* x86_64 targets, this attribute changes the calling
9180convention of a function to pass vector parameters in SSE registers.
9181
9182On 32-bit x86 targets, this calling convention is similar to ``__fastcall``.
9183The first two integer parameters are passed in ECX and EDX. Subsequent integer
9184parameters are passed in memory, and callee clears the stack. On x86_64
9185targets, the callee does *not* clear the stack, and integer parameters are
9186passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling
9187convention.
9188
9189On both 32-bit x86 and x86_64 targets, vector and floating point arguments are
9190passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are
9191passed in sequential SSE registers if enough are available. If AVX is enabled,
9192256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that
9193cannot be passed in registers for any reason is passed by reference, which
9194allows the caller to align the parameter memory.
9195
9196See the documentation for `__vectorcall`_ on MSDN for more details.
9197
9198.. _`__vectorcall`: http://msdn.microsoft.com/en-us/library/dn375768.aspx)reST";
9199
9200static const char AttrDoc_Visibility[] = R"reST(No documentation.)reST";
9201
9202static const char AttrDoc_WarnUnused[] = R"reST(No documentation.)reST";
9203
9204static const char AttrDoc_WarnUnusedResult[] = R"reST(Clang supports the ability to diagnose when the results of a function call
9205expression are discarded under suspicious circumstances. A diagnostic is
9206generated when a function or its return type is marked with ``[[nodiscard]]``
9207(or ``__attribute__((warn_unused_result))``) and the function call appears as a
9208potentially-evaluated discarded-value expression that is not explicitly cast to
9209``void``.
9210
9211A string literal may optionally be provided to the attribute, which will be
9212reproduced in any resulting diagnostics. Redeclarations using different forms
9213of the attribute (with or without the string literal or with different string
9214literal contents) are allowed. If there are redeclarations of the entity with
9215differing string literals, it is unspecified which one will be used by Clang
9216in any resulting diagnostics.
9217
9218.. code-block:: c++
9219
9220 struct [[nodiscard]] error_info { /*...*/ };
9221 error_info enable_missile_safety_mode();
9222
9223 void launch_missiles();
9224 void test_missiles() {
9225 enable_missile_safety_mode(); // diagnoses
9226 launch_missiles();
9227 }
9228 error_info &foo();
9229 void f() { foo(); } // Does not diagnose, error_info is a reference.
9230
9231Additionally, discarded temporaries resulting from a call to a constructor
9232marked with ``[[nodiscard]]`` or a constructor of a type marked
9233``[[nodiscard]]`` will also diagnose. This also applies to type conversions that
9234use the annotated ``[[nodiscard]]`` constructor or result in an annotated type.
9235
9236.. code-block:: c++
9237
9238 struct [[nodiscard]] marked_type {/*..*/ };
9239 struct marked_ctor {
9240 [[nodiscard]] marked_ctor();
9241 marked_ctor(int);
9242 };
9243
9244 struct S {
9245 operator marked_type() const;
9246 [[nodiscard]] operator int() const;
9247 };
9248
9249 void usages() {
9250 marked_type(); // diagnoses.
9251 marked_ctor(); // diagnoses.
9252 marked_ctor(3); // Does not diagnose, int constructor isn't marked nodiscard.
9253
9254 S s;
9255 static_cast<marked_type>(s); // diagnoses
9256 (int)s; // diagnoses
9257 })reST";
9258
9259static const char AttrDoc_Weak[] = R"reST(In supported output formats the ``weak`` attribute can be used to
9260specify that a variable or function should be emitted as a symbol with
9261``weak`` (if a definition) or ``extern_weak`` (if a declaration of an
9262external symbol) `linkage
9263<https://llvm.org/docs/LangRef.html#linkage-types>`_.
9264
9265If there is a non-weak definition of the symbol the linker will select
9266that over the weak. They must have same type and alignment (variables
9267must also have the same size), but may have a different value.
9268
9269If there are multiple weak definitions of same symbol, but no non-weak
9270definition, they should have same type, size, alignment and value, the
9271linker will select one of them (see also selectany_ attribute).
9272
9273If the ``weak`` attribute is applied to a ``const`` qualified variable
9274definition that variable is no longer consider a compiletime constant
9275as its value can change during linking (or dynamic linking). This
9276means that it can e.g no longer be part of an initializer expression.
9277
9278.. code-block:: c
9279
9280 const int ANSWER __attribute__ ((weak)) = 42;
9281
9282 /* This function may be replaced link-time */
9283 __attribute__ ((weak)) void debug_log(const char *msg)
9284 {
9285 fprintf(stderr, "DEBUG: %s\n", msg);
9286 }
9287
9288 int main(int argc, const char **argv)
9289 {
9290 debug_log ("Starting up...");
9291
9292 /* This may print something else than "6 * 7 = 42",
9293 if there is a non-weak definition of "ANSWER" in
9294 an object linked in */
9295 printf("6 * 7 = %d\n", ANSWER);
9296
9297 return 0;
9298 }
9299
9300If an external declaration is marked weak and that symbol does not
9301exist during linking (possibly dynamic) the address of the symbol will
9302evaluate to NULL.
9303
9304.. code-block:: c
9305
9306 void may_not_exist(void) __attribute__ ((weak));
9307
9308 int main(int argc, const char **argv)
9309 {
9310 if (may_not_exist) {
9311 may_not_exist();
9312 } else {
9313 printf("Function did not exist\n");
9314 }
9315 return 0;
9316 })reST";
9317
9318static const char AttrDoc_WeakImport[] = R"reST(No documentation.)reST";
9319
9320static const char AttrDoc_WeakRef[] = R"reST(No documentation.)reST";
9321
9322static const char AttrDoc_WebAssemblyExportName[] = R"reST(Clang supports the ``__attribute__((export_name(<name>)))``
9323attribute for the WebAssembly target. This attribute may be attached to a
9324function declaration, where it modifies how the symbol is to be exported
9325from the linked WebAssembly.
9326
9327WebAssembly functions are exported via string name. By default when a symbol
9328is exported, the export name for C/C++ symbols are the same as their C/C++
9329symbol names. This attribute can be used to override the default behavior, and
9330request a specific string name be used instead.)reST";
9331
9332static const char AttrDoc_WebAssemblyFuncref[] = R"reST(Clang supports the ``__attribute__((export_name(<name>)))``
9333attribute for the WebAssembly target. This attribute may be attached to a
9334function declaration, where it modifies how the symbol is to be exported
9335from the linked WebAssembly.
9336
9337WebAssembly functions are exported via string name. By default when a symbol
9338is exported, the export name for C/C++ symbols are the same as their C/C++
9339symbol names. This attribute can be used to override the default behavior, and
9340request a specific string name be used instead.)reST";
9341
9342static const char AttrDoc_WebAssemblyImportModule[] = R"reST(Clang supports the ``__attribute__((import_module(<module_name>)))``
9343attribute for the WebAssembly target. This attribute may be attached to a
9344function declaration, where it modifies how the symbol is to be imported
9345within the WebAssembly linking environment.
9346
9347WebAssembly imports use a two-level namespace scheme, consisting of a module
9348name, which typically identifies a module from which to import, and a field
9349name, which typically identifies a field from that module to import. By
9350default, module names for C/C++ symbols are assigned automatically by the
9351linker. This attribute can be used to override the default behavior, and
9352request a specific module name be used instead.)reST";
9353
9354static const char AttrDoc_WebAssemblyImportName[] = R"reST(Clang supports the ``__attribute__((import_name(<name>)))``
9355attribute for the WebAssembly target. This attribute may be attached to a
9356function declaration, where it modifies how the symbol is to be imported
9357within the WebAssembly linking environment.
9358
9359WebAssembly imports use a two-level namespace scheme, consisting of a module
9360name, which typically identifies a module from which to import, and a field
9361name, which typically identifies a field from that module to import. By
9362default, field names for C/C++ symbols are the same as their C/C++ symbol
9363names. This attribute can be used to override the default behavior, and
9364request a specific field name be used instead.)reST";
9365
9366static const char AttrDoc_WorkGroupSizeHint[] = R"reST(No documentation.)reST";
9367
9368static const char AttrDoc_X86ForceAlignArgPointer[] = R"reST(Use this attribute to force stack alignment.
9369
9370Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions
9371(like 'movaps') that work with the stack require operands to be 16-byte aligned.
9372This attribute realigns the stack in the function prologue to make sure the
9373stack can be used with SSE instructions.
9374
9375Note that the x86_64 ABI forces 16-byte stack alignment at the call site.
9376Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in
9377rare cases where the caller does not align the stack properly (e.g. flow
9378jumps from i386 arch code).
9379
9380 .. code-block:: c
9381
9382 __attribute__ ((force_align_arg_pointer))
9383 void f () {
9384 ...
9385 })reST";
9386
9387static const char AttrDoc_XRayInstrument[] = R"reST(``__attribute__((xray_always_instrument))`` or
9388``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++),
9389methods (in Objective C), and free functions (in C, C++, and Objective C) to be
9390instrumented with XRay. This will cause the function to always have space at
9391the beginning and exit points to allow for runtime patching.
9392
9393Conversely, ``__attribute__((xray_never_instrument))`` or
9394``[[clang::xray_never_instrument]]`` will inhibit the insertion of these
9395instrumentation points.
9396
9397If a function has neither of these attributes, they become subject to the XRay
9398heuristics used to determine whether a function should be instrumented or
9399otherwise.
9400
9401``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is
9402used to preserve N function arguments for the logging function. Currently,
9403only N==1 is supported.)reST";
9404
9405static const char AttrDoc_XRayLogArgs[] = R"reST(``__attribute__((xray_always_instrument))`` or
9406``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++),
9407methods (in Objective C), and free functions (in C, C++, and Objective C) to be
9408instrumented with XRay. This will cause the function to always have space at
9409the beginning and exit points to allow for runtime patching.
9410
9411Conversely, ``__attribute__((xray_never_instrument))`` or
9412``[[clang::xray_never_instrument]]`` will inhibit the insertion of these
9413instrumentation points.
9414
9415If a function has neither of these attributes, they become subject to the XRay
9416heuristics used to determine whether a function should be instrumented or
9417otherwise.
9418
9419``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is
9420used to preserve N function arguments for the logging function. Currently,
9421only N==1 is supported.)reST";
9422
9423static const char AttrDoc_ZeroCallUsedRegs[] = R"reST(This attribute, when attached to a function, causes the compiler to zero a
9424subset of all call-used registers before the function returns. It's used to
9425increase program security by either mitigating `Return-Oriented Programming`_
9426(ROP) attacks or preventing information leakage through registers.
9427
9428The term "call-used" means registers which are not guaranteed to be preserved
9429unchanged for the caller by the current calling convention. This could also be
9430described as "caller-saved" or "not callee-saved".
9431
9432The `choice` parameters gives the programmer flexibility to choose the subset
9433of the call-used registers to be zeroed:
9434
9435- ``skip`` doesn't zero any call-used registers. This choice overrides any
9436 command-line arguments.
9437- ``used`` only zeros call-used registers used in the function. By ``used``, we
9438 mean a register whose contents have been set or referenced in the function.
9439- ``used-gpr`` only zeros call-used GPR registers used in the function.
9440- ``used-arg`` only zeros call-used registers used to pass arguments to the
9441 function.
9442- ``used-gpr-arg`` only zeros call-used GPR registers used to pass arguments to
9443 the function.
9444- ``all`` zeros all call-used registers.
9445- ``all-gpr`` zeros all call-used GPR registers.
9446- ``all-arg`` zeros all call-used registers used to pass arguments to the
9447 function.
9448- ``all-gpr-arg`` zeros all call-used GPR registers used to pass arguments to
9449 the function.
9450
9451The default for the attribute is controlled by the ``-fzero-call-used-regs``
9452flag.
9453
9454.. _Return-Oriented Programming: https://en.wikipedia.org/wiki/Return-oriented_programming)reST";
9455