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][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_AMDGPUAvailableVisible[] = R"reST(This attribute controls availability and visibility as described in the [AMDGPU
53Memory Model](https://llvm.org/docs/AMDGPUMemoryModel.html). When placed on
54an atomic expression or fence, the resulting atomic or fence instruction carries
55the corresponding *AV Metadata*.
56
57The attribute takes a string literal as an argument, which currently has only
58one supported value:
59
60- `"none"`: Disable MakeAvailable and MakeVisible semantics on release and
61 acquire operations respectively.
62
63```c++
64[[clang::amdgpu_av("none")]] __atomic_thread_fence(__ATOMIC_SEQ_CST);
65[[clang::amdgpu_av("none")]] __atomic_fetch_add(ptr, 1, __ATOMIC_ACQ_REL);
66
67// Also works with _Atomic type qualifier operations.
68_Atomic int *p;
69[[clang::amdgpu_av("none")]] *p += 1;
70```)reST";
71
72static const char AttrDoc_AMDGPUFlatWorkGroupSize[] = R"reST(The flat work-group size is the number of work-items in the work-group size
73specified when the kernel is dispatched. It is the product of the sizes of the
74x, y, and z dimension of the work-group.
75
76Clang supports the
77`__attribute__((amdgpu_flat_work_group_size(<min>, <max>)))` attribute for the
78AMDGPU target. This attribute may be attached to a kernel function definition
79and is an optimization hint.
80
81`<min>` parameter specifies the minimum flat work-group size, and `<max>`
82parameter specifies the maximum flat work-group size (must be greater than
83`<min>`) to which all dispatches of the kernel will conform. Passing `0, 0`
84as `<min>, <max>` implies the default behavior (`128, 256`).
85
86If specified, the AMDGPU target backend might be able to produce better machine
87code for barriers and perform scratch promotion by estimating available group
88segment size.
89
90An error will be given if:
91: - Specified values violate subtarget specifications;
92 - Specified values are not compatible with values provided through other
93 attributes.)reST";
94
95static const char AttrDoc_AMDGPUMaxNumWorkGroups[] = R"reST(This attribute specifies the max number of work groups when the kernel
96is dispatched.
97
98Clang supports the
99`__attribute__((amdgpu_max_num_work_groups(<x>, <y>, <z>)))` or
100`[[clang::amdgpu_max_num_work_groups(<x>, <y>, <z>)]]` attribute for the
101AMDGPU target. This attribute may be attached to HIP or OpenCL kernel function
102definitions and is an optimization hint.
103
104The `<x>` parameter specifies the maximum number of work groups in the x dimension.
105Similarly `<y>` and `<z>` are for the y and z dimensions respectively.
106Each of the three values must be greater than 0 when provided. The `<x>` parameter
107is required, while `<y>` and `<z>` are optional with default value of 1.
108
109If specified, the AMDGPU target backend might be able to produce better machine
110code.
111
112An error will be given if:
113: - Specified values violate subtarget specifications;
114 - Specified values are not compatible with values provided through other
115 attributes.)reST";
116
117static const char AttrDoc_AMDGPUNamedBarrierWrapper[] = R"reST()reST";
118
119static const char AttrDoc_AMDGPUNumSGPR[] = R"reST(:::{warning}
120These attributes are deprecated. Use the `amdgpu_waves_per_eu` attribute to
121control SGPR and VGPR usage instead.
122:::
123
124Clang supports the `__attribute__((amdgpu_num_sgpr(<num_sgpr>)))` and
125`__attribute__((amdgpu_num_vgpr(<num_vgpr>)))` attributes for the AMDGPU
126target. These attributes may be attached to a kernel function definition and are
127an optimization hint.
128
129If these attributes are specified, then the AMDGPU target backend will attempt
130to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
131number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
132allocation requirements or constraints of the subtarget. Passing `0` as
133`num_sgpr` and/or `num_vgpr` implies the default behavior (no limits).
134
135These attributes can be used to test the AMDGPU target backend. It is
136recommended that the `amdgpu_waves_per_eu` attribute be used to control
137resources such as SGPRs and VGPRs since it is aware of the limits for different
138subtargets.
139
140An error will be given if:
141: - Specified values violate subtarget specifications;
142 - Specified values are not compatible with values provided through other
143 attributes;
144 - The AMDGPU target backend is unable to create machine code that can meet the
145 request.)reST";
146
147static const char AttrDoc_AMDGPUNumVGPR[] = R"reST(:::{warning}
148These attributes are deprecated. Use the `amdgpu_waves_per_eu` attribute to
149control SGPR and VGPR usage instead.
150:::
151
152Clang supports the `__attribute__((amdgpu_num_sgpr(<num_sgpr>)))` and
153`__attribute__((amdgpu_num_vgpr(<num_vgpr>)))` attributes for the AMDGPU
154target. These attributes may be attached to a kernel function definition and are
155an optimization hint.
156
157If these attributes are specified, then the AMDGPU target backend will attempt
158to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
159number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
160allocation requirements or constraints of the subtarget. Passing `0` as
161`num_sgpr` and/or `num_vgpr` implies the default behavior (no limits).
162
163These attributes can be used to test the AMDGPU target backend. It is
164recommended that the `amdgpu_waves_per_eu` attribute be used to control
165resources such as SGPRs and VGPRs since it is aware of the limits for different
166subtargets.
167
168An error will be given if:
169: - Specified values violate subtarget specifications;
170 - Specified values are not compatible with values provided through other
171 attributes;
172 - The AMDGPU target backend is unable to create machine code that can meet the
173 request.)reST";
174
175static const char AttrDoc_AMDGPUWavesPerEU[] = R"reST(A compute unit (CU) is responsible for executing the wavefronts of a work-group.
176It is composed of one or more execution units (EU), which are responsible for
177executing the wavefronts. An EU can have enough resources to maintain the state
178of more than one executing wavefront. This allows an EU to hide latency by
179switching between wavefronts in a similar way to symmetric multithreading on a
180CPU. In order to allow the state for multiple wavefronts to fit on an EU, the
181resources used by a single wavefront have to be limited. For example, the number
182of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding,
183but can result in having to spill some register state to memory.
184
185Clang supports the `__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))`
186attribute for the AMDGPU target. This attribute may be attached to a kernel
187function definition and is an optimization hint.
188
189`<min>` parameter specifies the requested minimum number of waves per EU, and
190*optional* `<max>` parameter specifies the requested maximum number of waves
191per EU (must be greater than `<min>` if specified). If `<max>` is omitted,
192then there is no restriction on the maximum number of waves per EU other than
193the one dictated by the hardware for which the kernel is compiled. Passing
194`0, 0` as `<min>, <max>` implies the default behavior (no limits).
195
196If specified, this attribute allows an advanced developer to tune the number of
197wavefronts that are capable of fitting within the resources of an EU. The AMDGPU
198target backend can use this information to limit resources, such as number of
199SGPRs, number of VGPRs, size of available group and private memory segments, in
200such a way that guarantees that at least `<min>` wavefronts and at most
201`<max>` wavefronts are able to fit within the resources of an EU. Requesting
202more wavefronts can hide memory latency but limits available registers which
203can result in spilling. Requesting fewer wavefronts can help reduce cache
204thrashing, but can reduce memory latency hiding.
205
206This attribute controls the machine code generated by the AMDGPU target backend
207to ensure it is capable of meeting the requested values. However, when the
208kernel is executed, there may be other reasons that prevent meeting the request,
209for example, there may be wavefronts from other kernels executing on the EU.
210
211An error will be given if:
212: - Specified values violate subtarget specifications;
213 - Specified values are not compatible with values provided through other
214 attributes;
215
216The AMDGPU target backend will emit a warning whenever it is unable to
217create machine code that meets the request.)reST";
218
219static const char AttrDoc_ARMInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt("TYPE")))` attribute on
220ARM targets. This attribute may be attached to a function definition and
221instructs the backend to generate appropriate function entry/exit code so that
222it can be used directly as an interrupt service routine.
223
224The parameter passed to the interrupt attribute is optional, but if
225provided it must be a string literal with one of the following values: "IRQ",
226"FIQ", "SWI", "ABORT", "UNDEF".
227
228The semantics are as follows:
229
230- If the function is AAPCS, Clang instructs the backend to realign the stack to
231 8 bytes on entry. This is a general requirement of the AAPCS at public
232 interfaces, but may not hold when an exception is taken. Doing this allows
233 other AAPCS functions to be called.
234
235- If the CPU is M-class this is all that needs to be done since the architecture
236 itself is designed in such a way that functions obeying the normal AAPCS ABI
237 constraints are valid exception handlers.
238
239- If the CPU is not M-class, the prologue and epilogue are modified to save all
240 non-banked registers that are used, so that upon return the user-mode state
241 will not be corrupted. Note that to avoid unnecessary overhead, only
242 general-purpose (integer) registers are saved in this way. If VFP operations
243 are needed, that state must be saved manually.
244
245 Specifically, interrupt kinds other than "FIQ" will save all core registers
246 except "lr" and "sp". "FIQ" interrupts will save r0-r7.
247
248- If the CPU is not M-class, the return instruction is changed to one of the
249 canonical sequences permitted by the architecture for exception return. Where
250 possible the function itself will make the necessary "lr" adjustments so that
251 the "preferred return address" is selected.
252
253 Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
254 handler, where the offset from "lr" to the preferred return address depends on
255 the execution state of the code which generated the exception. In this case
256 a sequence equivalent to "movs pc, lr" will be used.)reST";
257
258static const char AttrDoc_ARMInterruptSaveFP[] = R"reST(Clang supports the GNU style `__attribute__((interrupt_save_fp("TYPE")))`
259on ARM targets. This attribute behaves the same way as the ARM interrupt
260attribute, except the general purpose floating point registers are also saved,
261along with FPEXC and FPSCR. Note, even on M-class CPUs, where the floating
262point context can be automatically saved depending on the FPCCR, the general
263purpose floating point registers will be saved.)reST";
264
265static const char AttrDoc_ARMSaveFP[] = R"reST()reST";
266
267static const char AttrDoc_AVRInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt))` attribute on
268AVR targets. This attribute may be attached to a function definition and instructs
269the backend to generate appropriate function entry/exit code so that it can be used
270directly as an interrupt service routine.
271
272On the AVR, the hardware globally disables interrupts when an interrupt is executed.
273The first instruction of an interrupt handler declared with this attribute is a SEI
274instruction to re-enable interrupts. See also the signal attribute that
275does not insert a SEI instruction.)reST";
276
277static const char AttrDoc_AVRSignal[] = R"reST(Clang supports the GNU style `__attribute__((signal))` attribute on
278AVR targets. This attribute may be attached to a function definition and instructs
279the backend to generate appropriate function entry/exit code so that it can be used
280directly as an interrupt service routine.
281
282Interrupt handler functions defined with the signal attribute do not re-enable interrupts.)reST";
283
284static const char AttrDoc_AbiTag[] = R"reST(The `abi_tag` attribute can be applied to a function, variable, class or
285inline namespace declaration to modify the mangled name of the entity. It gives
286the ability to distinguish between different versions of the same entity but
287with different ABI versions supported. For example, a newer version of a class
288could have a different set of data members and thus have a different size. Using
289the `abi_tag` attribute, it is possible to have different mangled names for
290a global variable of the class type. Therefore, the old code could keep using
291the old mangled name and the new code will use the new mangled name with tags.)reST";
292
293static const char AttrDoc_AcquireCapability[] = R"reST(Marks a function as acquiring a capability.)reST";
294
295static const char AttrDoc_AcquireHandle[] = R"reST(If this annotation is on a function or a function type it is assumed to return
296a new handle. In case this annotation is on an output parameter,
297the function is assumed to fill the corresponding argument with a new
298handle. The attribute requires a string literal argument which used to
299identify the handle with later uses of `use_handle` or
300`release_handle`.
301
302```c++
303// Output arguments from Zircon.
304zx_status_t zx_socket_create(uint32_t options,
305 zx_handle_t __attribute__((acquire_handle("zircon"))) * out0,
306 zx_handle_t* out1 [[clang::acquire_handle("zircon")]]);
307
308
309// Returned handle.
310[[clang::acquire_handle("tag")]] int open(const char *path, int oflag, ... );
311int open(const char *path, int oflag, ... ) __attribute__((acquire_handle("tag")));
312```)reST";
313
314static const char AttrDoc_AcquiredAfter[] = R"reST(No documentation.)reST";
315
316static const char AttrDoc_AcquiredBefore[] = R"reST(No documentation.)reST";
317
318static const char AttrDoc_AddressSpace[] = R"reST(:::{Note}
319This attribute is mainly intended to be used by target headers
320provided by the toolchain. End users should prefer the documented, named
321address space annotations for their platform, such as the
322[OpenCL address spaces], `__global__`, `__local__`, or something else.
323:::
324
325The `address_space` attribute functions as a type qualifier that allows the
326programmer to specify the address space for a pointer or reference type.
327Qualified pointer types are considered distinct types for the purposes of
328overload resolution. The attribute takes a single, non-negative integer
329constant expression identifying the address space. For example:
330
331```c
332int * __attribute__((address_space(1))) ptr;
333
334void foo(__attribute__((address_space(2))) float *buf);
335```
336
337Only one address space qualifier may be applied to a given pointer or reference
338type. Where address spaces are allowed (e.g., variables, parameters, return
339types) and what values are valid depends on the target and language mode.
340
341The meaning of each value is defined by the target; multiple address spaces are
342used in environments such as OpenCL, CUDA, HIP, and other GPU programming
343models to distinguish global, local, constant, and private memory. See for
344example the address spaces defined in the [NVPTX Usage Guide][nvptx usage guide] and the
345[AMDGPU Usage Guide][amdgpu usage guide].
346
347Address spaces may partially overlap or be entirely distinct. The compiler may
348reject attempts to convert between distinct, incompatible address spaces.
349Pointer width may vary between different address spaces, so some explicit casts
350may truncate.
351
352For more information, refer to [ISO TR18037][iso tr18037], which covers embedded C language
353extensions. Section 5 covers named address spaces.
354
355[amdgpu usage guide]: https://llvm.org/docs/AMDGPUUsage.html#address-spaces
356[iso tr18037]: https://standards.iso.org/ittf/PubliclyAvailableStandards/c051126_ISO_IEC_TR_18037_2008.zip
357[nvptx usage guide]: https://llvm.org/docs/NVPTXUsage.html#address-spaces)reST";
358
359static const char AttrDoc_Alias[] = R"reST(No documentation.)reST";
360
361static const char AttrDoc_AlignMac68k[] = R"reST()reST";
362
363static const char AttrDoc_AlignNatural[] = R"reST()reST";
364
365static const char AttrDoc_AlignValue[] = R"reST(The align_value attribute can be added to the typedef of a pointer type or the
366declaration of a variable of pointer or reference type. It specifies that the
367pointer will point to, or the reference will bind to, only objects with at
368least the provided alignment. This alignment value must be some positive power
369of 2.
370
371```c
372typedef double * aligned_double_ptr __attribute__((align_value(64)));
373void foo(double & x __attribute__((align_value(128))),
374 aligned_double_ptr y) { ... }
375```
376
377If the pointer value does not have the specified alignment at runtime, the
378behavior of the program is undefined.)reST";
379
380static const char AttrDoc_Aligned[] = R"reST(No documentation.)reST";
381
382static const char AttrDoc_AllocAlign[] = R"reST(Use `__attribute__((alloc_align(<parameter-index>)))` on a declaration with a
383function prototype to specify that the prototype's return value (which must be a
384pointer type) is at least as aligned as the value of the indicated parameter.
385This includes functions, Objective-C methods, blocks, and declarations of
386function pointer, member function pointer, function reference, and block pointer
387types. The attribute can also be applied to typedef or type alias declarations
388whose underlying type has a function prototype.
389
390The parameter is given by its index in the list of formal parameters; the first
391parameter has index 1 unless the function is a C++ non-static member function,
392in which case the first parameter has index 2 to account for the implicit `this`
393parameter.
394
395```c++
396// The returned pointer has the alignment specified by the first parameter.
397void *a(size_t align) __attribute__((alloc_align(1)));
398
399// The function pointer's returned pointer has the alignment specified by
400// the first parameter of the pointed-to function.
401void *(*allocator)(size_t align) __attribute__((alloc_align(1)));
402
403// The returned pointer has the alignment specified by the second parameter.
404void *b(void *v, size_t align) __attribute__((alloc_align(2)));
405
406// The returned pointer has the alignment specified by the second visible
407// parameter, however it must be adjusted for the implicit 'this' parameter.
408void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3)));
409```
410
411Note that this attribute merely informs the compiler that a function always
412returns a sufficiently aligned pointer. It does not cause the compiler to
413emit code to enforce that alignment. The behavior is undefined if the returned
414pointer is not sufficiently aligned.)reST";
415
416static const char AttrDoc_AllocSize[] = R"reST(The `alloc_size` attribute can be placed on functions that return pointers in
417order to hint to the compiler how many bytes of memory will be available at the
418returned pointer. `alloc_size` takes one or two arguments.
419
420- `alloc_size(N)` implies that argument number N equals the number of
421 available bytes at the returned pointer.
422- `alloc_size(N, M)` implies that the product of argument number N and
423 argument number M equals the number of available bytes at the returned
424 pointer.
425
426Argument numbers are 1-based.
427
428An example of how to use `alloc_size`
429
430```c
431void *my_malloc(int a) __attribute__((alloc_size(1)));
432void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2)));
433
434int main() {
435 void *const p = my_malloc(100);
436 assert(__builtin_object_size(p, 0) == 100);
437 void *const a = my_calloc(20, 5);
438 assert(__builtin_object_size(a, 0) == 100);
439}
440```
441
442When `-Walloc-size` is enabled, this attribute allows the compiler to
443diagnose cases when the allocated memory is insufficient for the size of the
444type the returned pointer is cast to.
445
446```c
447void *my_malloc(int a) __attribute__((alloc_size(1)));
448void consumer_func(int *);
449
450int main() {
451 int *ptr = my_malloc(sizeof(int)); // no warning
452 int *w = my_malloc(1); // warning: allocation of insufficient size '1' for type 'int' with size '4'
453 consumer_func(my_malloc(1)); // warning: allocation of insufficient size '1' for type 'int' with size '4'
454}
455```
456
457:::{Note}
458This attribute works differently in clang than it does in GCC.
459Specifically, clang will only trace `const` pointers (as above); we give up
460on pointers that are not marked as `const`. In the vast majority of cases,
461this is unimportant, because LLVM has support for the `alloc_size`
462attribute. However, this may cause mildly unintuitive behavior when used with
463other attributes, such as `enable_if`.
464:::)reST";
465
466static const char AttrDoc_Allocating[] = R"reST(Declares that a function potentially allocates heap memory, and prevents any potential inference
467of `nonallocating` by the compiler.)reST";
468
469static const char AttrDoc_AlwaysDestroy[] = R"reST(The `always_destroy` attribute specifies that a variable with static or thread
470storage duration should have its exit-time destructor run. This attribute is the
471default unless clang was invoked with -fno-c++-static-destructors.
472
473If a variable is explicitly declared with this attribute, Clang will silence
474otherwise applicable `-Wexit-time-destructors` warnings.)reST";
475
476static const char AttrDoc_AlwaysInline[] = R"reST(Inlining heuristics are disabled and inlining is always attempted regardless of
477optimization level.
478
479`[[clang::always_inline]]` spelling can be used as a statement attribute; other
480spellings of the attribute are not supported on statements. If a statement is
481marked `[[clang::always_inline]]` and contains calls, the compiler attempts
482to inline those calls.
483
484```c
485int example(void) {
486 int i;
487 [[clang::always_inline]] foo(); // attempts to inline foo
488 [[clang::always_inline]] i = bar(); // attempts to inline bar
489 [[clang::always_inline]] return f(42, baz(bar())); // attempts to inline everything
490}
491```
492
493A declaration statement, which is a statement, is not a statement that can have an
494attribute associated with it (the attribute applies to the declaration, not the
495statement in that case). So this use case will not work:
496
497```c
498int example(void) {
499 [[clang::always_inline]] int i = bar();
500 return i;
501}
502```
503
504This attribute does not guarantee that inline substitution actually occurs.
505
506\<ins>Note: applying this attribute to a coroutine at the `-O0` optimization level
507has no effect; other optimization levels may only partially inline and result in a
508diagnostic.\</ins>
509
510See also [the Microsoft Docs on Inline Functions][the microsoft docs on inline functions], [the GCC Common Function
511Attribute docs][the gcc common function attribute docs], and [the GCC Inline docs][the gcc inline docs].
512
513[the gcc common function attribute docs]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html
514[the gcc inline docs]: https://gcc.gnu.org/onlinedocs/gcc/Inline.html
515[the microsoft docs on inline functions]: https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp)reST";
516
517static const char AttrDoc_AnalyzerNoReturn[] = R"reST(No documentation.)reST";
518
519static const char AttrDoc_Annotate[] = R"reST(The `annotate` attribute is used to add annotations to declarations or statements,
520typically for use by static analysis tools that are not integrated into the
521core Clang compiler (e.g., Clang-Tidy checks or out-of-tree Clang-based tools).
522It is a counterpart to the `annotate_type` attribute, which serves the same
523purpose, but for types.
524
525The attribute takes a mandatory string literal argument specifying the
526annotation category and an arbitrary number of optional arguments that provide
527additional information specific to the annotation category. The optional
528arguments must be constant expressions of arbitrary type.
529
530For example:
531
532```c++
533[[clang::annotate("category1", "foo", 1)]] void func(int val [[clang::annotate("category2")]]) {
534 [[clang::annotate("category3")]] if (val) {
535
536 }
537}
538```)reST";
539
540static const char AttrDoc_AnnotateType[] = R"reST(This attribute is used to add annotations to types, typically for use by static
541analysis tools that are not integrated into the core Clang compiler (e.g.,
542Clang-Tidy checks or out-of-tree Clang-based tools). It is a counterpart to the
543`annotate` attribute, which serves the same purpose, but for declarations.
544
545The attribute takes a mandatory string literal argument specifying the
546annotation category and an arbitrary number of optional arguments that provide
547additional information specific to the annotation category. The optional
548arguments must be constant expressions of arbitrary type.
549
550For example:
551
552```c++
553int* [[clang::annotate_type("category1", "foo", 1)]] f(int[[clang::annotate_type("category2")]] *);
554```
555
556The attribute does not have any effect on the semantics of the type system,
557neither type checking rules, nor runtime semantics. In particular:
558
559- `std::is_same<T, T [[clang::annotate_type("foo")]]>` is true for all types
560 `T`.
561- It is not permissible for overloaded functions or template specializations
562 to differ merely by an `annotate_type` attribute.
563- The presence of an `annotate_type` attribute will not affect name
564 mangling.)reST";
565
566static const char AttrDoc_AnyX86Interrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt))` attribute on X86
567targets. This attribute may be attached to a function definition and instructs
568the backend to generate appropriate function entry/exit code so that it can be
569used directly as an interrupt service routine.
570
571Interrupt handlers have access to the stack frame pushed onto the stack by the processor,
572and return using the `IRET` instruction. All registers in an interrupt handler are callee-saved.
573Exception handlers also have access to the error code pushed onto the stack by the processor,
574when applicable.
575
576An interrupt handler must take the following arguments:
577
578```c
579__attribute__ ((interrupt))
580void f (struct stack_frame *frame) {
581 ...
582}
583```
584
585Where `struct stack_frame` is a suitable struct matching the stack frame pushed
586by the processor.
587
588An exception handler must take the following arguments:
589
590```c
591__attribute__ ((interrupt))
592void g (struct stack_frame *frame, unsigned long code) {
593 ...
594}
595```
596
597On 32-bit targets, the `code` argument should be of type `unsigned int`.
598
599Exception handlers should only be used when an error code is pushed by the processor.
600Using the incorrect handler type will crash the system.
601
602Interrupt and exception handlers cannot be called by other functions and must have return type `void`.
603
604Interrupt and exception handlers should only call functions with the 'no_caller_saved_registers'
605attribute, or should be compiled with the '-mgeneral-regs-only' flag to avoid saving unused
606non-GPR registers.)reST";
607
608static const char AttrDoc_AnyX86NoCallerSavedRegisters[] = R"reST(Use this attribute to indicate that the specified function has no
609caller-saved registers. That is, all registers are callee-saved except for
610registers used for passing parameters to the function or returning parameters
611from the function.
612The compiler saves and restores any modified registers that were not used for
613passing or returning arguments to the function.
614
615The user can call functions specified with the 'no_caller_saved_registers'
616attribute from an interrupt handler without saving and restoring all
617call-clobbered registers.
618
619Functions specified with the 'no_caller_saved_registers' attribute should only
620call other functions with the 'no_caller_saved_registers' attribute, or should be
621compiled with the '-mgeneral-regs-only' flag to avoid saving unused non-GPR registers.
622
623Note that 'no_caller_saved_registers' attribute is not a calling convention.
624In fact, it only overrides the decision of which registers should be saved by
625the caller, but not how the parameters are passed from the caller to the callee.
626
627For example:
628
629```c
630__attribute__ ((no_caller_saved_registers, fastcall))
631void f (int arg1, int arg2) {
632 ...
633}
634```
635
636In this case parameters 'arg1' and 'arg2' will be passed in registers.
637In this case, on 32-bit x86 targets, the function 'f' will use ECX and EDX as
638register parameters. However, it will not assume any scratch registers and
639should save and restore any modified registers except for ECX and EDX.)reST";
640
641static const char AttrDoc_AnyX86NoCfCheck[] = R"reST(Jump Oriented Programming attacks rely on tampering with addresses used by
642indirect call / jmp, e.g. redirect control-flow to non-programmer
643intended bytes in the binary.
644X86 Supports Indirect Branch Tracking (IBT) as part of Control-Flow
645Enforcement Technology (CET). IBT instruments ENDBR instructions used to
646specify valid targets of indirect call / jmp.
647The `nocf_check` attribute has two roles:
6481\. Appertains to a function - do not add ENDBR instruction at the beginning of
649the function.
6502\. Appertains to a function pointer - do not track the target function of this
651pointer (by adding nocf_check prefix to the indirect-call instruction).)reST";
652
653static const char AttrDoc_ArcWeakrefUnavailable[] = R"reST(No documentation.)reST";
654
655static const char AttrDoc_ArgumentWithTypeTag[] = R"reST(Use `__attribute__((argument_with_type_tag(arg_kind, arg_idx,
656type_tag_idx)))` on a function declaration to specify that the function
657accepts a type tag that determines the type of some other argument.
658
659This attribute is primarily useful for checking arguments of variadic functions
660(`pointer_with_type_tag` can be used in most non-variadic cases).
661
662In the attribute prototype above:
663: - `arg_kind` is an identifier that should be used when annotating all
664 applicable type tags.
665 - `arg_idx` provides the position of a function argument. The expected type of
666 this function argument will be determined by the function argument specified
667 by `type_tag_idx`. In the code example below, "3" means that the type of the
668 function's third argument will be determined by `type_tag_idx`.
669 - `type_tag_idx` provides the position of a function argument. This function
670 argument will be a type tag. The type tag will determine the expected type of
671 the argument specified by `arg_idx`. In the code example below, "2" means
672 that the type tag associated with the function's second argument should agree
673 with the type of the argument specified by `arg_idx`.
674
675For example:
676
677```c++
678int fcntl(int fd, int cmd, ...)
679 __attribute__(( argument_with_type_tag(fcntl,3,2) ));
680// The function's second argument will be a type tag; this type tag will
681// determine the expected type of the function's third argument.
682```)reST";
683
684static const char AttrDoc_ArmAgnostic[] = R"reST(The `__arm_agnostic` keyword applies to prototyped function types and
685affects the function's calling convention for a given state S. This
686attribute allows the user to describe a function that preserves S, without
687requiring the function to share S with its callers and without making
688the assumption that S exists.
689
690If a function has the `__arm_agnostic(S)` attribute and calls a function
691without this attribute, then the function's object code will contain code
692to preserve state S. Otherwise, the function's object code will be the same
693as if it did not have the attribute.
694
695The attribute takes string arguments to describe state S. The supported
696states are:
697
698- `"sme_za_state"` for state enabled by PSTATE.ZA, such as ZA and ZT0.
699
700The attribute `__arm_agnostic("sme_za_state")` cannot be used in conjunction
701with `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` or
702`__arm_preserves(S)` where state S describes state enabled by PSTATE.ZA,
703such as "za" or "zt0".)reST";
704
705static const char AttrDoc_ArmBuiltinAlias[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics.
706It allows the intrinsic functions to
707be declared using the names defined in ACLE, and still be recognized
708as clang builtins equivalent to the underlying name. For example,
709`arm_mve.h` declares the function `vaddq_u32` with
710`__attribute__((__clang_arm_mve_alias(__builtin_arm_mve_vaddq_u32)))`,
711and similarly, one of the type-overloaded declarations of `vaddq`
712will have the same attribute. This ensures that both functions are
713recognized as that clang builtin, and in the latter case, the choice
714of which builtin to identify the function as can be deferred until
715after overload resolution.
716
717This attribute can only be used to set up the aliases for certain Arm
718intrinsic functions; it is intended for use only inside `arm_*.h`
719and is not a general mechanism for declaring arbitrary aliases for
720clang builtin functions.
721
722In order to avoid duplicating the attribute definitions for similar
723purpose for other architecture, there is a general form for the
724attribute `clang_builtin_alias`.)reST";
725
726static const char AttrDoc_ArmIn[] = R"reST(The `__arm_in` keyword applies to prototyped function types and specifies
727that the function shares a given state S with its caller. For `__arm_in`, the
728function takes the state S as input and returns with the state S unchanged.
729
730The attribute takes string arguments to instruct the compiler which state
731is shared. The supported states for S are:
732
733- `"za"` for Matrix Storage (requires SME)
734
735The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and
736`__arm_preserves(S)` are all mutually exclusive for the same state S.)reST";
737
738static const char AttrDoc_ArmInOut[] = R"reST(The `__arm_inout` keyword applies to prototyped function types and specifies
739that the function shares a given state S with its caller. For `__arm_inout`,
740the function takes the state S as input and returns new state for S.
741
742The attribute takes string arguments to instruct the compiler which state
743is shared. The supported states for S are:
744
745- `"za"` for Matrix Storage (requires SME)
746
747The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and
748`__arm_preserves(S)` are all mutually exclusive for the same state S.)reST";
749
750static const char AttrDoc_ArmLocallyStreaming[] = R"reST(The `__arm_locally_streaming` keyword applies to function declarations
751and specifies that all the statements in the function are executed in
752streaming mode. This means that:
753
754- the function requires that the target processor implements the Scalable Matrix
755 Extension (SME).
756- the program automatically puts the machine into streaming mode before
757 executing the statements and automatically restores the previous mode
758 afterwards.
759
760Clang manages PSTATE.SM automatically; it is not the source code's
761responsibility to do this. For example, Clang will emit code to enable
762streaming mode at the start of the function, and disable streaming mode
763at the end of the function.)reST";
764
765static const char AttrDoc_ArmMveStrictPolymorphism[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics for the Arm
766MVE instruction set. It is used to define the vector types used by the MVE
767intrinsics.
768
769Its effect is to modify the behavior of a vector type with respect to function
770overloading. If a candidate function for overload resolution has a parameter
771type with this attribute, then the selection of that candidate function will be
772disallowed if the actual argument can only be converted via a lax vector
773conversion. The aim is to prevent spurious ambiguity in ARM MVE polymorphic
774intrinsics.
775
776```c++
777void overloaded(uint16x8_t vector, uint16_t scalar);
778void overloaded(int32x4_t vector, int32_t scalar);
779uint16x8_t myVector;
780uint16_t myScalar;
781
782// myScalar is promoted to int32_t as a side effect of the addition,
783// so if lax vector conversions are considered for myVector, then
784// the two overloads are equally good (one argument conversion
785// each). But if the vector has the __clang_arm_mve_strict_polymorphism
786// attribute, only the uint16x8_t,uint16_t overload will match.
787overloaded(myVector, myScalar + 1);
788```
789
790However, this attribute does not prohibit lax vector conversions in contexts
791other than overloading.
792
793```c++
794uint16x8_t function();
795
796// This is still permitted with lax vector conversion enabled, even
797// if the vector types have __clang_arm_mve_strict_polymorphism
798int32x4_t result = function();
799```)reST";
800
801static const char AttrDoc_ArmNew[] = R"reST(The `__arm_new` keyword applies to function declarations and specifies
802that the function will create a new scope for state S.
803
804The attribute takes string arguments to instruct the compiler for which state
805to create new scope. The supported states for S are:
806
807- `"za"` for Matrix Storage (requires SME)
808
809For state `"za"`, this means that:
810
811- the function requires that the target processor implements the Scalable Matrix
812 Extension (SME).
813- the function will commit any lazily saved ZA data.
814- the function will create a new ZA context and enable PSTATE.ZA.
815- the function will disable PSTATE.ZA (by setting it to 0) before returning.
816
817For `__arm_new("za")` functions Clang will set up the ZA context automatically
818on entry to the function and disable it before returning. For example, if ZA is
819in a dormant state Clang will generate the code to commit a lazy-save and set up
820a new ZA state before executing user code.)reST";
821
822static const char AttrDoc_ArmOut[] = R"reST(The `__arm_out` keyword applies to prototyped function types and specifies
823that the function shares a given state S with its caller. For `__arm_out`,
824the function ignores the incoming state for S and returns new state for S.
825
826The attribute takes string arguments to instruct the compiler which state
827is shared. The supported states for S are:
828
829- `"za"` for Matrix Storage (requires SME)
830
831The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and
832`__arm_preserves(S)` are all mutually exclusive for the same state S.)reST";
833
834static const char AttrDoc_ArmPreserves[] = R"reST(The `__arm_preserves` keyword applies to prototyped function types and
835specifies that the function does not read a given state S and returns
836with state S unchanged.
837
838The attribute takes string arguments to instruct the compiler which state
839is shared. The supported states for S are:
840
841- `"za"` for Matrix Storage (requires SME)
842
843The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and
844`__arm_preserves(S)` are all mutually exclusive for the same state S.)reST";
845
846static const char AttrDoc_ArmStreaming[] = R"reST(The `__arm_streaming` keyword applies to prototyped function types and specifies
847that the function has a "streaming interface". This means that:
848
849- the function requires that the processor implements the Scalable Matrix
850 Extension (SME).
851- the function must be entered in streaming mode (that is, with PSTATE.SM
852 set to 1)
853- the function must return in streaming mode
854
855Clang manages PSTATE.SM automatically; it is not the source code's
856responsibility to do this. For example, if a non-streaming
857function calls an `__arm_streaming` function, Clang generates code
858that switches into streaming mode before calling the function and
859switches back to non-streaming mode on return.)reST";
860
861static const char AttrDoc_ArmStreamingCompatible[] = R"reST(The `__arm_streaming_compatible` keyword applies to prototyped function types and
862specifies that the function has a "streaming compatible interface". This
863means that:
864
865- the function may be entered in either non-streaming mode (PSTATE.SM=0) or
866 in streaming mode (PSTATE.SM=1).
867- the function must return in the same mode as it was entered.
868- the code executed in the function is compatible with either mode.
869
870Clang manages PSTATE.SM automatically; it is not the source code's
871responsibility to do this. Clang will ensure that the generated code in
872streaming-compatible functions is valid in either mode (PSTATE.SM=0 or
873PSTATE.SM=1). For example, if an `__arm_streaming_compatible` function calls a
874non-streaming function, Clang generates code to temporarily switch out of streaming
875mode before calling the function and switch back to streaming-mode on return if
876`PSTATE.SM` is `1` on entry of the caller. If `PSTATE.SM` is `0` on
877entry to the `__arm_streaming_compatible` function, the call will be executed
878without changing modes.)reST";
879
880static const char AttrDoc_Artificial[] = R"reST(The `artificial` attribute can be applied to an inline function. If such a
881function is inlined, the attribute indicates that debuggers should associate
882the resulting instructions with the call site, rather than with the
883corresponding line within the inlined callee.)reST";
884
885static const char AttrDoc_AsmLabel[] = R"reST(This attribute can be used on a function or variable to specify its symbol name.
886
887On some targets, all C symbols are prefixed by default with a single character,
888typically `_`. This was done historically to distinguish them from symbols
889used by other languages. (This prefix is also added to the standard Itanium
890C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true
891symbol name for a C++ variable declared as `int cppvar;` would be
892`__Z6cppvar`; note the two underscores.) This prefix is *not* added to the
893symbol names specified by the `__asm` attribute; programmers wishing to match
894a C symbol name must compensate for this.
895
896For example, consider the following C code:
897
898```c
899int var1 __asm("altvar") = 1; // "altvar" in symbol table.
900int var2 = 1; // "_var2" in symbol table.
901
902void func1(void) __asm("altfunc");
903void func1(void) {} // "altfunc" in symbol table.
904void func2(void) {} // "_func2" in symbol table.
905```
906
907Clang's implementation of this attribute is compatible with GCC's, [documented here](https://gcc.gnu.org/onlinedocs/gcc/Asm-Labels.html).
908
909While it is possible to use this attribute to name a special symbol used
910internally by the compiler, such as an LLVM intrinsic, this is neither
911recommended nor supported and may cause the compiler to crash or miscompile.
912Users who wish to gain access to intrinsic behavior are strongly encouraged to
913request new builtin functions.)reST";
914
915static const char AttrDoc_AssertCapability[] = R"reST(Marks a function that dynamically tests whether a capability is held, and halts
916the program if it is not held.)reST";
917
918static const char AttrDoc_AssumeAligned[] = R"reST(Use `__attribute__((assume_aligned(<alignment>[,<offset>]))` on a function
919declaration to specify that the return value of the function (which must be a
920pointer type) has the specified offset, in bytes, from an address with the
921specified alignment. The offset is taken to be zero if omitted.
922
923```c++
924// The returned pointer value has 32-byte alignment.
925void *a() __attribute__((assume_aligned (32)));
926
927// The returned pointer value is 4 bytes greater than an address having
928// 32-byte alignment.
929void *b() __attribute__((assume_aligned (32, 4)));
930```
931
932Note that this attribute provides information to the compiler regarding a
933condition that the code already ensures is true. It does not cause the compiler
934to enforce the provided alignment assumption.)reST";
935
936static const char AttrDoc_Atomic[] = R"reST(The `atomic` attribute can be applied to *compound statements* to override or
937further specify the default atomic code-generation behavior, especially on
938targets such as AMDGPU. You can annotate compound statements with options
939to modify how atomic instructions inside that statement are emitted at the IR
940level.
941
942For details, see the documentation for
943{ref}`@atomic <langext-atomic-code-generation>`)reST";
944
945static const char AttrDoc_Availability[] = R"reST(The `availability` attribute can be placed on declarations to describe the
946lifecycle of that declaration relative to operating system versions. Consider
947the function declaration for a hypothetical function `f`:
948
949```c++
950void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
951```
952
953The availability attribute states that `f` was introduced in macOS 10.4,
954deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information
955is used by Clang to determine when it is safe to use `f`: for example, if
956Clang is instructed to compile code for macOS 10.5, a call to `f()`
957succeeds. If Clang is instructed to compile code for macOS 10.6, the call
958succeeds but Clang emits a warning specifying that the function is deprecated.
959Finally, if Clang is instructed to compile code for macOS 10.7, the call
960fails because `f()` is no longer available.
961
962Clang is instructed to compile code for a minimum deployment version using
963the `-target` or `-mtargetos` command line arguments. For example,
964macOS 10.7 would be specified as `-target x86_64-apple-macos10.7` or
965`-mtargetos=macos10.7`. Variants like Mac Catalyst are specified as
966`-target arm64-apple-ios15.0-macabi` or `-mtargetos=ios15.0-macabi`
967
968The availability attribute is a comma-separated list starting with the
969platform name and then including clauses specifying important milestones in the
970declaration's lifetime (in any order) along with additional information. Those
971clauses can be:
972
973introduced=*version*
974
975: The first version in which this declaration was introduced.
976
977deprecated=*version*
978
979: The first version in which this declaration was deprecated, meaning that
980 users should migrate away from this API.
981
982obsoleted=*version*
983
984: The first version in which this declaration was obsoleted, meaning that it
985 was removed completely and can no longer be used.
986
987unavailable
988
989: This declaration is never available on this platform.
990
991message=*string-literal*
992
993: Additional message text that Clang will provide when emitting a warning or
994 error about use of a deprecated or obsoleted declaration. Useful to direct
995 users to replacement APIs.
996
997replacement=*string-literal*
998
999: Additional message text that Clang will use to provide Fix-It when emitting
1000 a warning about use of a deprecated declaration. The Fix-It will replace
1001 the deprecated declaration with the new declaration specified.
1002
1003environment=*identifier*
1004
1005: Target environment in which this declaration is available. If present,
1006 the availability attribute applies only to targets with the same platform
1007 and environment. The parameter is currently supported only in HLSL.
1008
1009Multiple availability attributes can be placed on a declaration, which may
1010correspond to different platforms. For most platforms, the availability
1011attribute with the platform corresponding to the target platform will be used;
1012any others will be ignored. However, the availability for `watchOS` and
1013`tvOS` can be implicitly inferred from an `iOS` availability attribute.
1014Any explicit availability attributes for those platforms are still preferred over
1015the implicitly inferred availability attributes. If no availability attribute
1016specifies availability for the current target platform, the availability
1017attributes are ignored. Supported platforms are:
1018
1019`iOS`
1020`macOS`
1021`tvOS`
1022`watchOS`
1023`iOSApplicationExtension`
1024`macOSApplicationExtension`
1025`tvOSApplicationExtension`
1026`watchOSApplicationExtension`
1027`macCatalyst`
1028`macCatalystApplicationExtension`
1029`visionOS`
1030`visionOSApplicationExtension`
1031`driverkit`
1032`anyAppleOS`
1033`swift`
1034`android`
1035`fuchsia`
1036`ohos`
1037`zos`
1038`ShaderModel`
1039
1040Some platforms have alias names:
1041
1042`ios`
1043`macos`
1044`macosx (deprecated)`
1045`tvos`
1046`watchos`
1047`ios_app_extension`
1048`macos_app_extension`
1049`macosx_app_extension (deprecated)`
1050`tvos_app_extension`
1051`watchos_app_extension`
1052`maccatalyst`
1053`maccatalyst_app_extension`
1054`visionos`
1055`visionos_app_extension`
1056`anyappleos`
1057`shadermodel`
1058
1059Supported environment names for the ShaderModel platform:
1060
1061`pixel`
1062`vertex`
1063`geometry`
1064`hull`
1065`domain`
1066`compute`
1067`raygeneration`
1068`intersection`
1069`anyhit`
1070`closesthit`
1071`miss`
1072`callable`
1073`mesh`
1074`amplification`
1075`library`
1076
1077The special platform `anyAppleOS` (alias: `anyappleos`) is a shorthand that
1078applies the availability attribute to all Apple Darwin platforms. An explicit
1079platform-specific availability attribute takes precedence over an `anyAppleOS`
1080attribute for that platform. Versions specified with `anyAppleOS` must be at
1081least 26.0, which is the first OS release where all supported Apple platforms
1082share a unified version number.
1083
1084A declaration can typically be used even when deploying back to a platform
1085version prior to when the declaration was introduced. When this happens, the
1086declaration is [weakly linked](https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html),
1087as if the `weak_import` attribute were added to the declaration. A
1088weakly-linked declaration may or may not be present a run-time, and a program
1089can determine whether the declaration is present by checking whether the
1090address of that declaration is non-NULL.
1091
1092The flag `strict` disallows using API when deploying back to a
1093platform version prior to when the declaration was introduced. An
1094attempt to use such API before its introduction causes a hard error.
1095Weakly-linking is almost always a better API choice, since it allows
1096users to query availability at runtime.
1097
1098If there are multiple declarations of the same entity, the availability
1099attributes must either match on a per-platform basis or later
1100declarations must not have availability attributes for that
1101platform. For example:
1102
1103```c
1104void g(void) __attribute__((availability(macos,introduced=10.4)));
1105void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches
1106void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
1107void g(void); // okay, inherits both macos and ios availability from above.
1108void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch
1109```
1110
1111When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
1112
1113```objc
1114@interface A
1115- (id)method __attribute__((availability(macos,introduced=10.4)));
1116- (id)method2 __attribute__((availability(macos,introduced=10.4)));
1117@end
1118
1119@interface B : A
1120- (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later
1121- (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4
1122@end
1123```
1124
1125Starting with the macOS 10.12 SDK, the `API_AVAILABLE` macro from
1126`<os/availability.h>` can simplify the spelling:
1127
1128```objc
1129@interface A
1130- (id)method API_AVAILABLE(macos(10.11)));
1131- (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0));
1132@end
1133```
1134
1135Availability attributes can also be applied using a `#pragma clang attribute`.
1136Any explicit availability attribute whose platform corresponds to the target
1137platform is applied to a declaration regardless of the availability attributes
1138specified in the pragma. For example, in the code below,
1139`hasExplicitAvailabilityAttribute` will use the `macOS` availability
1140attribute that is specified with the declaration, whereas
1141`getsThePragmaAvailabilityAttribute` will use the `macOS` availability
1142attribute that is applied by the pragma.
1143
1144```c
1145#pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function)
1146void getsThePragmaAvailabilityAttribute(void);
1147void hasExplicitAvailabilityAttribute(void) __attribute__((availability(macos,introduced=10.4)));
1148#pragma clang attribute pop
1149```
1150
1151For platforms like `watchOS` and `tvOS`, whose availability attributes can
1152be implicitly inferred from an `iOS` availability attribute, the logic is
1153slightly more complex. The explicit and the pragma-applied availability
1154attributes whose platform corresponds to the target platform are applied as
1155described in the previous paragraph. However, the implicitly inferred attributes
1156are applied to a declaration only when there is no explicit or pragma-applied
1157availability attribute whose platform corresponds to the target platform. For
1158example, the function below will receive the `tvOS` availability from the
1159pragma rather than using the inferred `iOS` availability from the declaration:
1160
1161```c
1162#pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function)
1163void getsThePragmaTVOSAvailabilityAttribute(void) __attribute__((availability(iOS,introduced=11.0)));
1164#pragma clang attribute pop
1165```
1166
1167The compiler is also able to apply implicitly inferred attributes from a pragma
1168as well. For example, when targeting `tvOS`, the function below will receive
1169a `tvOS` availability attribute that is implicitly inferred from the `iOS`
1170availability attribute applied by the pragma:
1171
1172```c
1173#pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function)
1174void infersTVOSAvailabilityFromPragma(void);
1175#pragma clang attribute pop
1176```
1177
1178The implicit attributes that are inferred from explicitly specified attributes
1179whose platform corresponds to the target platform are applied to the declaration
1180even if there is an availability attribute that can be inferred from a pragma.
1181For example, the function below will receive the `tvOS, introduced=11.0`
1182availability that is inferred from the attribute on the declaration rather than
1183inferring availability from the pragma:
1184
1185```c
1186#pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function)
1187void infersTVOSAvailabilityFromAttributeNextToDeclaration(void)
1188 __attribute__((availability(iOS,introduced=11.0)));
1189#pragma clang attribute pop
1190```
1191
1192Also see the documentation for
1193{ref}`@available <langext-objective-c-available>`)reST";
1194
1195static const char AttrDoc_AvailableOnlyInDefaultEvalMethod[] = R"reST(No documentation.)reST";
1196
1197static const char AttrDoc_BPFFastCall[] = R"reST(Functions annotated with this attribute are likely to be inlined by BPF JIT.
1198It is assumed that inlined implementation uses less caller saved registers,
1199than a regular function.
1200Specifically, the following registers are likely to be preserved:
1201- `R0` if function return value is `void`;
1202- `R2-R5` if function takes 1 argument;
1203- `R3-R5` if function takes 2 arguments;
1204- `R4-R5` if function takes 3 arguments;
1205- `R5` if function takes 4 arguments;
1206
1207For such functions Clang generates code pattern that allows BPF JIT
1208to recognize and remove unnecessary spills and fills of the preserved
1209registers.)reST";
1210
1211static const char AttrDoc_BPFPreserveAccessIndex[] = R"reST(Clang supports the `__attribute__((preserve_access_index))`
1212attribute for the BPF target. This attribute may be attached to a
1213struct or union declaration, where if -g is specified, it enables
1214preserving struct or union member access debuginfo indices of this
1215struct or union, similar to clang `__builtin_preserve_access_index()`.)reST";
1216
1217static const char AttrDoc_BPFPreserveStaticOffset[] = R"reST(Clang supports the `__attribute__((preserve_static_offset))`
1218attribute for the BPF target. This attribute may be attached to a
1219struct or union declaration. Reading or writing fields of types having
1220such annotation is guaranteed to generate LDX/ST/STX instruction with
1221offset corresponding to the field.
1222
1223For example:
1224
1225```c
1226struct foo {
1227 int a;
1228 int b;
1229};
1230
1231struct bar {
1232 int a;
1233 struct foo b;
1234} __attribute__((preserve_static_offset));
1235
1236void buz(struct bar *g) {
1237 g->b.a = 42;
1238}
1239```
1240
1241The assignment to `g`'s field would produce an ST instruction with
1242offset 8: `*(u32)(r1 + 8) = 42;`.
1243
1244Without this attribute generated instructions might be different,
1245depending on optimizations behavior. E.g. the example above could be
1246rewritten as `r1 += 8; *(u32)(r1 + 0) = 42;`.)reST";
1247
1248static const char AttrDoc_BTFDeclTag[] = R"reST(Clang supports the `__attribute__((btf_decl_tag("ARGUMENT")))` attribute for
1249all targets. This attribute may be attached to a struct/union, struct/union
1250field, function, function parameter, variable or typedef declaration. If -g is
1251specified, the `ARGUMENT` info will be preserved in IR and be emitted to
1252dwarf. For BPF targets, the `ARGUMENT` info will be emitted to .BTF ELF
1253section too.)reST";
1254
1255static const char AttrDoc_BTFTypeTag[] = R"reST(Clang supports the `__attribute__((btf_type_tag("ARGUMENT")))` attribute for
1256all targets. It only has effect when `-g` is specified on the command line.
1257
1258The attribute can be applied to a pointer type, in which case the tag is
1259associated with the pointee type, e.g.:
1260
1261```c
1262int __attribute__((btf_type_tag("tag"))) *p;
1263```
1264
1265It can also be applied to the underlying type of a typedef, in which case the
1266tag follows the typedef down to its base type, e.g.:
1267
1268```c
1269typedef struct foo __attribute__((btf_type_tag("tag"))) foo_t;
1270```
1271
1272The following is the corresponding btf:
1273
1274```
1275...
1276[2] TYPE_TAG 'tag' type_id=4
1277[3] TYPEDEF 'foo_t' type_id=2
1278[4] STRUCT 'foo' size=4 vlen=1
1279 'c' type_id=5 bits_offset=0
1280[5] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
1281...
1282```
1283
1284The attribute is currently silently ignored in any other position (note: this
1285scenario may be diagnosed in the future).
1286
1287The `ARGUMENT` string will be preserved in IR and emitted to DWARF for the
1288types used in variable declarations, function declarations, or typedef
1289declarations.
1290
1291For BPF targets, the `ARGUMENT` string will also be emitted to .BTF ELF
1292section.)reST";
1293
1294static const char AttrDoc_Blocking[] = R"reST(Declares that a function potentially blocks, and prevents any potential inference of `nonblocking`
1295by the compiler.)reST";
1296
1297static const char AttrDoc_Blocks[] = R"reST(No documentation.)reST";
1298
1299static const char AttrDoc_Builtin[] = R"reST()reST";
1300
1301static const char AttrDoc_BuiltinAlias[] = R"reST(This attribute is used in the implementation of the C intrinsics.
1302It allows the C intrinsic functions to be declared using the names defined
1303in target builtins, and still be recognized as clang builtins equivalent to the
1304underlying name. For example, `riscv_vector.h` declares the function `vadd`
1305with `__attribute__((clang_builtin_alias(__builtin_rvv_vadd_vv_i8m1)))`.
1306This ensures that both functions are recognized as that clang builtin,
1307and in the latter case, the choice of which builtin to identify the
1308function as can be deferred until after overload resolution.
1309
1310This attribute can only be used to set up the aliases for certain ARM/RISC-V
1311C intrinsic functions; it is intended for use only inside `arm_*.h` and
1312`riscv_*.h` and is not a general mechanism for declaring arbitrary aliases
1313for clang builtin functions.)reST";
1314
1315static const char AttrDoc_C11NoReturn[] = R"reST(A function declared as `_Noreturn` shall not return to its caller. The
1316compiler will generate a diagnostic for a function declared as `_Noreturn`
1317that appears to be capable of returning to its caller. Despite being a type
1318specifier, the `_Noreturn` attribute cannot be specified on a function
1319pointer type.)reST";
1320
1321static const char AttrDoc_CDecl[] = R"reST(No documentation.)reST";
1322
1323static const char AttrDoc_CFAuditedTransfer[] = R"reST(No documentation.)reST";
1324
1325static const char AttrDoc_CFConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1326(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1327convention (e.g. functions starting with "get" are assumed to return at
1328`+0`).
1329
1330It can be overridden using a family of the following attributes. In
1331Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
1332a function communicates that the object is returned at `+1`, and the caller
1333is responsible for freeing it.
1334Similarly, the annotation `__attribute__((ns_returns_not_retained))`
1335specifies that the object is returned at `+0` and the ownership remains with
1336the callee.
1337The annotation `__attribute__((ns_consumes_self))` specifies that
1338the Objective-C method call consumes the reference to `self`, e.g. by
1339attaching it to a supplied parameter.
1340Additionally, parameters can have an annotation
1341`__attribute__((ns_consumed))`, which specifies that passing an owned object
1342as that parameter effectively transfers the ownership, and the caller is no
1343longer responsible for it.
1344These attributes affect code generation when interacting with ARC code, and
1345they are used by the Clang Static Analyzer.
1346
1347In C programs using CoreFoundation, a similar set of attributes:
1348`__attribute__((cf_returns_not_retained))`,
1349`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
1350have the same respective semantics when applied to CoreFoundation objects.
1351These attributes affect code generation when interacting with ARC code, and
1352they are used by the Clang Static Analyzer.
1353
1354Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1355the same attribute family is present:
1356`__attribute__((os_returns_not_retained))`,
1357`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
1358with the same respective semantics.
1359Similar to `__attribute__((ns_consumes_self))`,
1360`__attribute__((os_consumes_this))` specifies that the method call consumes
1361the reference to "this" (e.g., when attaching it to a different object supplied
1362as a parameter).
1363Out parameters (parameters the function is meant to write into,
1364either via pointers-to-pointers or references-to-pointers)
1365may be annotated with `__attribute__((os_returns_retained))`
1366or `__attribute__((os_returns_not_retained))` which specifies that the object
1367written into the out parameter should (or respectively should not) be released
1368after use.
1369Since often out parameters may or may not be written depending on the exit
1370code of the function,
1371annotations `__attribute__((os_returns_retained_on_zero))`
1372and `__attribute__((os_returns_retained_on_non_zero))` specify that
1373an out parameter at `+1` is written if and only if the function returns a zero
1374(respectively non-zero) error code.
1375Observe that return-code-dependent out parameter annotations are only
1376available for retained out parameters, as non-retained object do not have to be
1377released by the callee.
1378These attributes are only used by the Clang Static Analyzer.
1379
1380The family of attributes `X_returns_X_retained` can be added to functions,
1381C++ methods, and Objective-C methods and properties.
1382Attributes `X_consumed` can be added to parameters of methods, functions,
1383and Objective-C methods.)reST";
1384
1385static const char AttrDoc_CFGuard[] = R"reST(Code can indicate CFG checks are not wanted with the `__declspec(guard(nocf))`
1386attribute. This directs the compiler to not insert any CFG checks for the entire
1387function. This approach is typically used only sparingly in specific situations
1388where the programmer has manually inserted "CFG-equivalent" protection. The
1389programmer knows that they are calling through some read-only function table
1390whose address is obtained through read-only memory references and for which the
1391index is masked to the function table limit. This approach may also be applied
1392to small wrapper functions that are not inlined and that do nothing more than
1393make a call through a function pointer. Since incorrect usage of this directive
1394can compromise the security of CFG, the programmer must be very careful using
1395the directive. Typically, this usage is limited to very small functions that
1396only call one function.
1397
1398`Control Flow Guard documentation <https://docs.microsoft.com/en-us/windows/win32/secbp/pe-metadata>`)reST";
1399
1400static const char AttrDoc_CFICanonicalJumpTable[] = R"reST(Use `__attribute__((cfi_canonical_jump_table))` on a function declaration to
1401make the function's CFI jump table canonical. See {ref}`the CFI documentation
1402<cfi-canonical-jump-tables>` for more details.)reST";
1403
1404static const char AttrDoc_CFISalt[] = R"reST(The `cfi_salt` attribute specifies a string literal that is used as a salt
1405for Control-Flow Integrity (CFI) checks to distinguish between functions with
1406the same type signature. This attribute can be applied to function declarations,
1407function definitions, and function pointer typedefs.
1408
1409The attribute prevents function pointers from being replaced with pointers to
1410functions that have a compatible type, which can be a CFI bypass vector.
1411
1412**Syntax:**
1413
1414- GNU-style: `__attribute__((cfi_salt("<salt_string>")))`
1415- C++11-style: `[[clang::cfi_salt("<salt_string>")]]`
1416
1417**Usage:**
1418
1419The attribute takes a single string literal argument that serves as the salt.
1420Functions or function types with different salt values will have different CFI
1421hashes, even if they have identical type signatures.
1422
1423**Motivation:**
1424
1425In large codebases like the Linux kernel, there are often hundreds of functions
1426with identical type signatures that are called indirectly:
1427
1428```
14291662 functions with void (*)(void)
14301179 functions with int (*)(void)
1431 ...
1432```
1433
1434By salting the CFI hashes, you can make CFI more robust by ensuring that
1435functions intended for different purposes have distinct CFI identities.
1436
1437**Type Compatibility:**
1438
1439- Functions with different salt values are considered to have incompatible types
1440- Function pointers with different salt values cannot be assigned to each other
1441- All declarations of the same function must use the same salt value
1442
1443**Example:**
1444
1445```c
1446// Header file - define convenience macros
1447#define __cfi_salt(s) __attribute__((cfi_salt(s)))
1448
1449// Typedef for regular function pointers
1450typedef int (*fptr_t)(void);
1451
1452// Typedef for salted function pointers
1453typedef int (*fptr_salted_t)(void) __cfi_salt("pepper");
1454
1455struct widget_ops {
1456 fptr_t init; // Regular CFI
1457 fptr_salted_t exec; // Salted CFI
1458 fptr_t cleanup; // Regular CFI
1459};
1460
1461// Function implementations
1462static int widget_init(void) { return 0; }
1463static int widget_exec(void) __cfi_salt("pepper") { return 1; }
1464static int widget_cleanup(void) { return 0; }
1465
1466static struct widget_ops ops = {
1467 .init = widget_init, // OK - compatible types
1468 .exec = widget_exec, // OK - both use "pepper" salt
1469 .cleanup = widget_cleanup // OK - compatible types
1470};
1471
1472// Using C++11 attribute syntax
1473void secure_callback(void) [[clang::cfi_salt("secure")]];
1474
1475// This would cause a compilation error:
1476// fptr_t bad_ptr = widget_exec; // Error: incompatible types
1477```
1478
1479**Notes:**
1480
1481- The salt string can contain non-NULL ASCII characters, including spaces and
1482 quotes
1483- This attribute only applies to function types; using it on non-function
1484 types will generate a warning
1485- All declarations and definitions of the same function must use identical
1486 salt values
1487- The attribute affects type compatibility during compilation and CFI hash
1488 generation during code generation)reST";
1489
1490static const char AttrDoc_CFIUncheckedCallee[] = R"reST(`cfi_unchecked_callee` is a function type attribute which prevents the
1491compiler from instrumenting
1492{doc}`Control Flow Integrity <ControlFlowIntegrity>` checks on indirect
1493function calls. This also includes control flow checks added by
1494`-fsanitize=function`; see {ref}`Available checks <ubsan-checks>`.
1495Specifically, the attribute has the following semantics:
1496
14971. Indirect calls to a function type with this attribute will not be instrumented with CFI. That is,
1498 the indirect call will not be checked. Note that this only changes the behavior for indirect calls
1499 on pointers to function types having this attribute. It does not prevent all indirect function calls
1500 for a given type from being checked.
15012. All direct references to a function whose type has this attribute will always reference the
1502 function definition rather than an entry in the CFI jump table.
15033. When a pointer to a function with this attribute is implicitly cast to a pointer to a function
1504 without this attribute, the compiler will give a warning saying this attribute is discarded. This
1505 warning can be silenced with an explicit cast. Note an explicit cast just disables the warning, so
1506 direct references to a function with a `cfi_unchecked_callee` attribute will still reference the
1507 function definition rather than the CFI jump table.
1508
1509```c
1510#define CFI_UNCHECKED_CALLEE __attribute__((cfi_unchecked_callee))
1511
1512void no_cfi() CFI_UNCHECKED_CALLEE {}
1513
1514void (*with_cfi)() = no_cfi; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1515 // `with_cfi` also points to the actual definition of `no_cfi` rather than
1516 // its jump table entry.
1517
1518void invoke(void (CFI_UNCHECKED_CALLEE *func)()) {
1519 func(); // CFI will not instrument this indirect call.
1520
1521 void (*func2)() = func; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1522
1523 func2(); // CFI will instrument this indirect call. Users should be careful however because if this
1524 // references a function with type `cfi_unchecked_callee`, then the CFI check may incorrectly
1525 // fail because the reference will be to the function definition rather than the CFI jump
1526 // table entry.
1527}
1528```
1529
1530This attribute can only be applied on functions or member functions. This attribute can be a good
1531alternative to `no_sanitize("cfi")` if you only want to disable innstrumentation for specific indirect
1532calls rather than applying `no_sanitize("cfi")` on the whole function containing indirect call. Note
1533that `cfi_unchecked_attribute` is a type attribute doesn't disable CFI instrumentation on a function
1534body.)reST";
1535
1536static const char AttrDoc_CFReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1537(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1538convention (e.g. functions starting with "get" are assumed to return at
1539`+0`).
1540
1541It can be overridden using a family of the following attributes. In
1542Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
1543a function communicates that the object is returned at `+1`, and the caller
1544is responsible for freeing it.
1545Similarly, the annotation `__attribute__((ns_returns_not_retained))`
1546specifies that the object is returned at `+0` and the ownership remains with
1547the callee.
1548The annotation `__attribute__((ns_consumes_self))` specifies that
1549the Objective-C method call consumes the reference to `self`, e.g. by
1550attaching it to a supplied parameter.
1551Additionally, parameters can have an annotation
1552`__attribute__((ns_consumed))`, which specifies that passing an owned object
1553as that parameter effectively transfers the ownership, and the caller is no
1554longer responsible for it.
1555These attributes affect code generation when interacting with ARC code, and
1556they are used by the Clang Static Analyzer.
1557
1558In C programs using CoreFoundation, a similar set of attributes:
1559`__attribute__((cf_returns_not_retained))`,
1560`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
1561have the same respective semantics when applied to CoreFoundation objects.
1562These attributes affect code generation when interacting with ARC code, and
1563they are used by the Clang Static Analyzer.
1564
1565Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1566the same attribute family is present:
1567`__attribute__((os_returns_not_retained))`,
1568`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
1569with the same respective semantics.
1570Similar to `__attribute__((ns_consumes_self))`,
1571`__attribute__((os_consumes_this))` specifies that the method call consumes
1572the reference to "this" (e.g., when attaching it to a different object supplied
1573as a parameter).
1574Out parameters (parameters the function is meant to write into,
1575either via pointers-to-pointers or references-to-pointers)
1576may be annotated with `__attribute__((os_returns_retained))`
1577or `__attribute__((os_returns_not_retained))` which specifies that the object
1578written into the out parameter should (or respectively should not) be released
1579after use.
1580Since often out parameters may or may not be written depending on the exit
1581code of the function,
1582annotations `__attribute__((os_returns_retained_on_zero))`
1583and `__attribute__((os_returns_retained_on_non_zero))` specify that
1584an out parameter at `+1` is written if and only if the function returns a zero
1585(respectively non-zero) error code.
1586Observe that return-code-dependent out parameter annotations are only
1587available for retained out parameters, as non-retained object do not have to be
1588released by the callee.
1589These attributes are only used by the Clang Static Analyzer.
1590
1591The family of attributes `X_returns_X_retained` can be added to functions,
1592C++ methods, and Objective-C methods and properties.
1593Attributes `X_consumed` can be added to parameters of methods, functions,
1594and Objective-C methods.)reST";
1595
1596static const char AttrDoc_CFReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1597(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1598convention (e.g. functions starting with "get" are assumed to return at
1599`+0`).
1600
1601It can be overridden using a family of the following attributes. In
1602Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
1603a function communicates that the object is returned at `+1`, and the caller
1604is responsible for freeing it.
1605Similarly, the annotation `__attribute__((ns_returns_not_retained))`
1606specifies that the object is returned at `+0` and the ownership remains with
1607the callee.
1608The annotation `__attribute__((ns_consumes_self))` specifies that
1609the Objective-C method call consumes the reference to `self`, e.g. by
1610attaching it to a supplied parameter.
1611Additionally, parameters can have an annotation
1612`__attribute__((ns_consumed))`, which specifies that passing an owned object
1613as that parameter effectively transfers the ownership, and the caller is no
1614longer responsible for it.
1615These attributes affect code generation when interacting with ARC code, and
1616they are used by the Clang Static Analyzer.
1617
1618In C programs using CoreFoundation, a similar set of attributes:
1619`__attribute__((cf_returns_not_retained))`,
1620`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
1621have the same respective semantics when applied to CoreFoundation objects.
1622These attributes affect code generation when interacting with ARC code, and
1623they are used by the Clang Static Analyzer.
1624
1625Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1626the same attribute family is present:
1627`__attribute__((os_returns_not_retained))`,
1628`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
1629with the same respective semantics.
1630Similar to `__attribute__((ns_consumes_self))`,
1631`__attribute__((os_consumes_this))` specifies that the method call consumes
1632the reference to "this" (e.g., when attaching it to a different object supplied
1633as a parameter).
1634Out parameters (parameters the function is meant to write into,
1635either via pointers-to-pointers or references-to-pointers)
1636may be annotated with `__attribute__((os_returns_retained))`
1637or `__attribute__((os_returns_not_retained))` which specifies that the object
1638written into the out parameter should (or respectively should not) be released
1639after use.
1640Since often out parameters may or may not be written depending on the exit
1641code of the function,
1642annotations `__attribute__((os_returns_retained_on_zero))`
1643and `__attribute__((os_returns_retained_on_non_zero))` specify that
1644an out parameter at `+1` is written if and only if the function returns a zero
1645(respectively non-zero) error code.
1646Observe that return-code-dependent out parameter annotations are only
1647available for retained out parameters, as non-retained object do not have to be
1648released by the callee.
1649These attributes are only used by the Clang Static Analyzer.
1650
1651The family of attributes `X_returns_X_retained` can be added to functions,
1652C++ methods, and Objective-C methods and properties.
1653Attributes `X_consumed` can be added to parameters of methods, functions,
1654and Objective-C methods.)reST";
1655
1656static const char AttrDoc_CFUnknownTransfer[] = R"reST(No documentation.)reST";
1657
1658static const char AttrDoc_CPUDispatch[] = R"reST(The `cpu_specific` and `cpu_dispatch` attributes are used to define and
1659resolve multiversioned functions. This form of multiversioning provides a
1660mechanism for declaring versions across translation units and manually
1661specifying the resolved function list. A specified CPU defines a set of minimum
1662features that are required for the function to be called. The result of this is
1663that future processors execute the most restrictive version of the function the
1664new processor can execute.
1665
1666In addition, unlike the ICC implementation of this feature, the selection of the
1667version does not consider the manufacturer or microarchitecture of the processor.
1668It tests solely the list of features that are both supported by the specified
1669processor and present in the compiler-rt library. This can be surprising at times,
1670as the runtime processor may be from a completely different manufacturer, as long
1671as it supports the same feature set.
1672
1673This can additionally be surprising, as some processors are indistringuishable from
1674others based on the list of testable features. When this happens, the variant
1675is selected in an unspecified manner.
1676
1677Function versions are defined with `cpu_specific`, which takes one or more CPU
1678names as a parameter. For example:
1679
1680```c
1681// Declares and defines the ivybridge version of single_cpu.
1682__attribute__((cpu_specific(ivybridge)))
1683void single_cpu(void){}
1684
1685// Declares and defines the atom version of single_cpu.
1686__attribute__((cpu_specific(atom)))
1687void single_cpu(void){}
1688
1689// Declares and defines both the ivybridge and atom version of multi_cpu.
1690__attribute__((cpu_specific(ivybridge, atom)))
1691void multi_cpu(void){}
1692```
1693
1694A dispatching (or resolving) function can be declared anywhere in a project's
1695source code with `cpu_dispatch`. This attribute takes one or more CPU names
1696as a parameter (like `cpu_specific`). Functions marked with `cpu_dispatch`
1697are not expected to be defined, only declared. If such a marked function has a
1698definition, any side effects of the function are ignored; trivial function
1699bodies are permissible for ICC compatibility.
1700
1701```c
1702// Creates a resolver for single_cpu above.
1703__attribute__((cpu_dispatch(ivybridge, atom)))
1704void single_cpu(void){}
1705
1706// Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1707// translation unit.
1708__attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1709void multi_cpu(void){}
1710```
1711
1712Note that it is possible to have a resolving function that dispatches based on
1713more or fewer options than are present in the program. Specifying fewer will
1714result in the omitted options not being considered during resolution. Specifying
1715a version for resolution that isn't defined in the program will result in a
1716linking failure.
1717
1718It is also possible to specify a CPU name of `generic` which will be resolved
1719if the executing processor doesn't satisfy the features required in the CPU
1720name. The behavior of a program executing on a processor that doesn't satisfy
1721any option of a multiversioned function is undefined.)reST";
1722
1723static const char AttrDoc_CPUSpecific[] = R"reST(The `cpu_specific` and `cpu_dispatch` attributes are used to define and
1724resolve multiversioned functions. This form of multiversioning provides a
1725mechanism for declaring versions across translation units and manually
1726specifying the resolved function list. A specified CPU defines a set of minimum
1727features that are required for the function to be called. The result of this is
1728that future processors execute the most restrictive version of the function the
1729new processor can execute.
1730
1731In addition, unlike the ICC implementation of this feature, the selection of the
1732version does not consider the manufacturer or microarchitecture of the processor.
1733It tests solely the list of features that are both supported by the specified
1734processor and present in the compiler-rt library. This can be surprising at times,
1735as the runtime processor may be from a completely different manufacturer, as long
1736as it supports the same feature set.
1737
1738This can additionally be surprising, as some processors are indistringuishable from
1739others based on the list of testable features. When this happens, the variant
1740is selected in an unspecified manner.
1741
1742Function versions are defined with `cpu_specific`, which takes one or more CPU
1743names as a parameter. For example:
1744
1745```c
1746// Declares and defines the ivybridge version of single_cpu.
1747__attribute__((cpu_specific(ivybridge)))
1748void single_cpu(void){}
1749
1750// Declares and defines the atom version of single_cpu.
1751__attribute__((cpu_specific(atom)))
1752void single_cpu(void){}
1753
1754// Declares and defines both the ivybridge and atom version of multi_cpu.
1755__attribute__((cpu_specific(ivybridge, atom)))
1756void multi_cpu(void){}
1757```
1758
1759A dispatching (or resolving) function can be declared anywhere in a project's
1760source code with `cpu_dispatch`. This attribute takes one or more CPU names
1761as a parameter (like `cpu_specific`). Functions marked with `cpu_dispatch`
1762are not expected to be defined, only declared. If such a marked function has a
1763definition, any side effects of the function are ignored; trivial function
1764bodies are permissible for ICC compatibility.
1765
1766```c
1767// Creates a resolver for single_cpu above.
1768__attribute__((cpu_dispatch(ivybridge, atom)))
1769void single_cpu(void){}
1770
1771// Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1772// translation unit.
1773__attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1774void multi_cpu(void){}
1775```
1776
1777Note that it is possible to have a resolving function that dispatches based on
1778more or fewer options than are present in the program. Specifying fewer will
1779result in the omitted options not being considered during resolution. Specifying
1780a version for resolution that isn't defined in the program will result in a
1781linking failure.
1782
1783It is also possible to specify a CPU name of `generic` which will be resolved
1784if the executing processor doesn't satisfy the features required in the CPU
1785name. The behavior of a program executing on a processor that doesn't satisfy
1786any option of a multiversioned function is undefined.)reST";
1787
1788static const char AttrDoc_CUDAClusterDims[] = R"reST(In CUDA/HIP programming, the `cluster_dims` attribute, conventionally exposed as the
1789`__cluster_dims__` macro, can be applied to a kernel function to set the dimensions of a
1790thread block cluster, which is an optional level of hierarchy and made up of thread blocks.
1791`__cluster_dims__` defines the cluster size as `(X, Y, Z)`, where each value is the number
1792of thread blocks in that dimension. The `cluster_dims` and `no_cluster` attributes are
1793mutually exclusive.
1794
1795```
1796__global__ __cluster_dims__(2, 1, 1) void kernel(...) {
1797 ...
1798}
1799```)reST";
1800
1801static const char AttrDoc_CUDAConstant[] = R"reST(No documentation.)reST";
1802
1803static const char AttrDoc_CUDADevice[] = R"reST(No documentation.)reST";
1804
1805static const char AttrDoc_CUDADeviceBuiltinSurfaceType[] = R"reST(The `device_builtin_surface_type` attribute can be applied to a class
1806template when declaring the surface reference. A surface reference variable
1807could be accessed on the host side and, on the device side, might be translated
1808into an internal surface object, which is established through surface bind and
1809unbind runtime APIs.)reST";
1810
1811static const char AttrDoc_CUDADeviceBuiltinTextureType[] = R"reST(The `device_builtin_texture_type` attribute can be applied to a class
1812template when declaring the texture reference. A texture reference variable
1813could be accessed on the host side and, on the device side, might be translated
1814into an internal texture object, which is established through texture bind and
1815unbind runtime APIs.)reST";
1816
1817static const char AttrDoc_CUDAGlobal[] = R"reST(No documentation.)reST";
1818
1819static const char AttrDoc_CUDAGridConstant[] = R"reST(The `__grid_constant__` attribute can be applied to a `const`-qualified kernel
1820function argument and allows compiler to take the address of that argument without
1821making a copy. The argument applies to sm_70 or newer GPUs, during compilation
1822with CUDA-11.7(PTX 7.7) or newer, and is ignored otherwise.)reST";
1823
1824static const char AttrDoc_CUDAHost[] = R"reST(No documentation.)reST";
1825
1826static const char AttrDoc_CUDAInvalidTarget[] = R"reST()reST";
1827
1828static const char AttrDoc_CUDALaunchBounds[] = R"reST(The ``__launch_bounds__`` attribute (also spelled ``launch_bounds``) originates
1829in CUDA. It informs the compiler of the launch configuration a kernel will be
1830dispatched with, allowing it to optimize the kernel accordingly. It takes the
1831form ``__launch_bounds__(<max-threads-per-block>[,
1832<min-blocks-per-multiprocessor>[, <max-blocks-per-cluster>]])``. All arguments
1833are constant expressions.
1834
1835The attribute only takes effect on ``__global__`` (kernel) functions; like
1836NVCC, Clang ignores it on any other function.
1837
1838``<max-threads-per-block>`` specifies the maximum number of threads per block
1839the kernel will be launched with. ``<min-blocks-per-multiprocessor>`` specifies
1840the desired minimum number of blocks resident per multiprocessor, and
1841``<max-blocks-per-cluster>`` the maximum number of blocks per cluster.
1842
1843For the NVPTX target, ``<max-threads-per-block>`` and
1844``<min-blocks-per-multiprocessor>`` map to the ``.maxntid`` and ``.minnctapersm``
1845PTX directives, respectively, and ``<max-blocks-per-cluster>`` (which requires
1846``sm_90`` or newer) maps to ``.maxclusterrank``.
1847
1848For the AMDGPU target, the attribute is translated into the equivalent AMDGPU
1849kernel attributes:
1850
1851 - ``<max-threads-per-block>`` sets the maximum
1852 ``amdgpu_flat_work_group_size`` (as ``1, <max-threads-per-block>``).
1853 - ``<min-blocks-per-multiprocessor>`` sets the minimum
1854 ``amdgpu_waves_per_eu``. Note that HIP reinterprets this CUDA argument as a
1855 minimum number of waves per execution unit, so its meaning differs from the
1856 NVPTX interpretation.
1857 - ``<max-blocks-per-cluster>`` is currently ignored.
1858
1859An explicit ``amdgpu_flat_work_group_size`` or ``amdgpu_waves_per_eu`` attribute
1860takes precedence over the value derived from ``__launch_bounds__``.
1861
1862When the same kernel is declared multiple times, the launch bounds from the most
1863recent declaration that specifies them are used; a definition without
1864``__launch_bounds__`` inherits the bounds from an earlier declaration.)reST";
1865
1866static const char AttrDoc_CUDANoCluster[] = R"reST(In CUDA/HIP programming, a kernel function can still be launched with the cluster feature enabled
1867at runtime, even without being annotated with `__cluster_dims__`. The LLVM/Clang-exclusive
1868`no_cluster` attribute, conventionally exposed as the `__no_cluster__` macro, can be applied to
1869a kernel function to explicitly indicate that the cluster feature will not be enabled either at
1870compile time or at kernel launch time. This allows the compiler to apply certain optimizations
1871without assuming that clustering could be enabled at runtime. It is undefined behavior to launch a
1872kernel annotated with `__no_cluster__` if the cluster feature is enabled at runtime.
1873The `cluster_dims` and `no_cluster` attributes are mutually exclusive.
1874
1875```
1876__global__ __no_cluster__ void kernel(...) {
1877 ...
1878}
1879```)reST";
1880
1881static const char AttrDoc_CUDAShared[] = R"reST(No documentation.)reST";
1882
1883static const char AttrDoc_CXX11NoReturn[] = R"reST(A function declared as `[[noreturn]]` shall not return to its caller. The
1884compiler will generate a diagnostic for a function declared as `[[noreturn]]`
1885that appears to be capable of returning to its caller.
1886
1887The `[[_Noreturn]]` spelling is deprecated and only exists to ease code
1888migration for code using `[[noreturn]]` after including `<stdnoreturn.h>`.)reST";
1889
1890static const char AttrDoc_CXXAssume[] = R"reST(The `assume` attribute is used to indicate to the optimizer that a
1891certain condition is assumed to be true at a certain point in the
1892program. If this condition is violated at runtime, the behavior is
1893undefined. `assume` can only be applied to a null statement.
1894
1895Different optimisers are likely to react differently to the presence of
1896this attribute; in some cases, adding `assume` may affect performance
1897negatively. It should be used with parsimony and care.
1898
1899Example:
1900
1901```c++
1902int f(int x, int y) {
1903 [[assume(x == 27)]];
1904 [[assume(x == y)]];
1905 return y + 1; // May be optimised to `return 28`.
1906}
1907```)reST";
1908
1909static const char AttrDoc_CallableWhen[] = R"reST(Use `__attribute__((callable_when(...)))` to indicate what states a method
1910may be called in. Valid states are unconsumed, consumed, or unknown. Each
1911argument to this attribute must be a quoted string. E.g.:
1912
1913`__attribute__((callable_when("unconsumed", "unknown")))`)reST";
1914
1915static const char AttrDoc_Callback[] = R"reST(The `callback` attribute specifies that the annotated function may invoke the
1916specified callback zero or more times. The callback, as well as the passed
1917arguments, are identified by their parameter name or position (starting with
19181!) in the annotated function. The first position in the attribute identifies
1919the callback callee, the following positions declare describe its arguments.
1920The callback callee is required to be callable with the number, and order, of
1921the specified arguments. The index `0`, or the identifier `this`, is used to
1922represent an implicit "this" pointer in class methods. If there is no implicit
1923"this" pointer it shall not be referenced. The index '-1', or the name "\_\_",
1924represents an unknown callback callee argument. This can be a value which is
1925not present in the declared parameter list, or one that is, but is potentially
1926inspected, captured, or modified. Parameter names and indices can be mixed in
1927the callback attribute.
1928
1929The `callback` attribute, which is directly translated to `callback`
1930metadata \<<http://llvm.org/docs/LangRef.html#callback-metadata>>, make the
1931connection between the call to the annotated function and the callback callee.
1932This can enable interprocedural optimizations which were otherwise impossible.
1933If a function parameter is mentioned in the `callback` attribute, through its
1934position, it is undefined if that parameter is used for anything other than the
1935actual callback. Inspected, captured, or modified parameters shall not be
1936listed in the `callback` metadata.
1937
1938Example encodings for the callback performed by `pthread_create` are shown
1939below. The explicit attribute annotation indicates that the third parameter
1940(`start_routine`) is called zero or more times by the `pthread_create` function,
1941and that the fourth parameter (`arg`) is passed along. Note that the callback
1942behavior of `pthread_create` is automatically recognized by Clang. In addition,
1943the declarations of `__kmpc_fork_teams` and `__kmpc_fork_call`, generated for
1944`#pragma omp target teams` and `#pragma omp parallel`, respectively, are also
1945automatically recognized as broker functions. Further functions might be added
1946in the future.
1947
1948```c
1949__attribute__((callback (start_routine, arg)))
1950int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1951 void *(*start_routine) (void *), void *arg);
1952
1953__attribute__((callback (3, 4)))
1954int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1955 void *(*start_routine) (void *), void *arg);
1956```)reST";
1957
1958static const char AttrDoc_CalledOnce[] = R"reST(The `called_once` attribute specifies that the annotated function or method
1959parameter is invoked exactly once on all execution paths. It only applies
1960to parameters with function-like types, i.e. function pointers or blocks. This
1961concept is particularly useful for asynchronous programs.
1962
1963Clang implements a check for `called_once` parameters,
1964`-Wcalled-once-parameter`. It is on by default and finds the following
1965violations:
1966
1967- Parameter is not called at all.
1968- Parameter is called more than once.
1969- Parameter is not called on one of the execution paths.
1970
1971In the latter case, Clang pinpoints the path where parameter is not invoked
1972by showing the control-flow statement where the path diverges.
1973
1974```objc
1975void fooWithCallback(void (^callback)(void) __attribute__((called_once))) {
1976 if (somePredicate()) {
1977 ...
1978 callback();
1979 } else {
1980 callback(); // OK: callback is called on every path
1981 }
1982}
1983
1984void barWithCallback(void (^callback)(void) __attribute__((called_once))) {
1985 if (somePredicate()) {
1986 ...
1987 callback(); // note: previous call is here
1988 }
1989 callback(); // warning: callback is called twice
1990}
1991
1992void foobarWithCallback(void (^callback)(void) __attribute__((called_once))) {
1993 if (somePredicate()) { // warning: callback is not called when condition is false
1994 ...
1995 callback();
1996 }
1997}
1998```
1999
2000This attribute is useful for API developers who want to double-check if they
2001implemented their method correctly.)reST";
2002
2003static const char AttrDoc_Capability[] = R"reST(No documentation.)reST";
2004
2005static const char AttrDoc_CapturedRecord[] = R"reST()reST";
2006
2007static const char AttrDoc_CarriesDependency[] = R"reST(The `carries_dependency` attribute specifies dependency propagation into and
2008out of functions.
2009
2010When specified on a function or Objective-C method, the `carries_dependency`
2011attribute means that the return value carries a dependency out of the function,
2012so that the implementation need not constrain ordering upon return from that
2013function. Implementations of the function and its caller may choose to preserve
2014dependencies instead of emitting memory ordering instructions such as fences.
2015
2016Note, this attribute does not change the meaning of the program, but may result
2017in generation of more efficient code.)reST";
2018
2019static const char AttrDoc_Cleanup[] = R"reST(This attribute allows a function to be run when a local variable goes out of
2020scope. The attribute takes the identifier of a function with a parameter type
2021that is a pointer to the type with the attribute.
2022
2023```c
2024static void foo (int *) { ... }
2025static void bar (int *) { ... }
2026void baz (void) {
2027 int x __attribute__((cleanup(foo)));
2028 {
2029 int y __attribute__((cleanup(bar)));
2030 }
2031}
2032```
2033
2034The above example will result in a call to `bar` being passed the address of
2035`y` when `y` goes out of scope, then a call to `foo` being passed the
2036address of `x` when `x` goes out of scope. If two or more variables share
2037the same scope, their `cleanup` callbacks are invoked in the reverse order
2038the variables were declared in. It is not possible to check the return value
2039(if any) of these `cleanup` callback functions.)reST";
2040
2041static const char AttrDoc_ClspvLibclcBuiltin[] = R"reST(Attribute used by [clspv][clspv] (OpenCL-C to Vulkan SPIR-V compiler) to identify functions coming from [libclc][libclc] (OpenCL-C builtin library).
2042
2043```c
2044void __attribute__((clspv_libclc_builtin)) libclc_builtin() {}
2045```
2046
2047[clspv]: https://github.com/google/clspv
2048[libclc]: https://libclc.llvm.org)reST";
2049
2050static const char AttrDoc_CmseNSCall[] = R"reST(This attribute declares a non-secure function type. When compiling for secure
2051state, a call to such a function would switch from secure to non-secure state.
2052All non-secure function calls must happen only through a function pointer, and
2053a non-secure function type should only be used as a base type of a pointer.
2054See [ARMv8-M Security Extensions: Requirements on Development
2055Tools - Engineering Specification Documentation](https://developer.arm.com/docs/ecm0359818/latest/) for more information.)reST";
2056
2057static const char AttrDoc_CmseNSEntry[] = R"reST(This attribute declares a function that can be called from non-secure state, or
2058from secure state. Entering from and returning to non-secure state would switch
2059to and from secure state, respectively, and prevent flow of information
2060to non-secure state, except via return values. See [ARMv8-M Security Extensions:
2061Requirements on Development Tools - Engineering Specification Documentation](https://developer.arm.com/docs/ecm0359818/latest/) for more information.)reST";
2062
2063static const char AttrDoc_CodeAlign[] = R"reST(The `clang::code_align(N)` attribute applies to a loop and specifies the byte
2064alignment for a loop. The attribute accepts a positive integer constant
2065initialization expression indicating the number of bytes for the minimum
2066alignment boundary. Its value must be a power of 2, between 1 and 4096
2067(inclusive).
2068
2069```c++
2070void foo() {
2071 int var = 0;
2072 [[clang::code_align(16)]] for (int i = 0; i < 10; ++i) var++;
2073}
2074
2075void Array(int *array, size_t n) {
2076 [[clang::code_align(64)]] for (int i = 0; i < n; ++i) array[i] = 0;
2077}
2078
2079void count () {
2080 int a1[10], int i = 0;
2081 [[clang::code_align(32)]] while (i < 10) { a1[i] += 3; }
2082}
2083
2084void check() {
2085 int a = 10;
2086 [[clang::code_align(8)]] do {
2087 a = a + 1;
2088 } while (a < 20);
2089}
2090
2091template<int A>
2092void func() {
2093 [[clang::code_align(A)]] for(;;) { }
2094}
2095```)reST";
2096
2097static const char AttrDoc_CodeModel[] = R"reST(The `model` attribute allows overriding the translation unit's
2098code model (specified by `-mcmodel`) for a specific global variable.
2099
2100On LoongArch, allowed values are "normal", "medium", "extreme".
2101
2102On x86-64, allowed values are `"small"` and `"large"`. `"small"` is
2103roughly equivalent to `-mcmodel=small`, meaning the global is considered
2104"small" placed closer to the `.text` section relative to "large" globals, and
2105to prefer using 32-bit relocations to access the global. `"large"` is roughly
2106equivalent to `-mcmodel=large`, meaning the global is considered "large" and
2107placed further from the `.text` section relative to "small" globals, and
210864-bit relocations must be used to access the global.)reST";
2109
2110static const char AttrDoc_CodeSeg[] = R"reST(The `__declspec(code_seg)` attribute enables the placement of code into separate
2111named segments that can be paged or locked in memory individually. This attribute
2112is used to control the placement of instantiated templates and compiler-generated
2113code. See the documentation for [\_\_declspec(code_seg)][__declspec(code_seg)] on MSDN.
2114
2115[__declspec(code_seg)]: http://msdn.microsoft.com/en-us/library/dn636922.aspx)reST";
2116
2117static const char AttrDoc_Cold[] = R"reST(`__attribute__((cold))` marks a function as cold, as a manual alternative to PGO hotness data.
2118If PGO data is available, the profile count based hotness overrides the `__attribute__((cold))` annotation (unlike `__attribute__((hot))`).)reST";
2119
2120static const char AttrDoc_Common[] = R"reST(No documentation.)reST";
2121
2122static const char AttrDoc_Const[] = R"reST(No documentation.)reST";
2123
2124static const char AttrDoc_ConstInit[] = R"reST(This attribute specifies that the variable to which it is attached is intended
2125to have a [constant initializer](http://en.cppreference.com/w/cpp/language/constant_initialization)
2126according to the rules of [basic.start.static]. The variable is required to
2127have static or thread storage duration. If the initialization of the variable
2128is not a constant initializer an error will be produced. This attribute may
2129only be used in C++; the `constinit` spelling is only accepted in C++20
2130onwards.
2131
2132Note that in C++03 strict constant expression checking is not done. Instead
2133the attribute reports if Clang can emit the variable as a constant, even if it's
2134not technically a 'constant initializer'. This behavior is non-portable.
2135
2136Static storage duration variables with constant initializers avoid hard-to-find
2137bugs caused by the indeterminate order of dynamic initialization. They can also
2138be safely used during dynamic initialization across translation units.
2139
2140This attribute acts as a compile time assertion that the requirements
2141for constant initialization have been met. Since these requirements change
2142between dialects and have subtle pitfalls it's important to fail fast instead
2143of silently falling back on dynamic initialization.
2144
2145The first use of the attribute on a variable must be part of, or precede, the
2146initializing declaration of the variable. C++20 requires the `constinit`
2147spelling of the attribute to be present on the initializing declaration if it
2148is used anywhere. The other spellings can be specified on a forward declaration
2149and omitted on a later initializing declaration.
2150
2151```c++
2152// -std=c++14
2153#define SAFE_STATIC [[clang::require_constant_initialization]]
2154struct T {
2155 constexpr T(int) {}
2156 ~T(); // non-trivial
2157};
2158SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor.
2159SAFE_STATIC T y = 42; // error: variable does not have a constant initializer
2160// copy initialization is not a constant expression on a non-literal type.
2161```)reST";
2162
2163static const char AttrDoc_Constructor[] = R"reST(The `constructor` attribute causes the function to be called before entering
2164`main()`, and the `destructor` attribute causes the function to be called
2165after returning from `main()` or when the `exit()` function has been
2166called. Note, `quick_exit()`, `_Exit()`, and `abort()` prevent a function
2167marked `destructor` from being called.
2168
2169The constructor or destructor function should not accept any arguments and its
2170return type should be `void`.
2171
2172The attributes accept an optional argument used to specify the priority order
2173in which to execute constructor and destructor functions. The priority is
2174given as an integer constant expression between 101 and 65535 (inclusive).
2175Priorities outside of that range are reserved for use by the implementation. A
2176lower value indicates a higher priority of initialization. Note that only the
2177relative ordering of values is important. For example:
2178
2179```c++
2180__attribute__((constructor(200))) void foo(void);
2181__attribute__((constructor(101))) void bar(void);
2182```
2183
2184`bar()` will be called before `foo()`, and both will be called before
2185`main()`. If no argument is given to the `constructor` or `destructor`
2186attribute, they default to the value `65535`.)reST";
2187
2188static const char AttrDoc_Consumable[] = R"reST(Each `class` that uses any of the typestate annotations must first be marked
2189using the `consumable` attribute. Failure to do so will result in a warning.
2190
2191This attribute accepts a single parameter that must be one of the following:
2192`unknown`, `consumed`, or `unconsumed`.)reST";
2193
2194static const char AttrDoc_ConsumableAutoCast[] = R"reST(No documentation.)reST";
2195
2196static const char AttrDoc_ConsumableSetOnRead[] = R"reST(No documentation.)reST";
2197
2198static const char AttrDoc_Convergent[] = R"reST(The `convergent` attribute can be placed on a function declaration. It is
2199translated into the LLVM `convergent` attribute, which indicates that the call
2200instructions of a function with this attribute cannot be made control-dependent
2201on any additional values.
2202
2203This attribute is different from `noduplicate` because it allows duplicating
2204function calls if it can be proved that the duplicated function calls are
2205not made control-dependent on any additional values, e.g., unrolling a loop
2206executed by all work items.
2207
2208Sample usage:
2209
2210```c
2211void convfunc(void) __attribute__((convergent));
2212// Setting it as a C++11 attribute is also valid in a C++ program.
2213// void convfunc(void) [[clang::convergent]];
2214```)reST";
2215
2216static const char AttrDoc_CoroAwaitElidable[] = R"reST(The `[[clang::coro_await_elidable]]` is a class attribute which can be
2217applied to a coroutine return type. It provides a hint to the compiler to apply
2218Heap Allocation Elision more aggressively.
2219
2220When a coroutine function returns such a type, a direct call expression therein
2221that returns a prvalue of a type attributed `[[clang::coro_await_elidable]]`
2222is said to be under a safe elide context if one of the following is true:
2223
2224- it is the immediate right-hand side operand to a co_await expression.
2225- it is an argument to a `[[clang::coro_await_elidable_argument]]` parameter
2226 or parameter pack of another direct call expression under a safe elide context.
2227
2228Do note that the safe elide context applies only to the call expression itself,
2229and the context does not transitively include any of its subexpressions unless
2230exceptional rules of `[[clang::coro_await_elidable_argument]]` apply.
2231
2232The compiler performs heap allocation elision on call expressions under a safe
2233elide context, if the callee is a coroutine.
2234
2235Example:
2236
2237```c++
2238class [[clang::coro_await_elidable]] Task { ... };
2239
2240Task foo();
2241Task bar() {
2242 co_await foo(); // foo()'s coroutine frame on this line is elidable
2243 auto t = foo(); // foo()'s coroutine frame on this line is NOT elidable
2244 co_await t;
2245}
2246```
2247
2248Such elision replaces the heap allocated activation frame of the callee coroutine
2249with a local variable within the enclosing braces in the caller's stack frame.
2250The local variable, like other variables in coroutines, may be collected into the
2251coroutine frame, which may be allocated on the heap. The behavior is undefined
2252if the caller coroutine is destroyed earlier than the callee coroutine.)reST";
2253
2254static const char AttrDoc_CoroAwaitElidableArgument[] = R"reST(The `[[clang::coro_await_elidable_argument]]` is a function parameter attribute.
2255It works in conjunction with `[[clang::coro_await_elidable]]` to propagate a
2256safe elide context to a parameter or parameter pack if the function is called
2257under a safe elide context.
2258
2259This is sometimes necessary on utility functions used to compose or modify the
2260behavior of a callee coroutine.
2261
2262Example:
2263
2264```c++
2265template <typename T>
2266class [[clang::coro_await_elidable]] Task { ... };
2267
2268template <typename... T>
2269class [[clang::coro_await_elidable]] WhenAll { ... };
2270
2271// `when_all` is a utility function that composes coroutines. It does not
2272// need to be a coroutine to propagate.
2273template <typename... T>
2274WhenAll<T...> when_all([[clang::coro_await_elidable_argument]] Task<T> tasks...);
2275
2276Task<int> foo();
2277Task<int> bar();
2278Task<void> example1() {
2279 // `when_all`, `foo`, and `bar` are all elide safe because `when_all` is
2280 // under a safe elide context and, thanks to the [[clang::coro_await_elidable_argument]]
2281 // attribute, such context is propagated to foo and bar.
2282 co_await when_all(foo(), bar());
2283}
2284
2285Task<void> example2() {
2286 // `when_all` and `bar` are elide safe. `foo` is not elide safe.
2287 auto f = foo();
2288 co_await when_all(f, bar());
2289}
2290
2291
2292Task<void> example3() {
2293 // None of the calls are elide safe.
2294 auto t = when_all(foo(), bar());
2295 co_await t;
2296}
2297```)reST";
2298
2299static const char AttrDoc_CoroDisableLifetimeBound[] = R"reST(The `[[clang::coro_lifetimebound]]` is a class attribute which can be applied
2300to a coroutine return type ([coro_return_type, coro_wrapper]) (i.e.
2301it should also be annotated with `[[clang::coro_return_type]]`).
2302
2303All parameters of a function are considered to be lifetime bound if the function returns a
2304coroutine return type (CRT) annotated with `[[clang::coro_lifetimebound]]`.
2305This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2306with `[[clang::coro_disable_lifetimebound]]` function attribute .
2307See documentation of [lifetimebound] for details about lifetime bound analysis.
2308
2309Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2310
2311For example,
2312
2313```c++
2314task<int> coro(const int& a) { co_return a + 1; }
2315task<int> dangling_refs(int a) {
2316 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2317 auto foo = coro(1);
2318 // `coro` captures reference to local variable `a` which is destroyed after the return.
2319 return coro(a);
2320}
2321```
2322
2323Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2324which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2325`[[clang::coro_lifetimebound]]`, then lifetime bound analysis would detect capturing reference to
2326temporaries or return address of a local variable.
2327
2328Both coroutines and coroutine wrappers are part of this analysis.
2329
2330```c++
2331template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2332 using promise_type = some_promise_type;
2333};
2334
2335Task<int> coro(const int& a) { co_return a + 1; }
2336[[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2337 return a > b ? coro(a) : coro(b);
2338}
2339Task<int> temporary_reference() {
2340 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2341
2342 int a = 1;
2343 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2344
2345 co_return co_await coro(1); // fine.
2346}
2347[[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2348 return coro(a); // warning: returning address of stack variable `a`.
2349}
2350```
2351
2352This analysis can be disabled for all calls to a particular function by annotating the function
2353with function attribute `[[clang::coro_disable_lifetimebound]]`.
2354For example, this could be useful for coroutine wrappers which accept reference parameters
2355but do not pass them to the underlying coroutine or pass them by value.
2356
2357```c++
2358Task<int> coro(int a) { co_return a + 1; }
2359[[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2360 return coro(a + 1);
2361}
2362void use() {
2363 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2364}
2365```)reST";
2366
2367static const char AttrDoc_CoroLifetimeBound[] = R"reST(The `[[clang::coro_lifetimebound]]` is a class attribute which can be applied
2368to a coroutine return type ([coro_return_type, coro_wrapper]) (i.e.
2369it should also be annotated with `[[clang::coro_return_type]]`).
2370
2371All parameters of a function are considered to be lifetime bound if the function returns a
2372coroutine return type (CRT) annotated with `[[clang::coro_lifetimebound]]`.
2373This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2374with `[[clang::coro_disable_lifetimebound]]` function attribute .
2375See documentation of [lifetimebound] for details about lifetime bound analysis.
2376
2377Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2378
2379For example,
2380
2381```c++
2382task<int> coro(const int& a) { co_return a + 1; }
2383task<int> dangling_refs(int a) {
2384 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2385 auto foo = coro(1);
2386 // `coro` captures reference to local variable `a` which is destroyed after the return.
2387 return coro(a);
2388}
2389```
2390
2391Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2392which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2393`[[clang::coro_lifetimebound]]`, then lifetime bound analysis would detect capturing reference to
2394temporaries or return address of a local variable.
2395
2396Both coroutines and coroutine wrappers are part of this analysis.
2397
2398```c++
2399template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2400 using promise_type = some_promise_type;
2401};
2402
2403Task<int> coro(const int& a) { co_return a + 1; }
2404[[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2405 return a > b ? coro(a) : coro(b);
2406}
2407Task<int> temporary_reference() {
2408 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2409
2410 int a = 1;
2411 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2412
2413 co_return co_await coro(1); // fine.
2414}
2415[[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2416 return coro(a); // warning: returning address of stack variable `a`.
2417}
2418```
2419
2420This analysis can be disabled for all calls to a particular function by annotating the function
2421with function attribute `[[clang::coro_disable_lifetimebound]]`.
2422For example, this could be useful for coroutine wrappers which accept reference parameters
2423but do not pass them to the underlying coroutine or pass them by value.
2424
2425```c++
2426Task<int> coro(int a) { co_return a + 1; }
2427[[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2428 return coro(a + 1);
2429}
2430void use() {
2431 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2432}
2433```)reST";
2434
2435static const char AttrDoc_CoroOnlyDestroyWhenComplete[] = R"reST(The `coro_only_destroy_when_complete` attribute should be marked on a C++ class. The coroutines
2436whose return type is marked with the attribute are assumed to be destroyed only after the coroutine has
2437reached the final suspend point.
2438
2439This is helpful for the optimizers to reduce the size of the destroy function for the coroutines.
2440
2441For example,
2442
2443```c++
2444A foo() {
2445 dtor d;
2446 co_await something();
2447 dtor d1;
2448 co_await something();
2449 dtor d2;
2450 co_return 43;
2451}
2452```
2453
2454The compiler may generate the following pseudocode:
2455
2456```c++
2457void foo.destroy(foo.Frame *frame) {
2458 switch(frame->suspend_index()) {
2459 case 1:
2460 frame->d.~dtor();
2461 break;
2462 case 2:
2463 frame->d.~dtor();
2464 frame->d1.~dtor();
2465 break;
2466 case 3:
2467 frame->d.~dtor();
2468 frame->d1.~dtor();
2469 frame->d2.~dtor();
2470 break;
2471 default: // coroutine completed or haven't started
2472 break;
2473 }
2474
2475 frame->promise.~promise_type();
2476 delete frame;
2477}
2478```
2479
2480The `foo.destroy()` function's purpose is to release all of the resources
2481initialized for the coroutine when it is destroyed in a suspended state.
2482However, if the coroutine is only ever destroyed at the final suspend state,
2483the rest of the conditions are superfluous.
2484
2485The user can use the `coro_only_destroy_when_complete` attributo suppress
2486generation of the other destruction cases, optimizing the above `foo.destroy` to:
2487
2488```c++
2489void foo.destroy(foo.Frame *frame) {
2490 frame->promise.~promise_type();
2491 delete frame;
2492}
2493```)reST";
2494
2495static const char AttrDoc_CoroReturnType[] = R"reST(The `[[clang::coro_return_type]]` attribute is used to help static analyzers to recognize
2496coroutines from the function signatures.
2497
2498The `coro_return_type` attribute should be marked on a C++ class to mark it as
2499a **coroutine return type (CRT)**.
2500
2501A function `R func(P1, .., PN)` has a coroutine return type (CRT) `R` if `R`
2502is marked by `[[clang::coro_return_type]]` and `R` has a promise type associated to it
2503(i.e., std::coroutine_traits\<R, P1, .., PN>::promise_type is a valid promise type).
2504
2505If the return type of a function is a `CRT` then the function must be a coroutine.
2506Otherwise the program is invalid. It is allowed for a non-coroutine to return a `CRT`
2507if the function is marked with `[[clang::coro_wrapper]]`.
2508
2509The `[[clang::coro_wrapper]]` attribute should be marked on a C++ function to mark it as
2510a **coroutine wrapper**. A coroutine wrapper is a function which returns a `CRT`,
2511is not a coroutine itself and is marked with `[[clang::coro_wrapper]]`.
2512
2513Clang will enforce that all functions that return a `CRT` are either coroutines or marked
2514with `[[clang::coro_wrapper]]`. Clang will enforce this with an error.
2515
2516From a language perspective, it is not possible to differentiate between a coroutine and a
2517function returning a CRT by merely looking at the function signature.
2518
2519Coroutine wrappers, in particular, are susceptible to capturing
2520references to temporaries and other lifetime issues. This allows to avoid such lifetime
2521issues with coroutine wrappers.
2522
2523For example,
2524
2525```c++
2526// This is a CRT.
2527template <typename T> struct [[clang::coro_return_type]] Task {
2528 using promise_type = some_promise_type;
2529};
2530
2531Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2532Task<int> foo() { return increment(1); } // Error. foo is not a coroutine.
2533
2534// Fine for a coroutine wrapper to return a CRT.
2535[[clang::coro_wrapper]] Task<int> foo() { return increment(1); }
2536
2537void bar() {
2538 // Invalid. This intantiates a function which returns a CRT but is not marked as
2539 // a coroutine wrapper.
2540 std::function<Task<int>(int)> f = increment;
2541}
2542```
2543
2544Note: `a_promise_type::get_return_object` is exempted from this analysis as it is a necessary
2545implementation detail of any coroutine library.)reST";
2546
2547static const char AttrDoc_CoroWrapper[] = R"reST(The `[[clang::coro_return_type]]` attribute is used to help static analyzers to recognize
2548coroutines from the function signatures.
2549
2550The `coro_return_type` attribute should be marked on a C++ class to mark it as
2551a **coroutine return type (CRT)**.
2552
2553A function `R func(P1, .., PN)` has a coroutine return type (CRT) `R` if `R`
2554is marked by `[[clang::coro_return_type]]` and `R` has a promise type associated to it
2555(i.e., std::coroutine_traits\<R, P1, .., PN>::promise_type is a valid promise type).
2556
2557If the return type of a function is a `CRT` then the function must be a coroutine.
2558Otherwise the program is invalid. It is allowed for a non-coroutine to return a `CRT`
2559if the function is marked with `[[clang::coro_wrapper]]`.
2560
2561The `[[clang::coro_wrapper]]` attribute should be marked on a C++ function to mark it as
2562a **coroutine wrapper**. A coroutine wrapper is a function which returns a `CRT`,
2563is not a coroutine itself and is marked with `[[clang::coro_wrapper]]`.
2564
2565Clang will enforce that all functions that return a `CRT` are either coroutines or marked
2566with `[[clang::coro_wrapper]]`. Clang will enforce this with an error.
2567
2568From a language perspective, it is not possible to differentiate between a coroutine and a
2569function returning a CRT by merely looking at the function signature.
2570
2571Coroutine wrappers, in particular, are susceptible to capturing
2572references to temporaries and other lifetime issues. This allows to avoid such lifetime
2573issues with coroutine wrappers.
2574
2575For example,
2576
2577```c++
2578// This is a CRT.
2579template <typename T> struct [[clang::coro_return_type]] Task {
2580 using promise_type = some_promise_type;
2581};
2582
2583Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2584Task<int> foo() { return increment(1); } // Error. foo is not a coroutine.
2585
2586// Fine for a coroutine wrapper to return a CRT.
2587[[clang::coro_wrapper]] Task<int> foo() { return increment(1); }
2588
2589void bar() {
2590 // Invalid. This intantiates a function which returns a CRT but is not marked as
2591 // a coroutine wrapper.
2592 std::function<Task<int>(int)> f = increment;
2593}
2594```
2595
2596Note: `a_promise_type::get_return_object` is exempted from this analysis as it is a necessary
2597implementation detail of any coroutine library.)reST";
2598
2599static const char AttrDoc_CountedBy[] = R"reST(The `counted_by` attribute is applied to a pointer or flexible array member to
2600indicate that the pointer points to (or the flexible array member contains) at
2601least the number of *elements* given by the attribute's argument.
2602
2603This attribute is used by {doc}`-fbounds-safety <BoundsSafety>` to propagate
2604bounds information on API surfaces without any ABI changes. This attribute is
2605also used to improve the results of the array bound sanitizer and the
2606`__builtin_dynamic_object_size` builtin.
2607
2608Because the size of the pointee type must be known to compute the pointer's
2609bounds, such a pointer must not be used while its pointee type is incomplete; a
2610pointer to a forward-declared type is accepted on fields annotated with
2611`counted_by`, but the type must be completed before the pointer is used. If
2612the pointee type can never be completed, `counted_by` is rejected and
2613`sized_by` should be used instead. `void *` is a special case: as a GNU
2614extension (diagnosed by `-Wgnu-pointer-arith`), `counted_by` is accepted on
2615it, where it behaves like `sized_by` (the argument is treated as a byte count,
2616`void` having an assumed size of one byte).
2617
2618A pointer annotated with `counted_by` must have a count of zero when it is
2619null. This requirement is currently only enforced when compiling with
2620{doc}`-fbounds-safety <BoundsSafety>` (see {ref}`Current status of
2621-fbounds-safety support in upstream Clang <bounds-safety-current-upstream-status>`). Use
2622`counted_by_or_null` for a pointer that may be null while carrying a nonzero
2623count.
2624
2625#### Keeping pointer and count in sync
2626
2627The `counted_by` attribute establishes a relationship between the annotated
2628pointer and its count: the pointer must point to at least `count` elements.
2629Assigning to only one of them can break this relationship.
2630Without {doc}`-fbounds-safety <BoundsSafety>`, it is the programmer's
2631responsibility to ensure the pointer and count remain in sync. With
2632`-fbounds-safety` it is automatically enforced. For example:
2633
2634```c
2635struct buffer {
2636 int *buf __attribute__((counted_by(count)));
2637 size_t count;
2638};
2639
2640void grow(struct buffer *b, size_t new_count) {
2641 // b->buf isn't updated. The underlying memory pointed to by b->buf might be
2642 // smaller than new_count which would contradict the counted_by attribute.
2643 // Compile error with -fbounds-safety but allowed without -fbounds-safety.
2644 b->count = new_count;
2645}
2646```
2647
2648Updating both together - so that `buf` points to `count` elements - keeps
2649the attribute true. For example:
2650
2651```c
2652void grow(struct buffer *b, size_t new_count) {
2653 // Allowed by -fbounds-safety
2654 int *new_buf = malloc(new_count * sizeof(int));
2655 // -fbounds-safety enforces that the `new_buf` points to at least `new_count`
2656 // integers at runtime. Without -fbounds-safety nothing enforces this.
2657 b->buf = new_buf;
2658 b->count = new_count;
2659}
2660```
2661
2662#### Flexible array members
2663
2664The `counted_by` attribute may also be applied to the flexible array member of
2665a structure in C. In this case the argument names the field member holding the
2666count of elements in the flexible array; that field must be within the same
2667non-anonymous, enclosing struct as the flexible array member.
2668
2669This example specifies that the flexible array member `array` has the number
2670of elements allocated for it in `count`:
2671
2672```c
2673struct bar;
2674
2675struct foo {
2676 size_t count;
2677 char other;
2678 struct bar *array[] __attribute__((counted_by(count)));
2679};
2680```
2681
2682This establishes a relationship between `array` and `count`. Specifically,
2683`array` must have at least `count` number of elements available. It's the
2684user's responsibility to ensure that this relationship is maintained through
2685changes to the structure.
2686
2687In the following example, the allocated array erroneously has fewer elements
2688than what's specified by `p->count`. This would result in an out-of-bounds
2689access not being detected.
2690
2691```c
2692#define SIZE_INCR 42
2693
2694struct foo *p;
2695
2696void foo_alloc(size_t count) {
2697 p = malloc(MAX(sizeof(struct foo),
2698 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2699 p->count = count + SIZE_INCR;
2700}
2701```
2702
2703The next example updates `p->count`, but breaks the relationship requirement
2704that `p->array` must have at least `p->count` number of elements available:
2705
2706```c
2707#define SIZE_INCR 42
2708
2709struct foo *p;
2710
2711void foo_alloc(size_t count) {
2712 p = malloc(MAX(sizeof(struct foo),
2713 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2714 p->count = count;
2715}
2716
2717void use_foo(int index, int val) {
2718 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
2719 p->array[index] = val; /* The sanitizer can't properly check this access. */
2720}
2721```
2722
2723In this example, an update to `p->count` maintains the relationship
2724requirement:
2725
2726```c
2727void use_foo(int index, int val) {
2728 if (p->count == 0)
2729 return;
2730 --p->count;
2731 p->array[index] = val;
2732}
2733```)reST";
2734
2735static const char AttrDoc_CountedByOrNull[] = R"reST(The `counted_by_or_null` attribute is applied to a pointer to indicate that,
2736if the pointer is non-null, it points to memory containing at least the number
2737of *elements* given by the attribute's argument. If the pointer is null, the
2738value of the argument is ignored and the pointer points to zero elements.
2739
2740The `counted_by_or_null` attribute is identical to `counted_by` except that
2741it treats null pointers differently and cannot be applied to a flexible array
2742member. Whereas `counted_by` requires a null pointer to have a count of zero,
2743`counted_by_or_null` allows the pointer to be null regardless of the value of
2744the count. This supports the common idiom where a pointer is either null or
2745points to memory containing at least the given number of elements.
2746
2747Currently only {doc}`-fbounds-safety <BoundsSafety>` makes use of the
2748distinction between `counted_by_or_null` and `counted_by` (see
2749{ref}`Current status of -fbounds-safety support in upstream Clang
2750<bounds-safety-current-upstream-status>`).)reST";
2751
2752static const char AttrDoc_DLLExport[] = R"reST(The `__declspec(dllexport)` attribute declares a variable, function, or
2753Objective-C interface to be exported from the module. It is available under the
2754`-fdeclspec` flag for compatibility with various compilers. The primary use
2755is for COFF object files which explicitly specify what interfaces are available
2756for external use. See the [dllexport][dllexport] documentation on MSDN for more
2757information.
2758
2759[dllexport]: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2760
2761static const char AttrDoc_DLLExportOnDecl[] = R"reST()reST";
2762
2763static const char AttrDoc_DLLExportStaticLocal[] = R"reST()reST";
2764
2765static const char AttrDoc_DLLImport[] = R"reST(The `__declspec(dllimport)` attribute declares a variable, function, or
2766Objective-C interface to be imported from an external module. It is available
2767under the `-fdeclspec` flag for compatibility with various compilers. The
2768primary use is for COFF object files which explicitly specify what interfaces
2769are imported from external modules. See the [dllimport][dllimport] documentation on MSDN
2770for more information.
2771
2772Note that a dllimport function may still be inlined, if its definition is
2773available and it doesn't reference any non-dllimport functions or global
2774variables.
2775
2776[dllimport]: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2777
2778static const char AttrDoc_DLLImportStaticLocal[] = R"reST()reST";
2779
2780static const char AttrDoc_Deprecated[] = R"reST(The `deprecated` attribute can be applied to a function, a variable, or a
2781type. This is useful when identifying functions, variables, or types that are
2782expected to be removed in a future version of a program.
2783
2784Consider the function declaration for a hypothetical function `f`:
2785
2786```c++
2787void f(void) __attribute__((deprecated("message", "replacement")));
2788```
2789
2790When spelled as `__attribute__((deprecated))`, the deprecated attribute can have
2791two optional string arguments. The first one is the message to display when
2792emitting the warning; the second one enables the compiler to provide a Fix-It
2793to replace the deprecated name with a new name. Otherwise, when spelled as
2794`[[gnu::deprecated]]` or `[[deprecated]]`, the attribute can have one optional
2795string argument which is the message to display when emitting the warning.)reST";
2796
2797static const char AttrDoc_Destructor[] = R"reST(The `constructor` attribute causes the function to be called before entering
2798`main()`, and the `destructor` attribute causes the function to be called
2799after returning from `main()` or when the `exit()` function has been
2800called. Note, `quick_exit()`, `_Exit()`, and `abort()` prevent a function
2801marked `destructor` from being called.
2802
2803The constructor or destructor function should not accept any arguments and its
2804return type should be `void`.
2805
2806The attributes accept an optional argument used to specify the priority order
2807in which to execute constructor and destructor functions. The priority is
2808given as an integer constant expression between 101 and 65535 (inclusive).
2809Priorities outside of that range are reserved for use by the implementation. A
2810lower value indicates a higher priority of initialization. Note that only the
2811relative ordering of values is important. For example:
2812
2813```c++
2814__attribute__((constructor(200))) void foo(void);
2815__attribute__((constructor(101))) void bar(void);
2816```
2817
2818`bar()` will be called before `foo()`, and both will be called before
2819`main()`. If no argument is given to the `constructor` or `destructor`
2820attribute, they default to the value `65535`.)reST";
2821
2822static const char AttrDoc_DeviceKernel[] = R"reST(These attributes specify that the function represents a kernel for device offloading.
2823The specific semantics depend on the offloading language, target, and attribute spelling.
2824Here is a code example using the attribute to mark a function as a kernel:
2825
2826```c++
2827[[clang::device_kernel]] int foo(int x) { return ++x; }
2828```)reST";
2829
2830static const char AttrDoc_DiagnoseAsBuiltin[] = R"reST(The `diagnose_as_builtin` attribute indicates that Fortify diagnostics are to
2831be applied to the declared function as if it were the function specified by the
2832attribute. The builtin function whose diagnostics are to be mimicked should be
2833given. In addition, the order in which arguments should be applied must also
2834be given.
2835
2836For example, the attribute can be used as follows.
2837
2838```c
2839__attribute__((diagnose_as_builtin(__builtin_memset, 3, 2, 1)))
2840void *mymemset(int n, int c, void *s) {
2841 // ...
2842}
2843```
2844
2845This indicates that calls to `mymemset` should be diagnosed as if they were
2846calls to `__builtin_memset`. The arguments `3, 2, 1` indicate by index the
2847order in which arguments of `mymemset` should be applied to
2848`__builtin_memset`. The third argument should be applied first, then the
2849second, and then the first. Thus (when Fortify warnings are enabled) the call
2850`mymemset(n, c, s)` will diagnose overflows as if it were the call
2851`__builtin_memset(s, c, n)`.
2852
2853For variadic functions, the variadic arguments must come in the same order as
2854they would to the builtin function, after all normal arguments. For instance,
2855to diagnose a new function as if it were `sscanf`, we can use the attribute as
2856follows.
2857
2858```c
2859__attribute__((diagnose_as_builtin(sscanf, 1, 2)))
2860int mysscanf(const char *str, const char *format, ...) {
2861 // ...
2862}
2863```
2864
2865Then the call `mysscanf("abc def", "%4s %4s", buf1, buf2)` will be diagnosed as
2866if it were the call `sscanf("abc def", "%4s %4s", buf1, buf2)`.
2867
2868This attribute cannot be applied to non-static member functions.)reST";
2869
2870static const char AttrDoc_DiagnoseIf[] = R"reST(The `diagnose_if` attribute can be placed on function declarations to emit
2871warnings or errors at compile-time if calls to the attributed function meet
2872certain user-defined criteria. For example:
2873
2874```c
2875int abs(int a)
2876 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning")));
2877int must_abs(int a)
2878 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error")));
2879
2880int val = abs(1); // warning: Redundant abs call
2881int val2 = must_abs(1); // error: Redundant abs call
2882int val3 = abs(val);
2883int val4 = must_abs(val); // Because run-time checks are not emitted for
2884 // diagnose_if attributes, this executes without
2885 // issue.
2886```
2887
2888`diagnose_if` is closely related to `enable_if`, with a few key differences:
2889
2890- Overload resolution is not aware of `diagnose_if` attributes: they're
2891 considered only after we select the best candidate from a given candidate set.
2892- Function declarations that differ only in their `diagnose_if` attributes are
2893 considered to be redeclarations of the same function (not overloads).
2894- If the condition provided to `diagnose_if` cannot be evaluated, no
2895 diagnostic will be emitted.
2896
2897Otherwise, `diagnose_if` is essentially the logical negation of `enable_if`.
2898
2899As a result of bullet number two, `diagnose_if` attributes will stack on the
2900same function. For example:
2901
2902```c
2903int foo() __attribute__((diagnose_if(1, "diag1", "warning")));
2904int foo() __attribute__((diagnose_if(1, "diag2", "warning")));
2905
2906int bar = foo(); // warning: diag1
2907 // warning: diag2
2908int (*fooptr)(void) = foo; // warning: diag1
2909 // warning: diag2
2910
2911constexpr int supportsAPILevel(int N) { return N < 5; }
2912int baz(int a)
2913 __attribute__((diagnose_if(!supportsAPILevel(10),
2914 "Upgrade to API level 10 to use baz", "error")));
2915int baz(int a)
2916 __attribute__((diagnose_if(!a, "0 is not recommended.", "warning")));
2917
2918int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz
2919int v = baz(0); // error: Upgrade to API level 10 to use baz
2920```
2921
2922Query for this feature with `__has_attribute(diagnose_if)`.)reST";
2923
2924static const char AttrDoc_DisableSanitizerInstrumentation[] = R"reST(Use the `disable_sanitizer_instrumentation` attribute on a function,
2925Objective-C method, or global variable, to specify that no sanitizer
2926instrumentation should be applied.
2927
2928This is not the same as `__attribute__((no_sanitize(...)))`, which depending
2929on the tool may still insert instrumentation to prevent false positive reports.)reST";
2930
2931static const char AttrDoc_DisableTailCalls[] = R"reST(The `disable_tail_calls` attribute instructs the backend to not perform tail
2932call optimization inside the marked function.
2933
2934For example:
2935
2936```c
2937int callee(int);
2938
2939int foo(int a) __attribute__((disable_tail_calls)) {
2940 return callee(a); // This call is not tail-call optimized.
2941}
2942```
2943
2944Marking virtual functions as `disable_tail_calls` is legal.
2945
2946```c++
2947int callee(int);
2948
2949class Base {
2950public:
2951 [[clang::disable_tail_calls]] virtual int foo1() {
2952 return callee(); // This call is not tail-call optimized.
2953 }
2954};
2955
2956class Derived1 : public Base {
2957public:
2958 int foo1() override {
2959 return callee(); // This call is tail-call optimized.
2960 }
2961};
2962```)reST";
2963
2964static const char AttrDoc_EmptyBases[] = R"reST(The empty_bases attribute permits the compiler to utilize the
2965empty-base-optimization more frequently.
2966This attribute only applies to struct, class, and union types.
2967It is only supported when using the Microsoft C++ ABI.)reST";
2968
2969static const char AttrDoc_EnableIf[] = R"reST(:::{Note}
2970Some features of this attribute are experimental. The meaning of
2971multiple enable_if attributes on a single declaration is subject to change in
2972a future version of clang. Also, the ABI is not standardized and the name
2973mangling may change in future versions. To avoid that, use asm labels.
2974:::
2975
2976The `enable_if` attribute can be placed on function declarations to control
2977which overload is selected based on the values of the function's arguments.
2978When combined with the `overloadable` attribute, this feature is also
2979available in C.
2980
2981```c++
2982int isdigit(int c);
2983int 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")));
2984
2985void foo(char c) {
2986 isdigit(c);
2987 isdigit(10);
2988 isdigit(-10); // results in a compile-time error.
2989}
2990```
2991
2992The enable_if attribute takes two arguments, the first is an expression written
2993in terms of the function parameters, the second is a string explaining why this
2994overload candidate could not be selected to be displayed in diagnostics. The
2995expression is part of the function signature for the purposes of determining
2996whether it is a redeclaration (following the rules used when determining
2997whether a C++ template specialization is ODR-equivalent), but is not part of
2998the type.
2999
3000The enable_if expression is evaluated as if it were the body of a
3001bool-returning constexpr function declared with the arguments of the function
3002it is being applied to, then called with the parameters at the call site. If the
3003result is false or could not be determined through constant expression
3004evaluation, then this overload will not be chosen and the provided string may
3005be used in a diagnostic if the compile fails as a result.
3006
3007Because the enable_if expression is an unevaluated context, there are no global
3008state changes, nor the ability to pass information from the enable_if
3009expression to the function body. For example, suppose we want calls to
3010strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
3011strbuf) only if the size of strbuf can be determined:
3012
3013```c++
3014__attribute__((always_inline))
3015static inline size_t strnlen(const char *s, size_t maxlen)
3016 __attribute__((overloadable))
3017 __attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
3018 "chosen when the buffer size is known but 'maxlen' is not")))
3019{
3020 return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
3021}
3022```
3023
3024Multiple enable_if attributes may be applied to a single declaration. In this
3025case, the enable_if expressions are evaluated from left to right in the
3026following manner. First, the candidates whose enable_if expressions evaluate to
3027false or cannot be evaluated are discarded. If the remaining candidates do not
3028share ODR-equivalent enable_if expressions, the overload resolution is
3029ambiguous. Otherwise, enable_if overload resolution continues with the next
3030enable_if attribute on the candidates that have not been discarded and have
3031remaining enable_if attributes. In this way, we pick the most specific
3032overload out of a number of viable overloads using enable_if.
3033
3034```c++
3035void f() __attribute__((enable_if(true, ""))); // #1
3036void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2
3037
3038void g(int i, int j) __attribute__((enable_if(i, ""))); // #1
3039void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2
3040```
3041
3042In this example, a call to f() is always resolved to #2, as the first enable_if
3043expression is ODR-equivalent for both declarations, but #1 does not have another
3044enable_if expression to continue evaluating, so the next round of evaluation has
3045only a single candidate. In a call to g(1, 1), the call is ambiguous even though
3046#2 has more enable_if attributes, because the first enable_if expressions are
3047not ODR-equivalent.
3048
3049Query for this feature with `__has_attribute(enable_if)`.
3050
3051Note that functions with one or more `enable_if` attributes may not have
3052their address taken, unless all of the conditions specified by said
3053`enable_if` are constants that evaluate to `true`. For example:
3054
3055```c
3056const int TrueConstant = 1;
3057const int FalseConstant = 0;
3058int f(int a) __attribute__((enable_if(a > 0, "")));
3059int g(int a) __attribute__((enable_if(a == 0 || a != 0, "")));
3060int h(int a) __attribute__((enable_if(1, "")));
3061int i(int a) __attribute__((enable_if(TrueConstant, "")));
3062int j(int a) __attribute__((enable_if(FalseConstant, "")));
3063
3064void fn() {
3065 int (*ptr)(int);
3066 ptr = &f; // error: 'a > 0' is not always true
3067 ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant
3068 ptr = &h; // OK: 1 is a truthy constant
3069 ptr = &i; // OK: 'TrueConstant' is a truthy constant
3070 ptr = &j; // error: 'FalseConstant' is a constant, but not truthy
3071}
3072```
3073
3074Because `enable_if` evaluation happens during overload resolution,
3075`enable_if` may give unintuitive results when used with templates, depending
3076on when overloads are resolved. In the example below, clang will emit a
3077diagnostic about no viable overloads for `foo` in `bar`, but not in `baz`:
3078
3079```c++
3080double foo(int i) __attribute__((enable_if(i > 0, "")));
3081void *foo(int i) __attribute__((enable_if(i <= 0, "")));
3082template <int I>
3083auto bar() { return foo(I); }
3084
3085template <typename T>
3086auto baz() { return foo(T::number); }
3087
3088struct WithNumber { constexpr static int number = 1; };
3089void callThem() {
3090 bar<sizeof(WithNumber)>();
3091 baz<WithNumber>();
3092}
3093```
3094
3095This is because, in `bar`, `foo` is resolved prior to template
3096instantiation, so the value for `I` isn't known (thus, both `enable_if`
3097conditions for `foo` fail). However, in `baz`, `foo` is resolved during
3098template instantiation, so the value for `T::number` is known.)reST";
3099
3100static const char AttrDoc_EnforceTCB[] = R"reST(The `enforce_tcb` attribute can be placed on functions to enforce that a
3101trusted compute base (TCB) does not call out of the TCB. This generates a
3102warning every time a function not marked with an `enforce_tcb` attribute is
3103called from a function with the `enforce_tcb` attribute. A function may be a
3104part of multiple TCBs. Invocations through function pointers are currently
3105not checked. Builtins are considered to a part of every TCB.
3106
3107- `enforce_tcb(Name)` indicates that this function is a part of the TCB named `Name`)reST";
3108
3109static const char AttrDoc_EnforceTCBLeaf[] = R"reST(The `enforce_tcb_leaf` attribute satisfies the requirement enforced by
3110`enforce_tcb` for the marked function to be in the named TCB but does not
3111continue to check the functions called from within the leaf function.
3112
3113- `enforce_tcb_leaf(Name)` indicates that this function is a part of the TCB named `Name`)reST";
3114
3115static const char AttrDoc_EnumExtensibility[] = R"reST(Attribute `enum_extensibility` is used to distinguish between enum definitions
3116that are extensible and those that are not. The attribute can take either
3117`closed` or `open` as an argument. `closed` indicates a variable of the
3118enum type takes a value that corresponds to one of the enumerators listed in the
3119enum definition or, when the enum is annotated with `flag_enum`, a value that
3120can be constructed using values corresponding to the enumerators. `open`
3121indicates a variable of the enum type can take any values allowed by the
3122standard and instructs clang to be more lenient when issuing warnings.
3123
3124```c
3125enum __attribute__((enum_extensibility(closed))) ClosedEnum {
3126 A0, A1
3127};
3128
3129enum __attribute__((enum_extensibility(open))) OpenEnum {
3130 B0, B1
3131};
3132
3133enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum {
3134 C0 = 1 << 0, C1 = 1 << 1
3135};
3136
3137enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum {
3138 D0 = 1 << 0, D1 = 1 << 1
3139};
3140
3141void foo1() {
3142 enum ClosedEnum ce;
3143 enum OpenEnum oe;
3144 enum ClosedFlagEnum cfe;
3145 enum OpenFlagEnum ofe;
3146
3147 ce = A1; // no warnings
3148 ce = 100; // warning issued
3149 oe = B1; // no warnings
3150 oe = 100; // no warnings
3151 cfe = C0 | C1; // no warnings
3152 cfe = C0 | C1 | 4; // warning issued
3153 ofe = D0 | D1; // no warnings
3154 ofe = D0 | D1 | 4; // no warnings
3155}
3156```)reST";
3157
3158static const char AttrDoc_Error[] = R"reST(The `error` and `warning` function attributes can be used to specify a
3159custom diagnostic to be emitted when a call to such a function is not
3160eliminated via optimizations. This can be used to create compile time
3161assertions that depend on optimizations, while providing diagnostics
3162pointing to precise locations of the call site in the source.
3163
3164```c++
3165__attribute__((warning("oh no"))) void dontcall();
3166void foo() {
3167 if (someCompileTimeAssertionThatsTrue)
3168 dontcall(); // Warning
3169
3170 dontcall(); // Warning
3171
3172 if (someCompileTimeAssertionThatsFalse)
3173 dontcall(); // No Warning
3174 sizeof(dontcall()); // No Warning
3175}
3176```
3177
3178When the call occurs through inlined functions, the
3179`-fdiagnostics-show-inlining-chain` option can be used to show the
3180inlining chain that led to the call. This helps identify which call site
3181triggered the diagnostic when the attributed function is called from
3182multiple locations through inline functions.
3183
3184When enabled, this option automatically uses debug info for accurate source
3185locations if available (`-gline-directives-only` (implicitly enabled at
3186`-g1`) or higher), or falls back to a heuristic based on metadata tracking.
3187When falling back, a note is emitted suggesting `-gline-directives-only` for
3188more accurate locations.)reST";
3189
3190static const char AttrDoc_ExcludeFromExplicitInstantiation[] = R"reST(The `exclude_from_explicit_instantiation` attribute opts-out a member of a
3191class template from being part of explicit template instantiations of that
3192class template. This means that an explicit instantiation will not instantiate
3193members of the class template marked with the attribute, but also that code
3194where an extern template declaration of the enclosing class template is visible
3195will not take for granted that an external instantiation of the class template
3196would provide those members (which would otherwise be a link error, since the
3197explicit instantiation won't provide those members). For example, let's say we
3198don't want the `data()` method to be part of libc++'s ABI. To make sure it
3199is not exported from the dylib, we give it hidden visibility:
3200
3201```c++
3202// in <string>
3203template <class CharT>
3204class basic_string {
3205public:
3206 __attribute__((__visibility__("hidden")))
3207 const value_type* data() const noexcept { ... }
3208};
3209
3210template class basic_string<char>;
3211```
3212
3213Since an explicit template instantiation declaration for `basic_string<char>`
3214is provided, the compiler is free to assume that `basic_string<char>::data()`
3215will be provided by another translation unit, and it is free to produce an
3216external call to this function. However, since `data()` has hidden visibility
3217and the explicit template instantiation is provided in a shared library (as
3218opposed to simply another translation unit), `basic_string<char>::data()`
3219won't be found and a link error will ensue. This happens because the compiler
3220assumes that `basic_string<char>::data()` is part of the explicit template
3221instantiation declaration, when it really isn't. To tell the compiler that
3222`data()` is not part of the explicit template instantiation declaration, the
3223`exclude_from_explicit_instantiation` attribute can be used:
3224
3225```c++
3226// in <string>
3227template <class CharT>
3228class basic_string {
3229public:
3230 __attribute__((__visibility__("hidden")))
3231 __attribute__((exclude_from_explicit_instantiation))
3232 const value_type* data() const noexcept { ... }
3233};
3234
3235template class basic_string<char>;
3236```
3237
3238Now, the compiler won't assume that `basic_string<char>::data()` is provided
3239externally despite there being an explicit template instantiation declaration:
3240the compiler will implicitly instantiate `basic_string<char>::data()` in the
3241TUs where it is used.
3242
3243This attribute can be used on static and non-static member functions of class
3244templates, static data members of class templates and member classes of class
3245templates.
3246
3247**Interaction with \_\_declspec(dllexport/dllimport)**
3248
3249For a DLL platform (i.e., Windows), this attribute also means "this member will
3250never be exported or imported". Despite its name, this semantics applies to
3251implicit instantiations and non-template entities as well.
3252
3253```c++
3254// in <exception>
3255class __declspec(dllimport) nested_exception {
3256 ...
3257public:
3258 __attribute__((exclude_from_explicit_instantiation))
3259 exception_ptr nested_ptr() const noexcept { ... }
3260};
3261```
3262
3263In this case, `nested_exception::nested_ptr` will never be attempted to be
3264imported.)reST";
3265
3266static const char AttrDoc_ExplicitInit[] = R"reST(The `clang::require_explicit_initialization` attribute indicates that a
3267field of an aggregate must be initialized explicitly by the user when an object
3268of the aggregate type is constructed. The attribute supports both C and C++,
3269but its usage is invalid on non-aggregates.
3270
3271Note that this attribute is *not* a memory safety feature, and is *not* intended
3272to guard against use of uninitialized memory.
3273
3274Rather, it is intended for use in "parameter-objects", used to simulate,
3275for example, the passing of named parameters.
3276Except inside unevaluated contexts, the attribute generates a warning when
3277explicit initializers for such variables are not provided (this occurs
3278regardless of whether any in-class field initializers exist):
3279
3280```c++
3281struct Buffer {
3282 void *address [[clang::require_explicit_initialization]];
3283 size_t length [[clang::require_explicit_initialization]] = 0;
3284};
3285
3286struct ArrayIOParams {
3287 size_t count [[clang::require_explicit_initialization]];
3288 size_t element_size [[clang::require_explicit_initialization]];
3289 int flags = 0;
3290};
3291
3292size_t ReadArray(FILE *file, struct Buffer buffer,
3293 struct ArrayIOParams params);
3294
3295int main() {
3296 unsigned int buf[512];
3297 ReadArray(stdin, {
3298 buf
3299 // warning: field 'length' is not explicitly initialized
3300 }, {
3301 .count = sizeof(buf) / sizeof(*buf),
3302 // warning: field 'element_size' is not explicitly initialized
3303 // (Note that a missing initializer for 'flags' is not diagnosed, because
3304 // the field is not marked as requiring explicit initialization.)
3305 });
3306}
3307```)reST";
3308
3309static const char AttrDoc_ExtVectorType[] = R"reST(The `ext_vector_type(N)` attribute specifies that a type is a vector with N
3310elements, directly mapping to an LLVM vector type. Originally from OpenCL, it
3311allows element access the array subscript operator `[]`, `sN` where N is
3312a hexadecimal value, or `x, y, z, w` for graphics-style indexing.
3313This attribute enables efficient SIMD operations and is usable in
3314general-purpose code.
3315
3316```c++
3317template <typename T, uint32_t N>
3318constexpr T simd_reduce(T [[clang::ext_vector_type(N)]] v) {
3319 static_assert((N & (N - 1)) == 0, "N must be a power of two");
3320 if constexpr (N == 1)
3321 return v[0];
3322 else
3323 return simd_reduce<T, N / 2>(v.hi + v.lo);
3324}
3325```
3326
3327The vector type also supports swizzling up to sixteen elements. This can be done
3328using the object accessors. The OpenCL documentation lists all of the accepted
3329values.
3330
3331```c++
3332using f16_x16 = _Float16 __attribute__((ext_vector_type(16)));
3333
3334f16_x16 reverse(f16_x16 v) { return v.sfedcba9876543210; }
3335```
3336
3337See the OpenCL documentation for some more complete examples.)reST";
3338
3339static const char AttrDoc_ExternalSourceSymbol[] = R"reST(The `external_source_symbol` attribute specifies that a declaration originates
3340from an external source and describes the nature of that source.
3341
3342The fact that Clang is capable of recognizing declarations that were defined
3343externally can be used to provide better tooling support for mixed-language
3344projects or projects that rely on auto-generated code. For instance, an IDE that
3345uses Clang and that supports mixed-language projects can use this attribute to
3346provide a correct 'jump-to-definition' feature. For a concrete example,
3347consider a protocol that's defined in a Swift file:
3348
3349```swift
3350@objc public protocol SwiftProtocol {
3351 func method()
3352}
3353```
3354
3355This protocol can be used from Objective-C code by including a header file that
3356was generated by the Swift compiler. The declarations in that header can use
3357the `external_source_symbol` attribute to make Clang aware of the fact
3358that `SwiftProtocol` actually originates from a Swift module:
3359
3360```objc
3361__attribute__((external_source_symbol(language="Swift",defined_in="module")))
3362@protocol SwiftProtocol
3363@required
3364- (void) method;
3365@end
3366```
3367
3368Consequently, when 'jump-to-definition' is performed at a location that
3369references `SwiftProtocol`, the IDE can jump to the original definition in
3370the Swift source file rather than jumping to the Objective-C declaration in the
3371auto-generated header file.
3372
3373The `external_source_symbol` attribute is a comma-separated list that includes
3374clauses that describe the origin and the nature of the particular declaration.
3375Those clauses can be:
3376
3377language=*string-literal*
3378
3379: The name of the source language in which this declaration was defined.
3380
3381defined_in=*string-literal*
3382
3383: The name of the source container in which the declaration was defined. The
3384 exact definition of source container is language-specific, e.g. Swift's
3385 source containers are modules, so `defined_in` should specify the Swift
3386 module name.
3387
3388USR=*string-literal*
3389
3390: String that specifies a unified symbol resolution (USR) value for this
3391 declaration. USR string uniquely identifies this particular declaration, and
3392 is typically used when constructing an index of a codebase.
3393 The USR value in this attribute is expected to be generated by an external
3394 compiler that compiled the native declaration using its original source
3395 language. The exact format of the USR string and its other attributes
3396 are determined by the specification of this declaration's source language.
3397 When not specified, Clang's indexer will use the Clang USR for this symbol.
3398 User can query to see if Clang supports the use of the `USR` clause in
3399 the `external_source_symbol` attribute with
3400 `__has_attribute(external_source_symbol) >= 20230206`.
3401
3402generated_declaration
3403
3404: This declaration was automatically generated by some tool.
3405
3406The clauses can be specified in any order. The clauses that are listed above are
3407all optional, but the attribute has to have at least one clause.)reST";
3408
3409static const char AttrDoc_FallThrough[] = R"reST(The `fallthrough` (or `clang::fallthrough`) attribute is used
3410to annotate intentional fall-through
3411between switch labels. It can only be applied to a null statement placed at a
3412point of execution between any statement and the next switch label. It is
3413common to mark these places with a specific comment, but this attribute is
3414meant to replace comments with a more strict annotation, which can be checked
3415by the compiler. This attribute doesn't change semantics of the code and can
3416be used wherever an intended fall-through occurs. It is designed to mimic
3417control-flow statements like `break;`, so it can be placed in most places
3418where `break;` can, but only if there are no statements on the execution path
3419between it and the next switch label.
3420
3421By default, Clang does not warn on unannotated fallthrough from one `switch`
3422case to another. Diagnostics on fallthrough without a corresponding annotation
3423can be enabled with the `-Wimplicit-fallthrough` argument.
3424
3425Here is an example:
3426
3427```c++
3428// compile with -Wimplicit-fallthrough
3429switch (n) {
3430case 22:
3431case 33: // no warning: no statements between case labels
3432 f();
3433case 44: // warning: unannotated fall-through
3434 g();
3435 [[clang::fallthrough]];
3436case 55: // no warning
3437 if (x) {
3438 h();
3439 break;
3440 }
3441 else {
3442 i();
3443 [[clang::fallthrough]];
3444 }
3445case 66: // no warning
3446 p();
3447 [[clang::fallthrough]]; // warning: fallthrough annotation does not
3448 // directly precede case label
3449 q();
3450case 77: // warning: unannotated fall-through
3451 r();
3452}
3453```)reST";
3454
3455static const char AttrDoc_FastCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
3456function to use ECX and EDX as register parameters and clear parameters off of
3457the stack on return. This convention does not support variadic calls or
3458unprototyped functions in C, and has no effect on x86_64 targets. This calling
3459convention is supported primarily for compatibility with existing code. Users
3460seeking register parameters should use the `regparm` attribute, which does
3461not require callee-cleanup. See the documentation for [\_\_fastcall][__fastcall] on MSDN.
3462
3463[__fastcall]: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx)reST";
3464
3465static const char AttrDoc_Final[] = R"reST()reST";
3466
3467static const char AttrDoc_FlagEnum[] = R"reST(This attribute can be added to an enumerator to signal to the compiler that it
3468is intended to be used as a flag type. This will cause the compiler to assume
3469that the range of the type includes all of the values that you can get by
3470manipulating bits of the enumerator when issuing warnings.)reST";
3471
3472static const char AttrDoc_Flatten[] = R"reST(The `flatten` attribute causes calls within the attributed function to
3473be inlined unless it is impossible to do so, for example if the body of the
3474callee is unavailable or if the callee has the `noinline` attribute.)reST";
3475
3476static const char AttrDoc_Format[] = R"reST(Clang supports the `format` attribute, which indicates that the function
3477accepts (among other possibilities) a `printf` or `scanf`-like format string
3478and corresponding arguments or a `va_list` that contains these arguments.
3479
3480Please see [GCC documentation about format attribute](http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html) to find details
3481about attribute syntax.
3482
3483Clang implements two kinds of checks with this attribute.
3484
34851. Clang checks that the function with the `format` attribute is called with
3486 a format string that uses format specifiers that are allowed, and that
3487 arguments match the format string. This is the `-Wformat` warning, it is
3488 on by default.
3489
34902. Clang checks that the format string argument is a literal string. This is
3491 the `-Wformat-nonliteral` warning, it is off by default.
3492
3493 Clang implements this mostly the same way as GCC, but there is a difference
3494 for functions that accept a `va_list` argument (for example, `vprintf`).
3495 GCC does not emit `-Wformat-nonliteral` warning for calls to such
3496 functions. Clang does not warn if the format string comes from a function
3497 parameter, where the function is annotated with a compatible attribute,
3498 otherwise it warns. For example:
3499
3500 ```c
3501 __attribute__((__format__ (__scanf__, 1, 3)))
3502 void foo(const char* s, char *buf, ...) {
3503 va_list ap;
3504 va_start(ap, buf);
3505
3506 vprintf(s, ap); // warning: format string is not a string literal
3507 }
3508 ```
3509
3510 In this case we warn because `s` contains a format string for a
3511 `scanf`-like function, but it is passed to a `printf`-like function.
3512
3513 If the attribute is removed, clang still warns, because the format string is
3514 not a string literal.
3515
3516 Another example:
3517
3518 ```c
3519 __attribute__((__format__ (__printf__, 1, 3)))
3520 void foo(const char* s, char *buf, ...) {
3521 va_list ap;
3522 va_start(ap, buf);
3523
3524 vprintf(s, ap); // warning
3525 }
3526 ```
3527
3528 In this case Clang does not warn because the format string `s` and
3529 the corresponding arguments are annotated. If the arguments are
3530 incorrect, the caller of `foo` will receive a warning.
3531
3532As an extension to GCC's behavior, Clang accepts the `format` attribute on
3533non-variadic functions. Clang checks non-variadic format functions for the same
3534classes of issues that can be found on variadic functions, as controlled by the
3535same warning flags, except that the types of formatted arguments is forced by
3536the function signature. For example:
3537
3538```c
3539__attribute__((__format__(__printf__, 1, 2)))
3540void fmt(const char *s, const char *a, int b);
3541
3542void bar(void) {
3543 fmt("%s %i", "hello", 123); // OK
3544 fmt("%i %g", "hello", 123); // warning: arguments don't match format
3545 extern const char *fmt;
3546 fmt(fmt, "hello", 123); // warning: format string is not a string literal
3547}
3548```
3549
3550When using the format attribute on a variadic function, the first data parameter
3551\_must\_ be the index of the ellipsis in the parameter list. Clang will generate
3552a diagnostic otherwise, as it wouldn't be possible to forward that argument list
3553to `printf`-family functions. For instance, this is an error:
3554
3555```c
3556__attribute__((__format__(__printf__, 1, 2)))
3557void fmt(const char *s, int b, ...);
3558// ^ error: format attribute parameter 3 is out of bounds
3559// (must be __printf__, 1, 3)
3560```
3561
3562Using the `format` attribute on a non-variadic function emits a GCC
3563compatibility diagnostic.)reST";
3564
3565static const char AttrDoc_FormatArg[] = R"reST(No documentation.)reST";
3566
3567static const char AttrDoc_FormatMatches[] = R"reST(The `format` attribute is the basis for the enforcement of diagnostics in the
3568`-Wformat` family, but it only handles the case where the format string is
3569passed along with the arguments it is going to format. It cannot handle the case
3570where the format string and the format arguments are passed separately from each
3571other. For instance:
3572
3573```c
3574static const char *first_name;
3575static double todays_temperature;
3576static int wind_speed;
3577
3578void say_hi(const char *fmt) {
3579 printf(fmt, first_name, todays_temperature);
3580 // ^ warning: format string is not a string literal
3581 printf(fmt, first_name, wind_speed);
3582 // ^ warning: format string is not a string literal
3583}
3584
3585int main() {
3586 say_hi("hello %s, it is %g degrees outside");
3587 say_hi("hello %s, it is %d degrees outside!");
3588 // ^ no diagnostic, but %d cannot format doubles
3589}
3590```
3591
3592In this example, `fmt` is expected to format a `const char *` and a
3593`double`, but these values are not passed to `say_hi`. Without the
3594`format` attribute (which cannot apply in this case), the -Wformat-nonliteral
3595diagnostic unnecessarily triggers in the body of `say_hi`, and incorrect
3596`say_hi` call sites do not trigger a diagnostic.
3597
3598To complement the `format` attribute, Clang also defines the
3599`format_matches` attribute. Its syntax is similar to the `format`
3600attribute's, but instead of taking the index of the first formatted value
3601argument, it takes a C string literal with the expected specifiers:
3602
3603```c
3604static const char *first_name;
3605static double todays_temperature;
3606static int wind_speed;
3607
3608__attribute__((__format_matches__(printf, 1, "%s %g")))
3609void say_hi(const char *fmt) {
3610 printf(fmt, first_name, todays_temperature); // no dignostic
3611 printf(fmt, first_name, wind_speed); // warning: format specifies type 'int' but the argument has type 'double'
3612}
3613
3614int main() {
3615 say_hi("hello %s, it is %g degrees outside");
3616 say_hi("it is %g degrees outside, have a good day %s!");
3617 // warning: format specifies 'double' where 'const char *' is required
3618 // warning: format specifies 'const char *' where 'double' is required
3619}
3620```
3621
3622The third argument to `format_matches` is expected to evaluate to a **C string
3623literal** even when the format string would normally be a different type for the
3624given flavor, like a `CFStringRef` or a `NSString *`.
3625
3626The only requirement on the format string literal is that it has specifiers
3627that are compatible with the arguments that will be used. It can contain
3628arbitrary non-format characters. For instance, for the purposes of compile-time
3629validation, `"%s scored %g%% on her test"` and `"%s%g"` are interchangeable
3630as the format string argument. As a means of self-documentation, users may
3631prefer the former when it provides a useful example of an expected format
3632string.
3633
3634In the implementation of a function with the `format_matches` attribute,
3635format verification works as if the format string was identical to the one
3636specified in the attribute.
3637
3638```c
3639__attribute__((__format_matches__(printf, 1, "%s %g")))
3640void say_hi(const char *fmt) {
3641 printf(fmt, "person", 546);
3642 // ^ warning: format specifies type 'double' but the
3643 // argument has type 'int'
3644 // note: format string is defined here:
3645 // __attribute__((__format_matches__(printf, 1, "%s %g")))
3646 // ^~
3647}
3648```
3649
3650At the call sites of functions with the `format_matches` attribute, format
3651verification instead compares the two format strings to evaluate their
3652equivalence. Each format flavor defines equivalence between format specifiers.
3653Generally speaking, two specifiers are equivalent if they format the same type.
3654For instance, in the `printf` flavor, `%2i` and `%-0.5d` are compatible.
3655When `-Wformat-signedness` is disabled, `%d` and `%u` are compatible. For
3656a negative example, `%ld` is incompatible with `%d`.
3657
3658Do note the following un-obvious cases:
3659
3660- Passing `NULL` as the format string does not trigger format diagnostics.
3661- When the format string is not NULL, it cannot \_miss\_ specifiers, even in
3662 trailing positions. For instance, `%d` is not accepted when the required
3663 format is `%d %d %d`.
3664- While checks for the `format` attribute tolerate sone size mismatches
3665 that standard argument promotion renders immaterial (such as formatting an
3666 `int` with `%hhd`, which specifies a `char`-sized integer), checks for
3667 `format_matches` require specified argument sizes to match exactly.
3668- Format strings expecting a variable modifier (such as `%*s`) are
3669 incompatible with format strings that would itemize the variable modifiers
3670 (such as `%i %s`), even if the two specify ABI-compatible argument lists.
3671- All pointer specifiers, modifiers aside, are mutually incompatible. For
3672 instance, `%s` is not compatible with `%p`, and `%p` is not compatible
3673 with `%n`, and `%hhn` is incompatible with `%s`, even if the pointers
3674 are ABI-compatible or identical on the selected platform. However, `%0.5s`
3675 is compatible with `%s`, since the difference only exists in modifier flags.
3676 This is not overridable with `-Wformat-pedantic` or its inverse, which
3677 control similar behavior in `-Wformat`.
3678
3679At this time, clang implements `format_matches` only for format types in the
3680`printf` family. This includes variants such as Apple's NSString format and
3681the FreeBSD `kprintf`, but excludes `scanf`. Using a known but unsupported
3682format silently fails in order to be compatible with other implementations that
3683would support these formats.)reST";
3684
3685static const char AttrDoc_FunctionReturnThunks[] = R"reST(The attribute `function_return` can replace return instructions with jumps to
3686target-specific symbols. This attribute supports 2 possible values,
3687corresponding to the values supported by the `-mfunction-return=` command
3688line flag:
3689
3690- `__attribute__((function_return("keep")))` to disable related transforms.
3691 This is useful for undoing global setting from `-mfunction-return=` locally
3692 for individual functions.
3693- `__attribute__((function_return("thunk-extern")))` to replace returns with
3694 jumps, while NOT emitting the thunk.
3695
3696The values `thunk` and `thunk-inline` from GCC are not supported.
3697
3698The symbol used for `thunk-extern` is target specific:
3699\* X86: `__x86_return_thunk`
3700
3701As such, this function attribute is currently only supported on X86 targets.)reST";
3702
3703static const char AttrDoc_GCCStruct[] = R"reST(The `ms_struct` and `gcc_struct` attributes request the compiler to enter a
3704special record layout compatibility mode which mimics the layout of Microsoft or
3705Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the
3706requested ABI, the attribute does nothing. However, if it does not, annotated
3707structure or class is laid out in a special compatibility mode, which slightly
3708changes offsets for fields and bit-fields. The intention is to match the layout
3709of the requested ABI for structures which only use C features.
3710
3711Note that the default behavior can be controlled by `-mms-bitfields` and
3712`-mno-ms-bitfields` switches and via `#pragma ms_struct`.
3713
3714The primary difference is for bitfields, where the MS variant only packs
3715adjacent fields into the same allocation unit if they have integral types
3716of the same size, while the GCC/Itanium variant packs all fields in a bitfield
3717tightly.)reST";
3718
3719static const char AttrDoc_GNUInline[] = R"reST(The `gnu_inline` changes the meaning of `extern inline` to use GNU inline
3720semantics, meaning:
3721
3722- If any declaration that is declared `inline` is not declared `extern`,
3723 then the `inline` keyword is just a hint. In particular, an out-of-line
3724 definition is still emitted for a function with external linkage, even if all
3725 call sites are inlined, unlike in C99 and C++ inline semantics.
3726- If all declarations that are declared `inline` are also declared
3727 `extern`, then the function body is present only for inlining and no
3728 out-of-line version is emitted.
3729
3730Some important consequences: `static inline` emits an out-of-line
3731version if needed, a plain `inline` definition emits an out-of-line version
3732always, and an `extern inline` definition (in a header) followed by a
3733(non-`extern`) `inline` declaration in a source file emits an out-of-line
3734version of the function in that source file but provides the function body for
3735inlining to all includers of the header.
3736
3737Either `__GNUC_GNU_INLINE__` (GNU inline semantics) or
3738`__GNUC_STDC_INLINE__` (C99 semantics) will be defined (they are mutually
3739exclusive). If `__GNUC_STDC_INLINE__` is defined, then the `gnu_inline`
3740function attribute can be used to get GNU inline semantics on a per function
3741basis. If `__GNUC_GNU_INLINE__` is defined, then the translation unit is
3742already being compiled with GNU inline semantics as the implied default. It is
3743unspecified which macro is defined in a C++ compilation.
3744
3745GNU inline semantics are the default behavior with `-std=gnu89`,
3746`-std=c89`, `-fgnu89-inline`, or `-std=iso9899:199409`.)reST";
3747
3748static const char AttrDoc_GuardedBy[] = R"reST(No documentation.)reST";
3749
3750static const char AttrDoc_GuardedVar[] = R"reST(No documentation.)reST";
3751
3752static const char AttrDoc_HIPManaged[] = R"reST(The `__managed__` attribute can be applied to a global variable declaration in HIP.
3753A managed variable is emitted as an undefined global symbol in the device binary and is
3754registered by `__hipRegisterManagedVar` in init functions. The HIP runtime allocates
3755managed memory and uses it to define the symbol when loading the device binary.
3756A managed variable can be accessed in both device and host code.)reST";
3757
3758static const char AttrDoc_HLSLAppliedSemantic[] = R"reST()reST";
3759
3760static const char AttrDoc_HLSLAssociatedResourceDecl[] = R"reST()reST";
3761
3762static const char AttrDoc_HLSLColumnMajor[] = R"reST(The `row_major` and `column_major` keywords specify the memory layout
3763of an HLSL matrix type.
3764
3765- `row_major`: Matrices are stored in memory row-by-row.
3766- `column_major`: Matrices are stored in memory column-by-column (default).
3767
3768Example:
3769
3770```hlsl
3771row_major float2x2 myMatrix;
3772```)reST";
3773
3774static const char AttrDoc_HLSLContainedType[] = R"reST(The ``hlsl::contained_type`` attribute specifies the type of the HLSL resource
3775represented by a member variable of type ``__hlsl_resource_t``.
3776
3777This attribute is only valid for resource handles, and is an implementation
3778detail of clang's HLSL implementation. For more information see `HLSL Resource
3779Types`_
3780
3781.. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST";
3782
3783static const char AttrDoc_HLSLControlFlowHint[] = R"reST(The ``branch`` and ``flatten`` attributes can be applied to *if* and *switch*
3784statements in the HLSL language mode to provide hints for how the backend
3785should execute them.
3786
3787- ``branch`` means that control flow is preferred. The condition should be
3788 evaluated first and we should only execute the block guarded by it.
3789
3790- ``flatten`` means that control flow should be avoided. All blocks should be
3791 executed and variables that are modified should be conditionally assigned.
3792
3793These control flow hints are preserved through the compilation and emitted in a
3794backend-specific way.
3795
3796For details, see the Direct3D documentation for `if Statement`_ and `switch Statement`_.
3797
3798.. _`if Statement`: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-if
3799.. _`switch Statement`: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-switchhttps://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-switch)reST";
3800
3801static const char AttrDoc_HLSLGroupSharedAddressSpace[] = R"reST(HLSL enables threads of a compute shader to exchange values via shared memory.
3802HLSL provides barrier primitives such as GroupMemoryBarrierWithGroupSync,
3803and so on to ensure the correct ordering of reads and writes to shared memory
3804in the shader and to avoid data races.
3805Here's an example to declare a groupshared variable.
3806
3807```c++
3808groupshared GSData data[5*5*1];
3809```
3810
3811The full documentation is available here: <https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-syntax#group-shared>)reST";
3812
3813static const char AttrDoc_HLSLIsArray[] = R"reST(The ``hlsl::is_array`` attribute specifies that the HLSL resource represented
3814by a member variable of type ``__hlsl_resource_t`` has array dimensions.
3815
3816This attribute is only valid for resource handles, and is an implementation
3817detail of clang's HLSL implementation. For more information see `HLSL Resource
3818Types`_
3819
3820.. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST";
3821
3822static const char AttrDoc_HLSLIsCounter[] = R"reST(The ``hlsl::is_counter`` attribute specifies that the HLSL resource represented
3823by a member variable of type ``__hlsl_resource_t`` is a counter buffer.
3824
3825This attribute is only valid for resource handles, and is an implementation
3826detail of clang's HLSL implementation. For more information see `HLSL Resource
3827Types`_
3828
3829.. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST";
3830
3831static const char AttrDoc_HLSLIsMultiSampled[] = R"reST(The ``hlsl::is_array`` attribute specifies that the HLSL resource represented
3832by a member variable of type ``__hlsl_resource_t`` is multisampled.
3833
3834This attribute is only valid for resource handles, and is an implementation
3835detail of clang's HLSL implementation. For more information see `HLSL Resource
3836Types`_
3837
3838.. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST";
3839
3840static const char AttrDoc_HLSLIsROV[] = R"reST(The ``hlsl::is_rov`` attribute specifies that the HLSL resource represented by
3841a member variable of type ``__hlsl_resource_t`` is a rasterizer ordered view.
3842
3843This attribute is only valid for resource handles, and is an implementation
3844detail of clang's HLSL implementation. For more information see `HLSL Resource
3845Types`_
3846
3847.. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST";
3848
3849static const char AttrDoc_HLSLLoopHint[] = R"reST(The `[loop]` directive allows loop optimization hints to be
3850specified for the subsequent loop. The directive allows unrolling to
3851be disabled and is not compatible with [unroll(x)].
3852
3853Specifying the parameter, `[loop]`, directs the
3854unroller to not unroll the loop.
3855
3856```hlsl
3857[loop]
3858for (...) {
3859 ...
3860}
3861```
3862
3863```hlsl
3864[loop]
3865while (...) {
3866 ...
3867}
3868```
3869
3870```hlsl
3871[loop]
3872do {
3873 ...
3874} while (...)
3875```
3876
3877See [hlsl loop extensions](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-for)
3878for details.)reST";
3879
3880static const char AttrDoc_HLSLNumThreads[] = R"reST(The `numthreads` attribute applies to HLSL shaders where explcit thread counts
3881are required. The `X`, `Y`, and `Z` values provided to the attribute
3882dictate the thread id. Total number of threads executed is `X * Y * Z`.
3883
3884The full documentation is available here: <https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-numthreads>)reST";
3885
3886static const char AttrDoc_HLSLPackOffset[] = R"reST(The packoffset attribute is used to change the layout of a cbuffer.
3887Attribute spelling in HLSL is: `packoffset( c[Subcomponent][.component] )`.
3888A subcomponent is a register number, which is an integer. A component is in the form of [.xyzw].
3889
3890Examples:
3891
3892```hlsl
3893cbuffer A {
3894 float3 a : packoffset(c0.y);
3895 float4 b : packoffset(c4);
3896}
3897```
3898
3899The full documentation is available here: <https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-packoffset>)reST";
3900
3901static const char AttrDoc_HLSLParamModifier[] = R"reST(HLSL function parameters are passed by value. Parameter declarations support
3902three qualifiers to denote parameter passing behavior. The three qualifiers are
3903`in`, `out` and `inout`.
3904
3905Parameters annotated with `in` or with no annotation are passed by value from
3906the caller to the callee.
3907
3908Parameters annotated with `out` are written to the argument after the callee
3909returns (Note: arguments values passed into `out` parameters *are not* copied
3910into the callee).
3911
3912Parameters annotated with `inout` are copied into the callee via a temporary,
3913and copied back to the argument after the callee returns.)reST";
3914
3915static const char AttrDoc_HLSLParsedSemantic[] = R"reST()reST";
3916
3917static const char AttrDoc_HLSLRawBuffer[] = R"reST(The ``hlsl::raw_buffer`` attribute specifies that the HLSL resource represented
3918by a member variable of type ``__hlsl_resource_t`` has raw buffer semantics.
3919
3920This attribute is only valid for resource handles, and is an implementation
3921detail of clang's HLSL implementation. For more information see `HLSL Resource
3922Types`_
3923
3924.. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST";
3925
3926static const char AttrDoc_HLSLResourceBinding[] = R"reST(The resource binding attribute sets the virtual register and logical register space for a resource.
3927Attribute spelling in HLSL is: `register(slot [, space])`.
3928`slot` takes the format `[type][number]`,
3929where `type` is a single character specifying the resource type and `number` is the virtual register number.
3930
3931Register types are:
3932t for shader resource views (SRV),
3933s for samplers,
3934u for unordered access views (UAV),
3935b for constant buffer views (CBV).
3936
3937Register space is specified in the format `space[number]` and defaults to `space0` if omitted.
3938Here're resource binding examples with and without space:
3939
3940```hlsl
3941RWBuffer<float> Uav : register(u3, space1);
3942Buffer<float> Buf : register(t1);
3943```
3944
3945The full documentation is available here: <https://docs.microsoft.com/en-us/windows/win32/direct3d12/resource-binding-in-hlsl>)reST";
3946
3947static const char AttrDoc_HLSLResourceClass[] = R"reST(The ``hlsl::resource_class`` attribute specifies the resource class of the HLSL
3948resource represented by a member variable of type ``__hlsl_resource_t``,
3949declaring it to be an SRV, UAV, CBuffer, or Sampler resource.
3950
3951This attribute is only valid for resource handles, and is an implementation
3952detail of clang's HLSL implementation. For more information see `HLSL Resource
3953Types`_
3954
3955.. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST";
3956
3957static const char AttrDoc_HLSLResourceDimension[] = R"reST(The ``hlsl::dimension`` attribute specifies the dimensions of the HLSL resource
3958represented by a member variable of type ``__hlsl_resource_t``, declaring the
3959resource to have Unknown, 1D, 2D, 3D, or Cube dimension.
3960
3961This attribute is only valid for resource handles, and is an implementation
3962detail of clang's HLSL implementation. For more information see `HLSL Resource
3963Types`_
3964
3965.. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST";
3966
3967static const char AttrDoc_HLSLRowMajor[] = R"reST(The `row_major` and `column_major` keywords specify the memory layout
3968of an HLSL matrix type.
3969
3970- `row_major`: Matrices are stored in memory row-by-row.
3971- `column_major`: Matrices are stored in memory column-by-column (default).
3972
3973Example:
3974
3975```hlsl
3976row_major float2x2 myMatrix;
3977```)reST";
3978
3979static const char AttrDoc_HLSLShader[] = R"reST(The `shader` type attribute applies to HLSL shader entry functions to
3980identify the shader type for the entry function.
3981The syntax is:
3982
3983```text
3984``[shader(string-literal)]``
3985```
3986
3987where the string literal is one of: "pixel", "vertex", "geometry", "hull",
3988"domain", "compute", "raygeneration", "intersection", "anyhit", "closesthit",
3989"miss", "callable", "mesh", "amplification". Normally the shader type is set
3990by shader target with the `-T` option like `-Tps_6_1`. When compiling to a
3991library target like `lib_6_3`, the shader type attribute can help the
3992compiler to identify the shader type. It is mostly used by Raytracing shaders
3993where shaders must be compiled into a library and linked at runtime.)reST";
3994
3995static const char AttrDoc_HLSLUnparsedSemantic[] = R"reST()reST";
3996
3997static const char AttrDoc_HLSLVkBinding[] = R"reST(The `[[vk::binding]]` attribute allows you to explicitly specify the descriptor
3998set and binding for a resource when targeting SPIR-V. This is particularly
3999useful when you need different bindings for SPIR-V and DXIL, as the `register`
4000attribute can be used for DXIL-specific bindings.
4001
4002The attribute takes two integer arguments: the binding and the descriptor set.
4003The descriptor set is optional and defaults to 0 if not provided.
4004
4005```c++
4006// A structured buffer with binding 23 in descriptor set 102.
4007[[vk::binding(23, 102)]] StructuredBuffer<float> Buf;
4008
4009// A structured buffer with binding 14 in descriptor set 0.
4010[[vk::binding(14)]] StructuredBuffer<float> Buf2;
4011
4012// A cbuffer with binding 1 in descriptor set 2.
4013[[vk::binding(1, 2)]] cbuffer MyCBuffer {
4014 float4x4 worldViewProj;
4015};
4016```)reST";
4017
4018static const char AttrDoc_HLSLVkConstantId[] = R"reST(The `vk::constant_id` attribute specifies the id for a SPIR-V specialization
4019constant. The attribute applies to const global scalar variables. The variable must be initialized with a C++11 constexpr.
4020In SPIR-V, the
4021variable will be replaced with an `OpSpecConstant` with the given id.
4022The syntax is:
4023
4024```text
4025``[[vk::constant_id(<Id>)]] const T Name = <Init>``
4026```)reST";
4027
4028static const char AttrDoc_HLSLVkExtBuiltinInput[] = R"reST(Vulkan shaders have `Input` builtins. Those variables are externally
4029initialized by the driver/pipeline, but each copy is private to the current
4030lane.
4031
4032Those builtins can be declared using the `[[vk::ext_builtin_input]]` attribute
4033like follows:
4034
4035```c++
4036[[vk::ext_builtin_input(/* WorkgroupId */ 26)]]
4037static const uint3 groupid;
4038```
4039
4040This variable will be lowered into a module-level variable, with the `Input`
4041storage class, and the `BuiltIn 26` decoration.
4042
4043The full documentation for this inline SPIR-V attribute can be found here:
4044<https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md>)reST";
4045
4046static const char AttrDoc_HLSLVkExtBuiltinOutput[] = R"reST(Vulkan shaders have `Output` builtins. Those variables are externally
4047visible to the driver/pipeline, but each copy is private to the current
4048lane.
4049
4050Those builtins can be declared using the `[[vk::ext_builtin_output]]`
4051attribute like follows:
4052
4053```c++
4054[[vk::ext_builtin_output(/* Position */ 0)]]
4055static float4 position;
4056```
4057
4058This variable will be lowered into a module-level variable, with the `Output`
4059storage class, and the `BuiltIn 0` decoration.
4060
4061The full documentation for this inline SPIR-V attribute can be found here:
4062<https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md>)reST";
4063
4064static const char AttrDoc_HLSLVkLocation[] = R"reST(Attribute used for specifying the location number for the stage input/output
4065variables. Allowed on function parameters, function returns, and struct
4066fields. This parameter has no effect when used outside of an entrypoint
4067parameter/parameter field/return value.
4068
4069This attribute maps to the 'Location' SPIR-V decoration.)reST";
4070
4071static const char AttrDoc_HLSLVkPushConstant[] = R"reST(Vulkan shaders have `PushConstants`
4072
4073The `[[vk::push_constant]]` attribute allows you to declare this
4074global variable as a push constant when targeting Vulkan.
4075This attribute is ignored otherwise.
4076
4077This attribute must be applied to the variable, not underlying type.
4078The variable type must be a struct, per the requirements of Vulkan, "there
4079must be no more than one push constant block statically used per shader entry
4080point.")reST";
4081
4082static const char AttrDoc_HLSLWaveSize[] = R"reST(The `WaveSize` attribute specify a wave size on a shader entry point in order
4083to indicate either that a shader depends on or strongly prefers a specific wave
4084size.
4085There're 2 versions of the attribute: `WaveSize` and `RangedWaveSize`.
4086The syntax for `WaveSize` is:
4087
4088```text
4089``[WaveSize(<numLanes>)]``
4090```
4091
4092The allowed wave sizes that an HLSL shader may specify are the powers of 2
4093between 4 and 128, inclusive.
4094In other words, the set: [4, 8, 16, 32, 64, 128].
4095
4096The syntax for `RangedWaveSize` is:
4097
4098```text
4099``[WaveSize(<minWaveSize>, <maxWaveSize>, [prefWaveSize])]``
4100```
4101
4102Where minWaveSize is the minimum wave size supported by the shader representing
4103the beginning of the allowed range, maxWaveSize is the maximum wave size
4104supported by the shader representing the end of the allowed range, and
4105prefWaveSize is the optional preferred wave size representing the size expected
4106to be the most optimal for this shader.
4107
4108`WaveSize` is available for HLSL shader model 6.6 and later.
4109`RangedWaveSize` available for HLSL shader model 6.8 and later.
4110
4111The full documentation is available here: <https://microsoft.github.io/DirectX-Specs/d3d/HLSL_SM_6_6_WaveSize.html>
4112and <https://microsoft.github.io/hlsl-specs/proposals/0013-wave-size-range.html>)reST";
4113
4114static const char AttrDoc_Hot[] = R"reST(`__attribute__((hot))` marks a function as hot, as a manual alternative to PGO hotness data.
4115If PGO data is available, the annotation `__attribute__((hot))` overrides the profile count based hotness (unlike `__attribute__((cold))`).)reST";
4116
4117static const char AttrDoc_HybridPatchable[] = R"reST(The `hybrid_patchable` attribute declares an ARM64EC function with an additional
4118x86-64 thunk, which may be patched at runtime.
4119
4120For more information see
4121[ARM64EC ABI documentation](https://learn.microsoft.com/en-us/windows/arm/arm64ec-abi).)reST";
4122
4123static const char AttrDoc_IBAction[] = R"reST(No documentation.)reST";
4124
4125static const char AttrDoc_IBOutlet[] = R"reST(No documentation.)reST";
4126
4127static const char AttrDoc_IBOutletCollection[] = R"reST(No documentation.)reST";
4128
4129static const char AttrDoc_IFunc[] = R"reST(`__attribute__((ifunc("resolver")))` is used to mark that the address of a
4130declaration should be resolved at runtime by calling a resolver function.
4131
4132The symbol name of the resolver function is given in quotes. A function with
4133this name (after mangling) must be defined in the current translation unit; it
4134may be `static`. The resolver function should return a pointer.
4135
4136The `ifunc` attribute may only be used on a function declaration. A function
4137declaration with an `ifunc` attribute is considered to be a definition of the
4138declared entity. The entity must not have weak linkage; for example, in C++,
4139it cannot be applied to a declaration if a definition at that location would be
4140considered inline.
4141
4142Not all targets support this attribute:
4143
4144- ELF target support depends on both the linker and runtime linker, and is
4145 available in at least lld 4.0 and later, binutils 2.20.1 and later, glibc
4146 v2.11.1 and later, and FreeBSD 9.1 and later.
4147- Mach-O targets support it, but with slightly different semantics: the resolver
4148 is run at first call, instead of at load time by the runtime linker.
4149- Windows target supports it on AArch64, but with different semantics: the
4150 `ifunc` is replaced with a global function pointer, and the call is replaced
4151 with an indirect call. The function pointer is initialized by a constructor
4152 that calls the resolver.
4153- Baremetal target supports it on AVR.
4154- AIX/XCOFF supports it via a compiler-only solution. An ifunc appears as a
4155 regular function (has an entry point `.foo[PR]` and a function descriptor
4156 `foo[DS]`). The entry point is a stub that branches to the function address
4157 in the descriptor, and the descriptor is initialized via a constructor
4158 function (`__init_ifuncs`) that is linked into every shared object and
4159 executable. `__init_ifuncs` calls the resolver of each ifunc and stores the
4160 result in the corresponding descriptor.
4161- Other targets currently do not support this attribute.)reST";
4162
4163static const char AttrDoc_InferredNoReturn[] = R"reST()reST";
4164
4165static const char AttrDoc_InitPriority[] = R"reST(In C++, the order in which global variables are initialized across translation
4166units is unspecified, unlike the ordering within a single translation unit. The
4167`init_priority` attribute allows you to specify a relative ordering for the
4168initialization of objects declared at namespace scope in C++ within a single
4169linked image on supported platforms. The priority is given as an integer constant
4170expression between 101 and 65535 (inclusive). Priorities outside of that range are
4171reserved for use by the implementation. A lower value indicates a higher priority
4172of initialization. Note that only the relative ordering of values is important.
4173For example:
4174
4175```c++
4176struct SomeType { SomeType(); };
4177__attribute__((init_priority(200))) SomeType Obj1;
4178__attribute__((init_priority(101))) SomeType Obj2;
4179```
4180
4181`Obj2` will be initialized *before* `Obj1` despite the usual order of
4182initialization being the opposite.
4183
4184Note that this attribute does not control the initialization order of objects
4185across final linked image boundaries like shared objects and executables.
4186
4187On Windows, `init_seg(compiler)` is represented with a priority of 200 and
4188`init_seg(library)` is represented with a priority of 400. `init_seg(user)`
4189uses the default 65535 priority.
4190
4191On MachO platforms, this attribute also does not control the order of initialization
4192across translation units, where it only affects the order within a single TU.
4193
4194This attribute is only supported for C++ and Objective-C++ and is ignored in
4195other language modes.)reST";
4196
4197static const char AttrDoc_InitSeg[] = R"reST(The attribute applied by `pragma init_seg()` controls the section into
4198which global initialization function pointers are emitted. It is only
4199available with `-fms-extensions`. Typically, this function pointer is
4200emitted into `.CRT$XCU` on Windows. The user can change the order of
4201initialization by using a different section name with the same
4202`.CRT$XC` prefix and a suffix that sorts lexicographically before or
4203after the standard `.CRT$XCU` sections. See the [init_seg][init_seg]
4204documentation on MSDN for more information.
4205
4206[init_seg]: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx)reST";
4207
4208static const char AttrDoc_IntelOclBicc[] = R"reST(No documentation.)reST";
4209
4210static const char AttrDoc_InternalLinkage[] = R"reST(The `internal_linkage` attribute changes the linkage type of the declaration
4211to internal. This is similar to C-style `static`, but can be used on classes
4212and class methods. When applied to a class definition, this attribute affects
4213all methods and static data members of that class. This can be used to contain
4214the ABI of a C++ library by excluding unwanted class methods from the export
4215tables.)reST";
4216
4217static const char AttrDoc_LTOVisibilityPublic[] = R"reST(See {doc}`LTOVisibility`.)reST";
4218
4219static const char AttrDoc_LayoutVersion[] = R"reST(The layout_version attribute requests that the compiler utilize the class
4220layout rules of a particular compiler version.
4221This attribute only applies to struct, class, and union types.
4222It is only supported when using the Microsoft C++ ABI.)reST";
4223
4224static const char AttrDoc_Leaf[] = R"reST(The `leaf` attribute is used as a compiler hint to improve dataflow analysis
4225in library functions. Functions marked with the `leaf` attribute are not allowed
4226to jump back into the caller's translation unit, whether through invoking a
4227callback function, an external function call, use of `longjmp`, or other means.
4228Therefore, they cannot use or modify any data that does not escape the caller function's
4229compilation unit.
4230
4231For more information see
4232`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html>`)reST";
4233
4234static const char AttrDoc_LifetimeBound[] = R"reST(The `lifetimebound` attribute on a function parameter or implicit object
4235parameter indicates that objects that are referred to by that parameter may
4236also be referred to by the return value of the annotated function (or, for a
4237parameter of a constructor, by the value of the constructed object).
4238
4239By default, a reference is considered to refer to its referenced object, a
4240pointer is considered to refer to its pointee, a `std::initializer_list<T>`
4241is considered to refer to its underlying array, and aggregates (arrays and
4242simple `struct`s) are considered to refer to all objects that their
4243transitive subobjects refer to.
4244
4245Clang warns if it is able to detect that an object or reference refers to
4246another object with a shorter lifetime. For example, Clang will warn if a
4247function returns a reference to a local variable, or if a reference is bound to
4248a temporary object whose lifetime is not extended. By using the
4249`lifetimebound` attribute, this determination can be extended to look through
4250user-declared functions. For example:
4251
4252```c++
4253#include <map>
4254#include <string>
4255
4256using namespace std::literals;
4257
4258// Returns m[key] if key is present, or default_value if not.
4259template<typename T, typename U>
4260const U &get_or_default(const std::map<T, U> &m [[clang::lifetimebound]],
4261 const T &key, /* note, not lifetimebound */
4262 const U &default_value [[clang::lifetimebound]]) {
4263 if (auto iter = m.find(key); iter != m.end()) return iter->second;
4264 else return default_value;
4265}
4266
4267int main() {
4268 std::map<std::string, std::string> m;
4269 // warning: temporary bound to local reference 'val1' will be destroyed
4270 // at the end of the full-expression
4271 const std::string &val1 = get_or_default(m, "foo"s, "bar"s);
4272
4273 // No warning in this case.
4274 std::string def_val = "bar"s;
4275 const std::string &val2 = get_or_default(m, "foo"s, def_val);
4276
4277 return 0;
4278}
4279```
4280
4281The attribute can be applied to the implicit `this` parameter of a member
4282function by writing the attribute after the function type:
4283
4284```c++
4285struct string {
4286 // The returned pointer should not outlive ``*this``.
4287 const char *data() const [[clang::lifetimebound]];
4288};
4289```
4290
4291This attribute is inspired by the C++ committee paper [P0936R0](http://wg21.link/p0936r0), but does not affect whether temporary objects
4292have their lifetimes extended.)reST";
4293
4294static const char AttrDoc_LifetimeCaptureBy[] = R"reST(Similar to [lifetimebound], the `lifetime_capture_by` attribute family on a
4295function parameter or implicit object parameter indicates that a capturing
4296entity may refer to the object referred to by that parameter. The capturing
4297entity can be named in `lifetime_capture_by(X)` or selected by one of the
4298standalone special forms listed below.
4299
4300Below is a list of types of the parameters and what they're considered to refer to:
4301
4302- A reference param (of non-view type) is considered to refer to its referenced object.
4303- A pointer param (of non-view type) is considered to refer to its pointee.
4304- View type param (type annotated with `[[gsl::Pointer()]]`) is considered to refer
4305 to its pointee (gsl owner). This holds true even if the view type appears as a reference
4306 in the parameter. For example, both `std::string_view` and
4307 `const std::string_view &` are considered to refer to a `std::string`.
4308- A `std::initializer_list<T>` is considered to refer to its underlying array.
4309- Aggregates (arrays and simple `struct`s) are considered to refer to all
4310 objects that their transitive subobjects refer to.
4311
4312Clang would diagnose when a temporary object is used as an argument to such an
4313annotated parameter.
4314In this case, the capturing entity `X` could capture a dangling reference to this
4315temporary object.
4316
4317```c++
4318void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
4319 s.insert(a);
4320}
4321void use() {
4322 std::set<std::string_view> s;
4323 addToSet(std::string(), s); // Warning: object whose reference is captured by 's' will be destroyed at the end of the full-expression.
4324 // ^^^^^^^^^^^^^
4325 std::string local;
4326 addToSet(local, s); // Ok.
4327}
4328```
4329
4330The capturing entity can be one of the following:
4331
4332- Another (named) function parameter.
4333
4334 ```c++
4335 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
4336 s.insert(a);
4337 }
4338 ```
4339
4340- `this` (in case of member functions), written as
4341 `lifetime_capture_by_this`.
4342
4343 ```c++
4344 class S {
4345 void addToSet(std::string_view a [[clang::lifetime_capture_by_this]]) {
4346 s.insert(a);
4347 }
4348 std::set<std::string_view> s;
4349 };
4350 ```
4351
4352 Note: When applied to a constructor parameter, `[[clang::lifetime_capture_by_this]]` is just an alias of `[[clang::lifetimebound]]`.
4353
4354- `global` and `unknown`, written as `lifetime_capture_by_global` and
4355 `lifetime_capture_by_unknown` respectively.
4356
4357 ```c++
4358 std::set<std::string_view> s;
4359 void addToSet(std::string_view a [[clang::lifetime_capture_by_global]]) {
4360 s.insert(a);
4361 }
4362 void addSomewhere(std::string_view a [[clang::lifetime_capture_by_unknown]]);
4363 ```
4364
4365The attribute can be applied to the implicit `this` parameter of a member
4366function by writing the attribute after the function type:
4367
4368```c++
4369struct S {
4370 const char *data(std::set<S*>& s) [[clang::lifetime_capture_by(s)]] {
4371 s.insert(this);
4372 }
4373};
4374```
4375
4376The parameter-list form supports specifying more than one capturing entity:
4377
4378```c++
4379void addToSets(std::string_view a [[clang::lifetime_capture_by(s1, s2)]],
4380 std::set<std::string_view>& s1,
4381 std::set<std::string_view>& s2) {
4382 s1.insert(a);
4383 s2.insert(a);
4384}
4385```
4386
4387Distinct `lifetime_capture_by` forms can also be combined on the same
4388declaration, but each form can appear at most once. For example,
4389`[[clang::lifetime_capture_by(s), clang::lifetime_capture_by_this]]` is
4390allowed, but two `[[clang::lifetime_capture_by(...)]]` attributes or two
4391`[[clang::lifetime_capture_by_this]]` attributes on the same declaration are
4392rejected.
4393
4394Limitation: The capturing entity `X` is not used by the analysis and is
4395used for documentation purposes only. This is because the analysis is
4396statement-local and only detects use of a temporary as an argument to the
4397annotated parameter.
4398
4399```c++
4400void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s);
4401void use() {
4402 std::set<std::string_view> s;
4403 if (foo()) {
4404 std::string str;
4405 addToSet(str, s); // Not detected.
4406 }
4407}
4408```)reST";
4409
4410static const char AttrDoc_Likely[] = R"reST(The `likely` and `unlikely` attributes are used as compiler hints.
4411The attributes are used to aid the compiler to determine which branch is
4412likely or unlikely to be taken. This is done by marking the branch substatement
4413with one of the two attributes.
4414
4415It isn't allowed to annotate a single statement with both `likely` and
4416`unlikely`. Annotating the `true` and `false` branch of an `if`
4417statement with the same likelihood attribute will result in a diagnostic and
4418the attributes are ignored on both branches.
4419
4420In a `switch` statement it's allowed to annotate multiple `case` labels
4421or the `default` label with the same likelihood attribute. This makes
4422\* all labels without an attribute have a neutral likelihood,
4423\* all labels marked `[[likely]]` have an equally positive likelihood, and
4424\* all labels marked `[[unlikely]]` have an equally negative likelihood.
4425The neutral likelihood is the more likely of path execution than the negative
4426likelihood. The positive likelihood is the more likely of path of execution
4427than the neutral likelihood.
4428
4429These attributes have no effect on the generated code when using
4430PGO (Profile-Guided Optimization) or at optimization level 0.
4431
4432In Clang, the attributes will be ignored if they're not placed on
4433\* the `case` or `default` label of a `switch` statement,
4434\* or on the substatement of an `if` or `else` statement,
4435\* or on the substatement of an `for` or `while` statement.
4436The C++ Standard recommends to honor them on every statement in the
4437path of execution, but that can be confusing:
4438
4439```c++
4440if (b) {
4441 [[unlikely]] --b; // Per the standard this is in the path of
4442 // execution, so this branch should be considered
4443 // unlikely. However, Clang ignores the attribute
4444 // here since it is not on the substatement.
4445}
4446
4447if (b) {
4448 --b;
4449 if(b)
4450 return;
4451 [[unlikely]] --b; // Not in the path of execution,
4452} // the branch has no likelihood information.
4453
4454if (b) {
4455 --b;
4456 foo(b);
4457 // Whether or not the next statement is in the path of execution depends
4458 // on the declaration of foo():
4459 // In the path of execution: void foo(int);
4460 // Not in the path of execution: [[noreturn]] void foo(int);
4461 // This means the likelihood of the branch depends on the declaration
4462 // of foo().
4463 [[unlikely]] --b;
4464}
4465```
4466
4467Below are some example usages of the likelihood attributes and their effects:
4468
4469```c++
4470if (b) [[likely]] { // Placement on the first statement in the branch.
4471 // The compiler will optimize to execute the code here.
4472} else {
4473}
4474
4475if (b)
4476 [[unlikely]] b++; // Placement on the first statement in the branch.
4477else {
4478 // The compiler will optimize to execute the code here.
4479}
4480
4481if (b) {
4482 [[unlikely]] b++; // Placement on the second statement in the branch.
4483} // The attribute will be ignored.
4484
4485if (b) [[likely]] {
4486 [[unlikely]] b++; // No contradiction since the second attribute
4487} // is ignored.
4488
4489if (b)
4490 ;
4491else [[likely]] {
4492 // The compiler will optimize to execute the code here.
4493}
4494
4495if (b)
4496 ;
4497else
4498 // The compiler will optimize to execute the next statement.
4499 [[likely]] b = f();
4500
4501if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
4502else [[likely]]; // and the attributes are ignored.
4503
4504if (b)
4505 [[likely]] int i = 5; // Issues a diagnostic since the attribute
4506 // isn't allowed on a declaration.
4507
4508switch (i) {
4509 [[likely]] case 1: // This value is likely
4510 ...
4511 break;
4512
4513 [[unlikely]] case 2: // This value is unlikely
4514 ...
4515 [[fallthrough]];
4516
4517 case 3: // No likelihood attribute
4518 ...
4519 [[likely]] break; // No effect
4520
4521 case 4: [[likely]] { // attribute on substatement has no effect
4522 ...
4523 break;
4524 }
4525
4526 [[unlikely]] default: // All other values are unlikely
4527 ...
4528 break;
4529}
4530
4531switch (i) {
4532 [[likely]] case 0: // This value and code path is likely
4533 ...
4534 [[fallthrough]];
4535
4536 case 1: // No likelihood attribute, code path is neutral
4537 break; // falling through has no effect on the likelihood
4538
4539 case 2: // No likelihood attribute, code path is neutral
4540 [[fallthrough]];
4541
4542 [[unlikely]] default: // This value and code path are both unlikely
4543 break;
4544}
4545
4546for(int i = 0; i != size; ++i) [[likely]] {
4547 ... // The loop is the likely path of execution
4548}
4549
4550for(const auto &E : Elements) [[likely]] {
4551 ... // The loop is the likely path of execution
4552}
4553
4554while(i != size) [[unlikely]] {
4555 ... // The loop is the unlikely path of execution
4556} // The generated code will optimize to skip the loop body
4557
4558while(true) [[unlikely]] {
4559 ... // The attribute has no effect
4560} // Clang elides the comparison and generates an infinite
4561 // loop
4562```)reST";
4563
4564static const char AttrDoc_LoaderUninitialized[] = R"reST(The `loader_uninitialized` attribute can be placed on global variables to
4565indicate that the variable does not need to be zero initialized by the loader.
4566On most targets, zero-initialization does not incur any additional cost.
4567For example, most general purpose operating systems deliberately ensure
4568that all memory is properly initialized in order to avoid leaking privileged
4569information from the kernel or other programs. However, some targets
4570do not make this guarantee, and on these targets, avoiding an unnecessary
4571zero-initialization can have a significant impact on load times and/or code
4572size.
4573
4574A declaration with this attribute is a non-tentative definition just as if it
4575provided an initializer. Variables with this attribute are considered to be
4576uninitialized in the same sense as a local variable, and the programs must
4577write to them before reading from them. If the variable's type is a C++ class
4578type with a non-trivial default constructor, or an array thereof, this attribute
4579only suppresses the static zero-initialization of the variable, not the dynamic
4580initialization provided by executing the default constructor.)reST";
4581
4582static const char AttrDoc_LockReturned[] = R"reST(No documentation.)reST";
4583
4584static const char AttrDoc_LocksExcluded[] = R"reST(No documentation.)reST";
4585
4586static const char AttrDoc_LoopHint[] = R"reST(The `#pragma clang loop` directive allows loop optimization hints to be
4587specified for the subsequent loop. The directive allows pipelining to be
4588disabled, or vectorization, vector predication, interleaving, and unrolling to
4589be enabled or disabled. Vector width, vector predication, interleave count,
4590unrolling count, and the initiation interval for pipelining can be explicitly
4591specified. See
4592{ref}`loop hint optimizations <langext-loop-hint-optimizations>` for details.)reST";
4593
4594static const char AttrDoc_M68kInterrupt[] = R"reST(No documentation.)reST";
4595
4596static const char AttrDoc_M68kRTD[] = R"reST(On M68k targets, this attribute changes the calling convention of a function
4597to clear parameters off the stack on return. In other words, callee is
4598responsible for cleaning out the stack space allocated for incoming paramters.
4599This convention does not support variadic calls or unprototyped functions in C.
4600When targeting M68010 or newer CPUs, this calling convention is implemented
4601using the `rtd` instruction.)reST";
4602
4603static const char AttrDoc_MIGServerRoutine[] = R"reST(The Mach Interface Generator release-on-success convention dictates
4604
4605functions that follow it to only release arguments passed to them when they
4606return "success" (a `kern_return_t` error code that indicates that
4607no errors have occurred). Otherwise the release is performed by the MIG client
4608that called the function. The annotation `__attribute__((mig_server_routine))`
4609is applied in order to specify which functions are expected to follow the
4610convention. This allows the Static Analyzer to find bugs caused by violations of
4611that convention. The attribute would normally appear on the forward declaration
4612of the actual server routine in the MIG server header, but it may also be
4613added to arbitrary functions that need to follow the same convention - for
4614example, a user can add them to auxiliary functions called by the server routine
4615that have their return value of type `kern_return_t` unconditionally returned
4616from the routine. The attribute can be applied to C++ methods, and in this case
4617it will be automatically applied to overrides if the method is virtual. The
4618attribute can also be written using C++11 syntax: `[[mig::server_routine]]`.)reST";
4619
4620static const char AttrDoc_MSABI[] = R"reST(On non-Windows x86_64 and aarch64 targets, this attribute changes the calling convention of
4621a function to match the default convention used on Windows. This
4622attribute has no effect on Windows targets or non-x86_64, non-aarch64 targets.)reST";
4623
4624static const char AttrDoc_MSAllocator[] = R"reST(The `__declspec(allocator)` attribute is applied to functions that allocate
4625memory, such as operator new in C++. When CodeView debug information is emitted
4626(enabled by `clang -gcodeview` or `clang-cl /Z7`), Clang will attempt to
4627record the code offset of heap allocation call sites in the debug info. It will
4628also record the type being allocated using some local heuristics. The Visual
4629Studio debugger uses this information to [profile memory usage][profile memory usage].
4630
4631This attribute does not affect optimizations in any way, unlike GCC's
4632`__attribute__((malloc))`.
4633
4634[profile memory usage]: https://docs.microsoft.com/en-us/visualstudio/profiling/memory-usage)reST";
4635
4636static const char AttrDoc_MSConstexpr[] = R"reST(The `[[msvc::constexpr]]` attribute can be applied only to a function
4637definition or a `return` statement. It does not impact function declarations.
4638A `[[msvc::constexpr]]` function cannot be `constexpr` or `consteval`.
4639A `[[msvc::constexpr]]` function is treated as if it were a `constexpr` function
4640when it is evaluated in a constant context of `[[msvc::constexpr]] return` statement.
4641Otherwise, it is treated as a regular function.
4642
4643Semantics of this attribute are enabled only under MSVC compatibility
4644(`-fms-compatibility-version`) 19.33 and later.)reST";
4645
4646static const char AttrDoc_MSInheritance[] = R"reST(This collection of keywords is enabled under `-fms-extensions` and controls
4647the pointer-to-member representation used on `*-*-win32` targets.
4648
4649The `*-*-win32` targets utilize a pointer-to-member representation which
4650varies in size and alignment depending on the definition of the underlying
4651class.
4652
4653However, this is problematic when a forward declaration is only available and
4654no definition has been made yet. In such cases, Clang is forced to utilize the
4655most general representation that is available to it.
4656
4657These keywords make it possible to use a pointer-to-member representation other
4658than the most general one regardless of whether or not the definition will ever
4659be present in the current translation unit.
4660
4661This family of keywords belong between the `class-key` and `class-name`:
4662
4663```c++
4664struct __single_inheritance S;
4665int S::*i;
4666struct S {};
4667```
4668
4669This keyword can be applied to class templates but only has an effect when used
4670on full specializations:
4671
4672```c++
4673template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
4674template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
4675template <> struct __single_inheritance A<int, float>;
4676```
4677
4678Note that choosing an inheritance model less general than strictly necessary is
4679an error:
4680
4681```c++
4682struct __multiple_inheritance S; // error: inheritance model does not match definition
4683int S::*i;
4684struct S {};
4685```)reST";
4686
4687static const char AttrDoc_MSNoVTable[] = R"reST(This attribute can be added to a class declaration or definition to signal to
4688the compiler that constructors and destructors will not reference the virtual
4689function table. It is only supported when using the Microsoft C++ ABI.)reST";
4690
4691static const char AttrDoc_MSP430Interrupt[] = R"reST(No documentation.)reST";
4692
4693static const char AttrDoc_MSStruct[] = R"reST(The `ms_struct` and `gcc_struct` attributes request the compiler to enter a
4694special record layout compatibility mode which mimics the layout of Microsoft or
4695Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the
4696requested ABI, the attribute does nothing. However, if it does not, annotated
4697structure or class is laid out in a special compatibility mode, which slightly
4698changes offsets for fields and bit-fields. The intention is to match the layout
4699of the requested ABI for structures which only use C features.
4700
4701Note that the default behavior can be controlled by `-mms-bitfields` and
4702`-mno-ms-bitfields` switches and via `#pragma ms_struct`.
4703
4704The primary difference is for bitfields, where the MS variant only packs
4705adjacent fields into the same allocation unit if they have integral types
4706of the same size, while the GCC/Itanium variant packs all fields in a bitfield
4707tightly.)reST";
4708
4709static const char AttrDoc_MSVtorDisp[] = R"reST()reST";
4710
4711static const char AttrDoc_MallocSpan[] = R"reST(The `malloc_span` attribute can be used to mark that a function which acts
4712like a system memory allocation function and returns a span-like structure,
4713where the returned memory range does not alias storage from any other object
4714accessible to the caller.
4715
4716In this context, a span-like structure is assumed to have two non-static data
4717members, one of which is a pointer to the start of the allocated memory and
4718the other one is either an integer type containing the size of the actually
4719allocated memory or a pointer to the end of the allocated region. Note, static
4720data members do not impact whether a type is span-like or not.)reST";
4721
4722static const char AttrDoc_MaxFieldAlignment[] = R"reST()reST";
4723
4724static const char AttrDoc_MayAlias[] = R"reST(No documentation.)reST";
4725
4726static const char AttrDoc_MaybeUndef[] = R"reST(The `maybe_undef` attribute can be placed on a function parameter. It indicates
4727that the parameter is allowed to use undef values. It informs the compiler
4728to insert a freeze LLVM IR instruction on the function parameter.
4729Please note that this is an attribute that is used as an internal
4730implementation detail and not intended to be used by external users.
4731
4732In languages HIP, CUDA etc., some functions have multi-threaded semantics and
4733it is enough for only one or some threads to provide defined arguments.
4734Depending on semantics, undef arguments in some threads don't produce
4735undefined results in the function call. Since, these functions accept undefined
4736arguments, `maybe_undef` attribute can be placed.
4737
4738Sample usage:
4739
4740```c
4741void maybeundeffunc(int __attribute__((maybe_undef))param);
4742```)reST";
4743
4744static const char AttrDoc_MicroMips[] = R"reST(Clang supports the GNU style `__attribute__((micromips))` and
4745`__attribute__((nomicromips))` attributes on MIPS targets. These attributes
4746may be attached to a function definition and instructs the backend to generate
4747or not to generate microMIPS code for that function.
4748
4749These attributes override the `-mmicromips` and `-mno-micromips` options
4750on the command line.)reST";
4751
4752static const char AttrDoc_MinSize[] = R"reST(This function attribute indicates that optimization passes and code generator passes
4753make choices that keep the function code size as small as possible. Optimizations may
4754also sacrifice runtime performance in order to minimize the size of the generated code.)reST";
4755
4756static const char AttrDoc_MinVectorWidth[] = R"reST(Clang supports the `__attribute__((min_vector_width(width)))` attribute. This
4757attribute may be attached to a function and informs the backend that this
4758function desires vectors of at least this width to be generated. Target-specific
4759maximum vector widths still apply. This means even if you ask for something
4760larger than the target supports, you will only get what the target supports.
4761This attribute is meant to be a hint to control target heuristics that may
4762generate narrower vectors than what the target hardware supports.
4763
4764This is currently used by the X86 target to allow some CPUs that support 512-bit
4765vectors to be limited to using 256-bit vectors to avoid frequency penalties.
4766This is currently enabled with the `-prefer-vector-width=256` command line
4767option. The `min_vector_width` attribute can be used to prevent the backend
4768from trying to split vector operations to match the `prefer-vector-width`. All
4769X86 vector intrinsics from x86intrin.h already set this attribute. Additionally,
4770use of any of the X86-specific vector builtins will implicitly set this
4771attribute on the calling function. The intent is that explicitly writing vector
4772code using the X86 intrinsics will prevent `prefer-vector-width` from
4773affecting the code.)reST";
4774
4775static const char AttrDoc_Mips16[] = R"reST(No documentation.)reST";
4776
4777static const char AttrDoc_MipsInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt("ARGUMENT")))` attribute on
4778MIPS targets. This attribute may be attached to a function definition and instructs
4779the backend to generate appropriate function entry/exit code so that it can be used
4780directly as an interrupt service routine.
4781
4782By default, the compiler will produce a function prologue and epilogue suitable for
4783an interrupt service routine that handles an External Interrupt Controller (eic)
4784generated interrupt. This behavior can be explicitly requested with the "eic"
4785argument.
4786
4787Otherwise, for use with vectored interrupt mode, the argument passed should be
4788of the form "vector=LEVEL" where LEVEL is one of the following values:
4789"sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will
4790then set the interrupt mask to the corresponding level which will mask all
4791interrupts up to and including the argument.
4792
4793The semantics are as follows:
4794
4795- The prologue is modified so that the Exception Program Counter (EPC) and
4796 Status coprocessor registers are saved to the stack. The interrupt mask is
4797 set so that the function can only be interrupted by a higher priority
4798 interrupt. The epilogue will restore the previous values of EPC and Status.
4799- The prologue and epilogue are modified to save and restore all non-kernel
4800 registers as necessary.
4801- The FPU is disabled in the prologue, as the floating pointer registers are not
4802 spilled to the stack.
4803- The function return sequence is changed to use an exception return instruction.
4804- The parameter sets the interrupt mask for the function corresponding to the
4805 interrupt level specified. If no mask is specified the interrupt mask
4806 defaults to "eic".)reST";
4807
4808static const char AttrDoc_MipsLongCall[] = R"reST(Clang supports the `__attribute__((long_call))`, `__attribute__((far))`,
4809and `__attribute__((near))` attributes on MIPS targets. These attributes may
4810only be added to function declarations and change the code generated
4811by the compiler when directly calling the function. The `near` attribute
4812allows calls to the function to be made using the `jal` instruction, which
4813requires the function to be located in the same naturally aligned 256MB
4814segment as the caller. The `long_call` and `far` attributes are synonyms
4815and require the use of a different call sequence that works regardless
4816of the distance between the functions.
4817
4818These attributes have no effect for position-independent code.
4819
4820These attributes take priority over command line switches such
4821as `-mlong-calls` and `-mno-long-calls`.)reST";
4822
4823static const char AttrDoc_MipsShortCall[] = R"reST(Clang supports the `__attribute__((long_call))`, `__attribute__((far))`,
4824`__attribute__((short__call))`, and `__attribute__((near))` attributes
4825on MIPS targets. These attributes may only be added to function declarations
4826and change the code generated by the compiler when directly calling
4827the function. The `short_call` and `near` attributes are synonyms and
4828allow calls to the function to be made using the `jal` instruction, which
4829requires the function to be located in the same naturally aligned 256MB segment
4830as the caller. The `long_call` and `far` attributes are synonyms and
4831require the use of a different call sequence that works regardless
4832of the distance between the functions.
4833
4834These attributes have no effect for position-independent code.
4835
4836These attributes take priority over command line switches such
4837as `-mlong-calls` and `-mno-long-calls`.)reST";
4838
4839static const char AttrDoc_Mode[] = R"reST(No documentation.)reST";
4840
4841static const char AttrDoc_ModularFormat[] = R"reST(The `modular_format` attribute can be applied to a function that bears the
4842`format` attribute (or standard library functions) to indicate that the
4843implementation is "modular", that is, that the implementation is logically
4844divided into a number of named aspects. When the compiler can determine that
4845not all aspects of the implementation are needed for a given call, the compiler
4846may redirect the call to the identifier given as the first argument to the
4847attribute (the modular implementation function).
4848
4849The second argument is an implementation name, and the remaining arguments are
4850aspects of the format string for the compiler to report. The implementation
4851name is an unevaluated identifier in the C namespace.
4852
4853The compiler reports that a call requires an aspect by issuing a relocation for
4854the symbol `<impl_name>_<aspect>` at the point of the call. This arranges for
4855code and data needed to support the aspect of the implementation to be brought
4856into the link to satisfy weak references in the modular implemenation function.
4857If the compiler does not understand an aspect, it must summarily consider any
4858call to require that aspect.
4859
4860For example, say `printf` is annotated with
4861`modular_format(__modular_printf, "__printf", "float")`. Then, a call to
4862`printf(var, 42)` would be untouched. A call to `printf("%d", 42)` would
4863become a call to `__modular_printf` with the same arguments, as would
4864`printf("%f", 42.0)`. The latter would be accompanied with a strong
4865relocation against the symbol `__printf_float`, which would bring floating
4866point support for `printf` into the link.
4867
4868If the attribute appears more than once on a declaration, or across a chain of
4869redeclarations, it is an error for the attributes to have different arguments,
4870excepting that the aspects may be in any order.
4871
4872The following aspects are currently supported:
4873
4874- `fixed`: The call has a C ISO 18037 fixed-point argument.
4875- `float`: The call has a floating-point argument.)reST";
4876
4877static const char AttrDoc_MustTail[] = R"reST(If a `return` statement is marked `musttail`, this indicates that the
4878compiler must generate a tail call for the program to be correct, even when
4879optimizations are disabled. This guarantees that the call will not cause
4880unbounded stack growth if it is part of a recursive cycle in the call graph.
4881
4882If the callee is a virtual function that is implemented by a thunk, there is
4883no guarantee in general that the thunk tail-calls the implementation of the
4884virtual function, so such a call in a recursive cycle can still result in
4885unbounded stack growth.
4886
4887`clang::musttail` can only be applied to a `return` statement whose value
4888is the result of a function call (even functions returning void must use
4889`return`, although no value is returned). The target function must have the
4890same number of arguments as the caller. The types of the return value and all
4891arguments must be similar according to C++ rules (differing only in cv
4892qualifiers or array size), including the implicit "this" argument, if any.
4893Any variables in scope, including all arguments to the function and the
4894return value must be trivially destructible. The calling convention of the
4895caller and callee must match, and they must not be variadic functions or have
4896old style K&R C function declarations.
4897
4898The lifetimes of all local variables and function parameters end immediately
4899before the call to the function. This means that it is undefined behaviour to
4900pass a pointer or reference to a local variable to the called function, which
4901is not the case without the attribute. Clang will emit a warning in common
4902cases where this happens.
4903
4904`clang::musttail` provides assurances that the tail call can be optimized on
4905all targets, not just one.)reST";
4906
4907static const char AttrDoc_NSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4908(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4909convention (e.g. functions starting with "get" are assumed to return at
4910`+0`).
4911
4912It can be overridden using a family of the following attributes. In
4913Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
4914a function communicates that the object is returned at `+1`, and the caller
4915is responsible for freeing it.
4916Similarly, the annotation `__attribute__((ns_returns_not_retained))`
4917specifies that the object is returned at `+0` and the ownership remains with
4918the callee.
4919The annotation `__attribute__((ns_consumes_self))` specifies that
4920the Objective-C method call consumes the reference to `self`, e.g. by
4921attaching it to a supplied parameter.
4922Additionally, parameters can have an annotation
4923`__attribute__((ns_consumed))`, which specifies that passing an owned object
4924as that parameter effectively transfers the ownership, and the caller is no
4925longer responsible for it.
4926These attributes affect code generation when interacting with ARC code, and
4927they are used by the Clang Static Analyzer.
4928
4929In C programs using CoreFoundation, a similar set of attributes:
4930`__attribute__((cf_returns_not_retained))`,
4931`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
4932have the same respective semantics when applied to CoreFoundation objects.
4933These attributes affect code generation when interacting with ARC code, and
4934they are used by the Clang Static Analyzer.
4935
4936Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4937the same attribute family is present:
4938`__attribute__((os_returns_not_retained))`,
4939`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
4940with the same respective semantics.
4941Similar to `__attribute__((ns_consumes_self))`,
4942`__attribute__((os_consumes_this))` specifies that the method call consumes
4943the reference to "this" (e.g., when attaching it to a different object supplied
4944as a parameter).
4945Out parameters (parameters the function is meant to write into,
4946either via pointers-to-pointers or references-to-pointers)
4947may be annotated with `__attribute__((os_returns_retained))`
4948or `__attribute__((os_returns_not_retained))` which specifies that the object
4949written into the out parameter should (or respectively should not) be released
4950after use.
4951Since often out parameters may or may not be written depending on the exit
4952code of the function,
4953annotations `__attribute__((os_returns_retained_on_zero))`
4954and `__attribute__((os_returns_retained_on_non_zero))` specify that
4955an out parameter at `+1` is written if and only if the function returns a zero
4956(respectively non-zero) error code.
4957Observe that return-code-dependent out parameter annotations are only
4958available for retained out parameters, as non-retained object do not have to be
4959released by the callee.
4960These attributes are only used by the Clang Static Analyzer.
4961
4962The family of attributes `X_returns_X_retained` can be added to functions,
4963C++ methods, and Objective-C methods and properties.
4964Attributes `X_consumed` can be added to parameters of methods, functions,
4965and Objective-C methods.)reST";
4966
4967static const char AttrDoc_NSConsumesSelf[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4968(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4969convention (e.g. functions starting with "get" are assumed to return at
4970`+0`).
4971
4972It can be overridden using a family of the following attributes. In
4973Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
4974a function communicates that the object is returned at `+1`, and the caller
4975is responsible for freeing it.
4976Similarly, the annotation `__attribute__((ns_returns_not_retained))`
4977specifies that the object is returned at `+0` and the ownership remains with
4978the callee.
4979The annotation `__attribute__((ns_consumes_self))` specifies that
4980the Objective-C method call consumes the reference to `self`, e.g. by
4981attaching it to a supplied parameter.
4982Additionally, parameters can have an annotation
4983`__attribute__((ns_consumed))`, which specifies that passing an owned object
4984as that parameter effectively transfers the ownership, and the caller is no
4985longer responsible for it.
4986These attributes affect code generation when interacting with ARC code, and
4987they are used by the Clang Static Analyzer.
4988
4989In C programs using CoreFoundation, a similar set of attributes:
4990`__attribute__((cf_returns_not_retained))`,
4991`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
4992have the same respective semantics when applied to CoreFoundation objects.
4993These attributes affect code generation when interacting with ARC code, and
4994they are used by the Clang Static Analyzer.
4995
4996Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4997the same attribute family is present:
4998`__attribute__((os_returns_not_retained))`,
4999`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
5000with the same respective semantics.
5001Similar to `__attribute__((ns_consumes_self))`,
5002`__attribute__((os_consumes_this))` specifies that the method call consumes
5003the reference to "this" (e.g., when attaching it to a different object supplied
5004as a parameter).
5005Out parameters (parameters the function is meant to write into,
5006either via pointers-to-pointers or references-to-pointers)
5007may be annotated with `__attribute__((os_returns_retained))`
5008or `__attribute__((os_returns_not_retained))` which specifies that the object
5009written into the out parameter should (or respectively should not) be released
5010after use.
5011Since often out parameters may or may not be written depending on the exit
5012code of the function,
5013annotations `__attribute__((os_returns_retained_on_zero))`
5014and `__attribute__((os_returns_retained_on_non_zero))` specify that
5015an out parameter at `+1` is written if and only if the function returns a zero
5016(respectively non-zero) error code.
5017Observe that return-code-dependent out parameter annotations are only
5018available for retained out parameters, as non-retained object do not have to be
5019released by the callee.
5020These attributes are only used by the Clang Static Analyzer.
5021
5022The family of attributes `X_returns_X_retained` can be added to functions,
5023C++ methods, and Objective-C methods and properties.
5024Attributes `X_consumed` can be added to parameters of methods, functions,
5025and Objective-C methods.)reST";
5026
5027static const char AttrDoc_NSErrorDomain[] = R"reST(In Cocoa frameworks in Objective-C, one can group related error codes in enums
5028and categorize these enums with error domains.
5029
5030The `ns_error_domain` attribute indicates a global `NSString` or
5031`CFString` constant representing the error domain that an error code belongs
5032to. For pointer uniqueness and code size this is a constant symbol, not a
5033literal.
5034
5035The domain and error code need to be used together. The `ns_error_domain`
5036attribute links error codes to their domain at the source level.
5037
5038This metadata is useful for documentation purposes, for static analysis, and for
5039improving interoperability between Objective-C and Swift. It is not used for
5040code generation in Objective-C.
5041
5042For example:
5043
5044```objc
5045#define NS_ERROR_ENUM(_type, _name, _domain) \
5046 enum _name : _type _name; enum __attribute__((ns_error_domain(_domain))) _name : _type
5047
5048extern NSString *const MyErrorDomain;
5049typedef NS_ERROR_ENUM(unsigned char, MyErrorEnum, MyErrorDomain) {
5050 MyErrFirst,
5051 MyErrSecond,
5052};
5053```)reST";
5054
5055static const char AttrDoc_NSReturnsAutoreleased[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5056(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5057convention (e.g. functions starting with "get" are assumed to return at
5058`+0`).
5059
5060It can be overridden using a family of the following attributes. In
5061Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
5062a function communicates that the object is returned at `+1`, and the caller
5063is responsible for freeing it.
5064Similarly, the annotation `__attribute__((ns_returns_not_retained))`
5065specifies that the object is returned at `+0` and the ownership remains with
5066the callee.
5067The annotation `__attribute__((ns_consumes_self))` specifies that
5068the Objective-C method call consumes the reference to `self`, e.g. by
5069attaching it to a supplied parameter.
5070Additionally, parameters can have an annotation
5071`__attribute__((ns_consumed))`, which specifies that passing an owned object
5072as that parameter effectively transfers the ownership, and the caller is no
5073longer responsible for it.
5074These attributes affect code generation when interacting with ARC code, and
5075they are used by the Clang Static Analyzer.
5076
5077In C programs using CoreFoundation, a similar set of attributes:
5078`__attribute__((cf_returns_not_retained))`,
5079`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
5080have the same respective semantics when applied to CoreFoundation objects.
5081These attributes affect code generation when interacting with ARC code, and
5082they are used by the Clang Static Analyzer.
5083
5084Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5085the same attribute family is present:
5086`__attribute__((os_returns_not_retained))`,
5087`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
5088with the same respective semantics.
5089Similar to `__attribute__((ns_consumes_self))`,
5090`__attribute__((os_consumes_this))` specifies that the method call consumes
5091the reference to "this" (e.g., when attaching it to a different object supplied
5092as a parameter).
5093Out parameters (parameters the function is meant to write into,
5094either via pointers-to-pointers or references-to-pointers)
5095may be annotated with `__attribute__((os_returns_retained))`
5096or `__attribute__((os_returns_not_retained))` which specifies that the object
5097written into the out parameter should (or respectively should not) be released
5098after use.
5099Since often out parameters may or may not be written depending on the exit
5100code of the function,
5101annotations `__attribute__((os_returns_retained_on_zero))`
5102and `__attribute__((os_returns_retained_on_non_zero))` specify that
5103an out parameter at `+1` is written if and only if the function returns a zero
5104(respectively non-zero) error code.
5105Observe that return-code-dependent out parameter annotations are only
5106available for retained out parameters, as non-retained object do not have to be
5107released by the callee.
5108These attributes are only used by the Clang Static Analyzer.
5109
5110The family of attributes `X_returns_X_retained` can be added to functions,
5111C++ methods, and Objective-C methods and properties.
5112Attributes `X_consumed` can be added to parameters of methods, functions,
5113and Objective-C methods.)reST";
5114
5115static const char AttrDoc_NSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5116(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5117convention (e.g. functions starting with "get" are assumed to return at
5118`+0`).
5119
5120It can be overridden using a family of the following attributes. In
5121Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
5122a function communicates that the object is returned at `+1`, and the caller
5123is responsible for freeing it.
5124Similarly, the annotation `__attribute__((ns_returns_not_retained))`
5125specifies that the object is returned at `+0` and the ownership remains with
5126the callee.
5127The annotation `__attribute__((ns_consumes_self))` specifies that
5128the Objective-C method call consumes the reference to `self`, e.g. by
5129attaching it to a supplied parameter.
5130Additionally, parameters can have an annotation
5131`__attribute__((ns_consumed))`, which specifies that passing an owned object
5132as that parameter effectively transfers the ownership, and the caller is no
5133longer responsible for it.
5134These attributes affect code generation when interacting with ARC code, and
5135they are used by the Clang Static Analyzer.
5136
5137In C programs using CoreFoundation, a similar set of attributes:
5138`__attribute__((cf_returns_not_retained))`,
5139`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
5140have the same respective semantics when applied to CoreFoundation objects.
5141These attributes affect code generation when interacting with ARC code, and
5142they are used by the Clang Static Analyzer.
5143
5144Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5145the same attribute family is present:
5146`__attribute__((os_returns_not_retained))`,
5147`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
5148with the same respective semantics.
5149Similar to `__attribute__((ns_consumes_self))`,
5150`__attribute__((os_consumes_this))` specifies that the method call consumes
5151the reference to "this" (e.g., when attaching it to a different object supplied
5152as a parameter).
5153Out parameters (parameters the function is meant to write into,
5154either via pointers-to-pointers or references-to-pointers)
5155may be annotated with `__attribute__((os_returns_retained))`
5156or `__attribute__((os_returns_not_retained))` which specifies that the object
5157written into the out parameter should (or respectively should not) be released
5158after use.
5159Since often out parameters may or may not be written depending on the exit
5160code of the function,
5161annotations `__attribute__((os_returns_retained_on_zero))`
5162and `__attribute__((os_returns_retained_on_non_zero))` specify that
5163an out parameter at `+1` is written if and only if the function returns a zero
5164(respectively non-zero) error code.
5165Observe that return-code-dependent out parameter annotations are only
5166available for retained out parameters, as non-retained object do not have to be
5167released by the callee.
5168These attributes are only used by the Clang Static Analyzer.
5169
5170The family of attributes `X_returns_X_retained` can be added to functions,
5171C++ methods, and Objective-C methods and properties.
5172Attributes `X_consumed` can be added to parameters of methods, functions,
5173and Objective-C methods.)reST";
5174
5175static const char AttrDoc_NSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5176(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5177convention (e.g. functions starting with "get" are assumed to return at
5178`+0`).
5179
5180It can be overridden using a family of the following attributes. In
5181Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
5182a function communicates that the object is returned at `+1`, and the caller
5183is responsible for freeing it.
5184Similarly, the annotation `__attribute__((ns_returns_not_retained))`
5185specifies that the object is returned at `+0` and the ownership remains with
5186the callee.
5187The annotation `__attribute__((ns_consumes_self))` specifies that
5188the Objective-C method call consumes the reference to `self`, e.g. by
5189attaching it to a supplied parameter.
5190Additionally, parameters can have an annotation
5191`__attribute__((ns_consumed))`, which specifies that passing an owned object
5192as that parameter effectively transfers the ownership, and the caller is no
5193longer responsible for it.
5194These attributes affect code generation when interacting with ARC code, and
5195they are used by the Clang Static Analyzer.
5196
5197In C programs using CoreFoundation, a similar set of attributes:
5198`__attribute__((cf_returns_not_retained))`,
5199`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
5200have the same respective semantics when applied to CoreFoundation objects.
5201These attributes affect code generation when interacting with ARC code, and
5202they are used by the Clang Static Analyzer.
5203
5204Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5205the same attribute family is present:
5206`__attribute__((os_returns_not_retained))`,
5207`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
5208with the same respective semantics.
5209Similar to `__attribute__((ns_consumes_self))`,
5210`__attribute__((os_consumes_this))` specifies that the method call consumes
5211the reference to "this" (e.g., when attaching it to a different object supplied
5212as a parameter).
5213Out parameters (parameters the function is meant to write into,
5214either via pointers-to-pointers or references-to-pointers)
5215may be annotated with `__attribute__((os_returns_retained))`
5216or `__attribute__((os_returns_not_retained))` which specifies that the object
5217written into the out parameter should (or respectively should not) be released
5218after use.
5219Since often out parameters may or may not be written depending on the exit
5220code of the function,
5221annotations `__attribute__((os_returns_retained_on_zero))`
5222and `__attribute__((os_returns_retained_on_non_zero))` specify that
5223an out parameter at `+1` is written if and only if the function returns a zero
5224(respectively non-zero) error code.
5225Observe that return-code-dependent out parameter annotations are only
5226available for retained out parameters, as non-retained object do not have to be
5227released by the callee.
5228These attributes are only used by the Clang Static Analyzer.
5229
5230The family of attributes `X_returns_X_retained` can be added to functions,
5231C++ methods, and Objective-C methods and properties.
5232Attributes `X_consumed` can be added to parameters of methods, functions,
5233and Objective-C methods.)reST";
5234
5235static const char AttrDoc_Naked[] = R"reST(No documentation.)reST";
5236
5237static const char AttrDoc_NoAlias[] = R"reST(The `noalias` attribute indicates that the only memory accesses inside
5238function are loads and stores from objects pointed to by its pointer-typed
5239arguments, with arbitrary offsets.)reST";
5240
5241static const char AttrDoc_NoBuiltin[] = R"reST(The `__attribute__((no_builtin))` is similar to the `-fno-builtin` flag
5242except it is specific to the body of a function. The attribute may also be
5243applied to a virtual function but has no effect on the behavior of overriding
5244functions in a derived class.
5245
5246It accepts one or more strings corresponding to the specific names of the
5247builtins to disable (e.g. "memcpy", "memset").
5248If the attribute is used without parameters it will disable all buitins at
5249once.
5250
5251```c++
5252// The compiler is not allowed to add any builtin to foo's body.
5253void foo(char* data, size_t count) __attribute__((no_builtin)) {
5254 // The compiler is not allowed to convert the loop into
5255 // `__builtin_memset(data, 0xFE, count);`.
5256 for (size_t i = 0; i < count; ++i)
5257 data[i] = 0xFE;
5258}
5259
5260// The compiler is not allowed to add the `memcpy` builtin to bar's body.
5261void bar(char* data, size_t count) __attribute__((no_builtin("memcpy"))) {
5262 // The compiler is allowed to convert the loop into
5263 // `__builtin_memset(data, 0xFE, count);` but cannot generate any
5264 // `__builtin_memcpy`
5265 for (size_t i = 0; i < count; ++i)
5266 data[i] = 0xFE;
5267}
5268```)reST";
5269
5270static const char AttrDoc_NoCommon[] = R"reST(No documentation.)reST";
5271
5272static const char AttrDoc_NoConvergent[] = R"reST(This attribute prevents a function from being treated as convergent; when a
5273function is marked `noconvergent`, calls to that function are not
5274automatically assumed to be convergent, unless such calls are explicitly marked
5275as `convergent`. If a statement is marked as `noconvergent`, any calls to
5276inline `asm` in that statement are no longer treated as convergent.
5277
5278In languages following SPMD/SIMT programming model, e.g., CUDA/HIP, function
5279declarations and inline asm calls are treated as convergent by default for
5280correctness. This `noconvergent` attribute is helpful for developers to
5281prevent them from being treated as convergent when it's safe.
5282
5283```c
5284__device__ float bar(float);
5285__device__ float foo(float) __attribute__((noconvergent)) {}
5286
5287__device__ int example(void) {
5288 float x;
5289 [[clang::noconvergent]] x = bar(x); // no effect on convergence
5290 [[clang::noconvergent]] { asm volatile ("nop"); } // the asm call is non-convergent
5291}
5292```)reST";
5293
5294static const char AttrDoc_NoDebug[] = R"reST(The `nodebug` attribute allows you to suppress debugging information for a
5295function or method, for a variable that is not a parameter or a non-static
5296data member, or for a typedef or using declaration.)reST";
5297
5298static const char AttrDoc_NoDeref[] = R"reST(The `noderef` attribute causes clang to diagnose dereferences of annotated pointer types.
5299This is ideally used with pointers that point to special memory which cannot be read
5300from or written to, but allowing for the pointer to be used in pointer arithmetic.
5301The following are examples of valid expressions where dereferences are diagnosed:
5302
5303```c
5304int __attribute__((noderef)) *p;
5305int x = *p; // warning
5306
5307int __attribute__((noderef)) **p2;
5308x = **p2; // warning
5309
5310int * __attribute__((noderef)) *p3;
5311p = *p3; // warning
5312
5313struct S {
5314 int a;
5315};
5316struct S __attribute__((noderef)) *s;
5317x = s->a; // warning
5318x = (*s).a; // warning
5319```
5320
5321Not all dereferences may diagnose a warning if the value directed by the pointer may not be
5322accessed. The following are examples of valid expressions where may not be diagnosed:
5323
5324```c
5325int *q;
5326int __attribute__((noderef)) *p;
5327q = &*p;
5328q = *&p;
5329
5330struct S {
5331 int a;
5332};
5333struct S __attribute__((noderef)) *s;
5334p = &s->a;
5335p = &(*s).a;
5336```
5337
5338`noderef` is currently only supported for pointers and arrays and not usable
5339for references or Objective-C object pointers.
5340
5341```c++
5342int x = 2;
5343int __attribute__((noderef)) &y = x; // warning: 'noderef' can only be used on an array or pointer type
5344```
5345
5346```objc
5347id __attribute__((noderef)) obj = [NSObject new]; // warning: 'noderef' can only be used on an array or pointer type
5348```)reST";
5349
5350static const char AttrDoc_NoDestroy[] = R"reST(The `no_destroy` attribute specifies that a variable with static or thread
5351storage duration shouldn't have its exit-time destructor run. Annotating every
5352static and thread duration variable with this attribute is equivalent to
5353invoking clang with -fno-c++-static-destructors.
5354
5355If a variable is declared with this attribute, clang doesn't access check or
5356generate the type's destructor. If you have a type that you only want to be
5357annotated with `no_destroy`, you can therefore declare the destructor private:
5358
5359```c++
5360struct only_no_destroy {
5361 only_no_destroy();
5362private:
5363 ~only_no_destroy();
5364};
5365
5366[[clang::no_destroy]] only_no_destroy global; // fine!
5367```
5368
5369Note that destructors are still required for subobjects of aggregates annotated
5370with this attribute. This is because previously constructed subobjects need to
5371be destroyed if an exception gets thrown before the initialization of the
5372complete object is complete. For instance:
5373
5374```c++
5375void f() {
5376 try {
5377 [[clang::no_destroy]]
5378 static only_no_destroy array[10]; // error, only_no_destroy has a private destructor.
5379 } catch (...) {
5380 // Handle the error
5381 }
5382}
5383```
5384
5385Here, if the construction of `array[9]` fails with an exception, `array[0..8]`
5386will be destroyed, so the element's destructor needs to be accessible.)reST";
5387
5388static const char AttrDoc_NoDuplicate[] = R"reST(The `noduplicate` attribute can be placed on function declarations to control
5389whether function calls to this function can be duplicated or not as a result of
5390optimizations. This is required for the implementation of functions with
5391certain special requirements, like the OpenCL "barrier" function, that might
5392need to be run concurrently by all the threads that are executing in lockstep
5393on the hardware. For example this attribute applied on the function
5394"nodupfunc" in the code below avoids that:
5395
5396```c
5397void nodupfunc() __attribute__((noduplicate));
5398// Setting it as a C++11 attribute is also valid
5399// void nodupfunc() [[clang::noduplicate]];
5400void foo();
5401void bar();
5402
5403nodupfunc();
5404if (a > n) {
5405 foo();
5406} else {
5407 bar();
5408}
5409```
5410
5411gets possibly modified by some optimizations into code similar to this:
5412
5413```c
5414if (a > n) {
5415 nodupfunc();
5416 foo();
5417} else {
5418 nodupfunc();
5419 bar();
5420}
5421```
5422
5423where the call to "nodupfunc" is duplicated and sunk into the two branches
5424of the condition.)reST";
5425
5426static const char AttrDoc_NoEscape[] = R"reST(`noescape` placed on a function parameter of a pointer type is used to inform
5427the compiler that the pointer cannot escape: that is, no reference to the object
5428the pointer points to that is derived from the parameter value will survive
5429after the function returns. Users are responsible for making sure parameters
5430annotated with `noescape` do not actually escape. The optimizer may make
5431assumptions based on the fact that it knows that a call to the function does
5432not escape a certain parameter, so incorrectly annotating a parameter with
5433`noescape` leads to undefined behavior. The callee is also not allowed to
5434deallocate memory through a `noescape` parameter: the optimizer does not make
5435assumptions based on this information at the moment, but may do so in the
5436future. Some cases of invalid uses of `noescape` can be found with
5437{ref}`-Wlifetime-safety-noescape <Wlifetime-safety-noescape>`.
5438
5439For example:
5440
5441```c
5442int *gp;
5443
5444void nonescapingFunc(__attribute__((noescape)) int *p) {
5445 *p += 100; // OK.
5446}
5447
5448void escapingFunc(__attribute__((noescape)) int *p) {
5449 gp = p; // Not OK.
5450}
5451
5452void freeingFunc(__attribute__((noescape)) int *p) {
5453 free(p); // Not OK.
5454}
5455```
5456
5457Since `noescape` is a parameter attribute and not a type attribute, it only
5458applies to the outermost pointer level, regardless of where in the parameter
5459declaration you place it:
5460
5461```c
5462int **gp;
5463
5464void nestingEscapes(__attribute__((noescape)) int **p) {
5465 gp = p; // Not OK.
5466 *gp = *p; // OK, p does not escape.
5467}
5468```
5469
5470Additionally, when the parameter is a
5471{doc}`block pointer <BlockLanguageSpec>`, the same restriction applies to
5472copies of the block. For example:
5473
5474```c
5475typedef void (^BlockTy)();
5476BlockTy g0, g1;
5477
5478void nonescapingFunc(__attribute__((noescape)) BlockTy block) {
5479 block(); // OK.
5480}
5481
5482void escapingFunc(__attribute__((noescape)) BlockTy block) {
5483 g0 = block; // Not OK.
5484 g1 = Block_copy(block); // Not OK either.
5485}
5486```
5487
5488The function *is* allowed to leak information about the memory address of the
5489pointer, but not any provenance of the allocation:
5490
5491```c
5492bool isNull(__attribute__((noescape)) void *p) {
5493 return !p; // OK.
5494}
5495
5496uintptr_t gi;
5497
5498void escapingAddress(__attribute__((noescape)) int *p) {
5499 // OK *if and only if* gi is never casted back to a pointer.
5500 gi = (uintptr_t)p;
5501}
5502
5503bool usingEscapedAddress(int *p) {
5504 return (uintptr_t)p > gi; // OK.
5505}
5506
5507bool usingEscapedPointer(int *p) {
5508 return p > (int*)gi; // Not OK.
5509}
5510
5511int *gp;
5512
5513void escapingEndFunc(__attribute__((noescape)) int *p, size_t len) {
5514 gp = p + len; // Not OK.
5515}
5516```)reST";
5517
5518static const char AttrDoc_NoFieldProtection[] = R"reST(No documentation.)reST";
5519
5520static const char AttrDoc_NoInline[] = R"reST(This function attribute suppresses the inlining of a function at the call sites
5521of the function.
5522
5523`[[clang::noinline]]` spelling can be used as a statement attribute; other
5524spellings of the attribute are not supported on statements. If a statement is
5525marked `[[clang::noinline]]` and contains calls, those calls inside the
5526statement will not be inlined by the compiler.
5527
5528`__noinline__` can be used as a keyword in CUDA/HIP languages. This is to
5529avoid diagnostics due to usage of `__attribute__((__noinline__))`
5530with `__noinline__` defined as a macro as `__attribute__((noinline))`.
5531
5532```c
5533int example(void) {
5534 int r;
5535 [[clang::noinline]] foo();
5536 [[clang::noinline]] r = bar();
5537 return r;
5538}
5539```)reST";
5540
5541static const char AttrDoc_NoInstrumentFunction[] = R"reST(No documentation.)reST";
5542
5543static const char AttrDoc_NoMerge[] = R"reST(If a statement is marked `nomerge` and contains call expressions, those call
5544expressions inside the statement will not be merged during optimization. This
5545attribute can be used to prevent the optimizer from obscuring the source
5546location of certain calls. For example, it will prevent tail merging otherwise
5547identical code sequences that raise an exception or terminate the program. Tail
5548merging normally reduces the precision of source location information, making
5549stack traces less useful for debugging. This attribute gives the user control
5550over the tradeoff between code size and debug information precision.
5551
5552`nomerge` attribute can also be used as function attribute to prevent all
5553calls to the specified function from merging. It has no effect on indirect
5554calls to such functions. For example:
5555
5556```c++
5557[[clang::nomerge]] void foo(int) {}
5558
5559void bar(int x) {
5560 auto *ptr = foo;
5561 if (x) foo(1); else foo(2); // will not be merged
5562 if (x) ptr(1); else ptr(2); // indirect call, can be merged
5563}
5564```
5565
5566`nomerge` attribute can also be used for pointers to functions to
5567prevent calls through such pointer from merging. In such case the
5568effect applies only to a specific function pointer. For example:
5569
5570```c++
5571[[clang::nomerge]] void (*foo)(int);
5572
5573void bar(int x) {
5574 auto *ptr = foo;
5575 if (x) foo(1); else foo(2); // will not be merged
5576 if (x) ptr(1); else ptr(2); // 'ptr' has no 'nomerge' attribute, can be merged
5577}
5578```)reST";
5579
5580static const char AttrDoc_NoMicroMips[] = R"reST(Clang supports the GNU style `__attribute__((micromips))` and
5581`__attribute__((nomicromips))` attributes on MIPS targets. These attributes
5582may be attached to a function definition and instructs the backend to generate
5583or not to generate microMIPS code for that function.
5584
5585These attributes override the `-mmicromips` and `-mno-micromips` options
5586on the command line.)reST";
5587
5588static const char AttrDoc_NoMips16[] = R"reST(No documentation.)reST";
5589
5590static const char AttrDoc_NoOutline[] = R"reST(This function attribute suppresses outlining from the annotated function.
5591
5592Outlining is the process where common parts of separate functions are extracted
5593into a separate function (or assembly snippet), and calls to that function or
5594snippet are inserted in the original functions. In this way, it can be seen as
5595the opposite of inlining. It can help to reduce code size.)reST";
5596
5597static const char AttrDoc_NoProfileFunction[] = R"reST(Use the `no_profile_instrument_function` attribute on a function declaration
5598to denote that the compiler should not instrument the function with
5599profile-related instrumentation, such as via the
5600`-fprofile-generate` / `-fprofile-instr-generate` /
5601`-fcs-profile-generate` / `-fprofile-arcs` flags.)reST";
5602
5603static const char AttrDoc_NoRandomizeLayout[] = R"reST(The attribute `randomize_layout`, when attached to a C structure, selects it
5604for structure layout field randomization; a compile-time hardening technique. A
5605"seed" value, is specified via the `-frandomize-layout-seed=` command line flag.
5606For example:
5607
5608```bash
5609SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
5610make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
5611```
5612
5613You can also supply the seed in a file with `-frandomize-layout-seed-file=`.
5614For example:
5615
5616```bash
5617od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
5618make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
5619```
5620
5621The randomization is deterministic based for a given seed, so the entire
5622program should be compiled with the same seed, but keep the seed safe
5623otherwise.
5624
5625The attribute `no_randomize_layout`, when attached to a C structure,
5626instructs the compiler that this structure should not have its field layout
5627randomized.)reST";
5628
5629static const char AttrDoc_NoReturn[] = R"reST(No documentation.)reST";
5630
5631static const char AttrDoc_NoSanitize[] = R"reST(Use the `no_sanitize` attribute on a function or a global variable
5632declaration to specify that a particular instrumentation or set of
5633instrumentations should not be applied.
5634
5635The attribute takes a list of string literals with the following accepted
5636values:
5637
5638- all values accepted by `-fno-sanitize=`;
5639- `coverage`, to disable SanitizerCoverage instrumentation.
5640
5641For example, `__attribute__((no_sanitize("address", "thread")))` specifies
5642that AddressSanitizer and ThreadSanitizer should not be applied to the function
5643or variable. Using `__attribute__((no_sanitize("coverage")))` specifies that
5644SanitizerCoverage should not be applied to the function.
5645
5646See {ref}`Controlling Code Generation <controlling-code-generation>` for a
5647full list of supported sanitizer flags.)reST";
5648
5649static const char AttrDoc_NoSpecializations[] = R"reST(``[[clang::no_specializations]]`` can be applied to function, class, or variable
5650templates for which neither an explicit specialization nor a partial specialization should be declared by users. This is primarily
5651used to diagnose user specializations of standard library type traits.)reST";
5652
5653static const char AttrDoc_NoSpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
5654that [Speculative Load Hardening][slh] is *not* needed for the function body.
5655This can also be applied to a method in Objective C. This attribute will take
5656precedence over the command line flag in the case where
5657{option}`-mspeculative-load-hardening` is specified.
5658
5659Warning: This attribute may not prevent Speculative Load Hardening from being
5660enabled for a function which inlines a function that has the
5661'speculative_load_hardening' attribute. This is intended to provide a
5662maximally conservative model where the code that is marked with the
5663'speculative_load_hardening' attribute will always (even when inlined)
5664be hardened. A user of this attribute may want to mark functions called by
5665a function they do not want to be hardened with the 'noinline' attribute.
5666
5667For example:
5668
5669```c
5670__attribute__((speculative_load_hardening))
5671int foo(int i) {
5672 return i;
5673}
5674
5675// Note: bar() may still have speculative load hardening enabled if
5676// foo() is inlined into bar(). Mark foo() with __attribute__((noinline))
5677// to avoid this situation.
5678__attribute__((no_speculative_load_hardening))
5679int bar(int i) {
5680 return foo(i);
5681}
5682```)reST";
5683
5684static const char AttrDoc_NoSplitStack[] = R"reST(The `no_split_stack` attribute disables the emission of the split stack
5685preamble for a particular function. It has no effect if `-fsplit-stack`
5686is not specified.)reST";
5687
5688static const char AttrDoc_NoStackProtector[] = R"reST(Clang supports the GNU style `__attribute__((no_stack_protector))` and Microsoft
5689style `__declspec(safebuffers)` attribute which disables
5690the stack protector on the specified function. This attribute is useful for
5691selectively disabling the stack protector on some functions when building with
5692`-fstack-protector` compiler option.
5693
5694For example, it disables the stack protector for the function `foo` but function
5695`bar` will still be built with the stack protector with the `-fstack-protector`
5696option.
5697
5698```c
5699int __attribute__((no_stack_protector))
5700foo (int x); // stack protection will be disabled for foo.
5701
5702int bar(int y); // bar can be built with the stack protector.
5703```)reST";
5704
5705static const char AttrDoc_NoThreadSafetyAnalysis[] = R"reST(No documentation.)reST";
5706
5707static const char AttrDoc_NoThrow[] = R"reST(Clang supports the GNU style `__attribute__((nothrow))` and Microsoft style
5708`__declspec(nothrow)` attribute as an equivalent of `noexcept` on function
5709declarations. This attribute informs the compiler that the annotated function
5710does not throw an exception. This prevents exception-unwinding. This attribute
5711is particularly useful on functions in the C Standard Library that are
5712guaranteed to not throw an exception.)reST";
5713
5714static const char AttrDoc_NoTrivialAutoVarInit[] = R"reST(The `__declspec(no_init_all)` attribute disables the automatic initialization
5715that the {option}`-ftrivial-auto-var-init` flag would have applied to locals in
5716a marked function, or instances of a marked type. Note that this attribute has
5717no effect for locals that are automatically initialized without the
5718{option}`-ftrivial-auto-var-init` flag.)reST";
5719
5720static const char AttrDoc_NoUniqueAddress[] = R"reST(The `no_unique_address` attribute allows tail padding in a non-static data
5721member to overlap other members of the enclosing class (and in the special
5722case when the type is empty, permits it to fully overlap other members).
5723The field is laid out as if a base class were encountered at the corresponding
5724point within the class (except that it does not share a vptr with the enclosing
5725object).
5726
5727Example usage:
5728
5729```c++
5730template<typename T, typename Alloc> struct my_vector {
5731 T *p;
5732 [[no_unique_address]] Alloc alloc;
5733 // ...
5734};
5735static_assert(sizeof(my_vector<int, std::allocator<int>>) == sizeof(int*));
5736```
5737
5738`[[no_unique_address]]` is a standard C++20 attribute. Clang supports its use
5739in C++11 onwards.
5740
5741On MSVC targets, `[[no_unique_address]]` is ignored; use
5742`[[msvc::no_unique_address]]` instead. Currently there is no guarantee of ABI
5743compatibility or stability with MSVC.)reST";
5744
5745static const char AttrDoc_NoUwtable[] = R"reST(Clang supports the `nouwtable` attribute which skips emitting
5746the unwind table entry for the specified function. This attribute is useful for
5747selectively emitting the unwind table entry on some functions when building with
5748`-funwind-tables` compiler option.)reST";
5749
5750static const char AttrDoc_NonAllocating[] = R"reST(Declares that a function or function type either does or does not allocate heap memory, according
5751to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5752is false, the attribute is equivalent to `allocating`.)reST";
5753
5754static const char AttrDoc_NonBlocking[] = R"reST(Declares that a function or function type either does or does not block in any way, according
5755to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5756is false, the attribute is equivalent to `blocking`.
5757
5758For the purposes of diagnostics, `nonblocking` is considered to include the
5759`nonallocating` guarantee and is therefore a "stronger" constraint or attribute.)reST";
5760
5761static const char AttrDoc_NonNull[] = R"reST(The `nonnull` attribute indicates that some function parameters must not be
5762null, and can be used in several different ways. It's original usage
5763([from GCC](https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes))
5764is as a function (or Objective-C method) attribute that specifies which
5765parameters of the function are nonnull in a comma-separated list. For example:
5766
5767```c
5768extern void * my_memcpy (void *dest, const void *src, size_t len)
5769 __attribute__((nonnull (1, 2)));
5770```
5771
5772Here, the `nonnull` attribute indicates that parameters 1 and 2
5773cannot have a null value. Omitting the parenthesized list of parameter indices
5774means that all parameters of pointer type cannot be null:
5775
5776```c
5777extern void * my_memcpy (void *dest, const void *src, size_t len)
5778 __attribute__((nonnull));
5779```
5780
5781Clang also allows the `nonnull` attribute to be placed directly on a function
5782(or Objective-C method) parameter, eliminating the need to specify the
5783parameter index ahead of type. For example:
5784
5785```c
5786extern void * my_memcpy (void *dest __attribute__((nonnull)),
5787 const void *src __attribute__((nonnull)), size_t len);
5788```
5789
5790Note that the `nonnull` attribute indicates that passing null to a non-null
5791parameter is undefined behavior, which the optimizer may take advantage of to,
5792e.g., remove null checks. The `_Nonnull` type qualifier indicates that a
5793pointer cannot be null in a more general manner (because it is part of the type
5794system) and does not imply undefined behavior, making it more widely applicable.)reST";
5795
5796static const char AttrDoc_NonString[] = R"reST(The `nonstring` attribute can be applied to the declaration of a variable or
5797a field whose type is a character pointer or character array to specify that
5798the buffer is not intended to behave like a null-terminated string. This will
5799silence diagnostics with code like:
5800
5801```c
5802char BadStr[3] = "foo"; // No space for the null terminator, diagnosed
5803__attribute__((nonstring)) char NotAStr[3] = "foo"; // Not diagnosed
5804```)reST";
5805
5806static const char AttrDoc_NotTailCalled[] = R"reST(The `not_tail_called` attribute prevents tail-call optimization on statically
5807bound calls. Objective-c methods, and functions marked as `always_inline`
5808cannot be marked as `not_tail_called`.
5809
5810For example, it prevents tail-call optimization in the following case:
5811
5812```c
5813int __attribute__((not_tail_called)) foo1(int);
5814
5815int foo2(int a) {
5816 return foo1(a); // No tail-call optimization on direct calls.
5817}
5818```
5819
5820However, it doesn't prevent tail-call optimization in this case:
5821
5822```c
5823int __attribute__((not_tail_called)) foo1(int);
5824
5825int foo2(int a) {
5826 int (*fn)(int) = &foo1;
5827
5828 // not_tail_called has no effect on an indirect call even if the call can
5829 // be resolved at compile time.
5830 return (*fn)(a);
5831}
5832```
5833
5834Generally, marking an overriding virtual function as `not_tail_called` is
5835not useful, because this attribute is a property of the static type. Calls
5836made through a pointer or reference to the base class type will respect
5837the `not_tail_called` attribute of the base class's member function,
5838regardless of the runtime destination of the call:
5839
5840```c++
5841struct Foo { virtual void f(); };
5842struct Bar : Foo {
5843 [[clang::not_tail_called]] void f() override;
5844};
5845void callera(Bar& bar) {
5846 Foo& foo = bar;
5847 // not_tail_called has no effect on here, even though the
5848 // underlying method is f from Bar.
5849 foo.f();
5850 bar.f(); // No tail-call optimization on here.
5851}
5852```)reST";
5853
5854static const char AttrDoc_OMPAllocateDecl[] = R"reST()reST";
5855
5856static const char AttrDoc_OMPAssume[] = R"reST(Clang supports the `[[omp::assume("assumption")]]` attribute to
5857provide additional information to the optimizer. The string-literal, here
5858"assumption", will be attached to the function declaration such that later
5859analysis and optimization passes can assume the "assumption" to hold.
5860This is similar to {ref}`__builtin_assume <langext-__builtin_assume>` but
5861instead of an expression that can be assumed to be non-zero, the assumption is
5862expressed as a string and it holds for the entire function.
5863
5864A function can have multiple assume attributes and they propagate from prior
5865declarations to later definitions. Multiple assumptions are aggregated into a
5866single comma separated string. Thus, one can provide multiple assumptions via
5867a comma separated string, i.a.,
5868`[[omp::assume("assumption1,assumption2")]]`.
5869
5870While LLVM plugins might provide more assumption strings, the default LLVM
5871optimization passes are aware of the following assumptions:
5872
5873```none
5874"omp_no_openmp"
5875"omp_no_openmp_routines"
5876"omp_no_parallelism"
5877"omp_no_openmp_constructs"
5878```
5879
5880The OpenMP standard defines the meaning of OpenMP assumptions ("omp_XYZ" is
5881spelled "XYZ" in the [OpenMP 5.1 Standard][openmp 5.1 standard]).
5882
5883[openmp 5.1 standard]: https://www.openmp.org/spec-html/5.1/openmpsu37.html#x56-560002.5.2)reST";
5884
5885static const char AttrDoc_OMPCaptureKind[] = R"reST()reST";
5886
5887static const char AttrDoc_OMPCaptureNoInit[] = R"reST()reST";
5888
5889static const char AttrDoc_OMPDeclareSimdDecl[] = R"reST(The `declare simd` construct can be applied to a function to enable the creation
5890of one or more versions that can process multiple arguments using SIMD
5891instructions from a single invocation in a SIMD loop. The `declare simd`
5892directive is a declarative directive. There may be multiple `declare simd`
5893directives for a function. The use of a `declare simd` construct on a function
5894enables the creation of SIMD versions of the associated function that can be
5895used to process multiple arguments from a single invocation from a SIMD loop
5896concurrently.
5897The syntax of the `declare simd` construct is as follows:
5898
5899```none
5900#pragma omp declare simd [clause[[,] clause] ...] new-line
5901[#pragma omp declare simd [clause[[,] clause] ...] new-line]
5902[...]
5903function definition or declaration
5904```
5905
5906where clause is one of the following:
5907
5908```none
5909simdlen(length)
5910linear(argument-list[:constant-linear-step])
5911aligned(argument-list[:alignment])
5912uniform(argument-list)
5913inbranch
5914notinbranch
5915```)reST";
5916
5917static const char AttrDoc_OMPDeclareTargetDecl[] = R"reST(The `declare target` directive specifies that variables and functions are mapped
5918to a device for OpenMP offload mechanism.
5919
5920The syntax of the declare target directive is as follows:
5921
5922```c
5923#pragma omp declare target new-line
5924declarations-definition-seq
5925#pragma omp end declare target new-line
5926```
5927
5928or
5929
5930```c
5931#pragma omp declare target (extended-list) new-line
5932```
5933
5934or
5935
5936```c
5937#pragma omp declare target clause[ [,] clause ... ] new-line
5938```
5939
5940where clause is one of the following:
5941
5942```c
5943to(extended-list)
5944link(list)
5945device_type(host | nohost | any)
5946```)reST";
5947
5948static const char AttrDoc_OMPDeclareVariant[] = R"reST(The `declare variant` directive declares a specialized variant of a base
5949function and specifies the context in which that specialized variant is used.
5950The declare variant directive is a declarative directive.
5951The syntax of the `declare variant` construct is as follows:
5952
5953```none
5954#pragma omp declare variant(variant-func-id) clause new-line
5955[#pragma omp declare variant(variant-func-id) clause new-line]
5956[...]
5957function definition or declaration
5958```
5959
5960where clause is one of the following:
5961
5962```none
5963match(context-selector-specification)
5964```
5965
5966and where `variant-func-id` is the name of a function variant that is either a
5967base language identifier or, for C++, a template-id.
5968
5969Clang provides the following context selector extensions, used via
5970`implementation={extension(EXTENSION)}`:
5971
5972```none
5973match_all
5974match_any
5975match_none
5976disable_implicit_base
5977allow_templates
5978bind_to_declaration
5979```
5980
5981The match extensions change when the *entire* context selector is considered a
5982match for an OpenMP context. The default is `all`, with `none` no trait in the
5983selector is allowed to be in the OpenMP context, with `any` a single trait in
5984both the selector and OpenMP context is sufficient. Only a single match
5985extension trait is allowed per context selector.
5986The disable extensions remove default effects of the `begin declare variant`
5987applied to a definition. If `disable_implicit_base` is given, we will not
5988introduce an implicit base function for a variant if no base function was
5989found. The variant is still generated but will never be called, due to the
5990absence of a base function and consequently calls to a base function.
5991The allow extensions change when the `begin declare variant` effect is
5992applied to a definition. If `allow_templates` is given, template function
5993definitions are considered as specializations of existing or assumed template
5994declarations with the same name. The template parameters for the base functions
5995are used to instantiate the specialization. If `bind_to_declaration` is given,
5996apply the same variant rules to function declarations. This allows the user to
5997override declarations with only a function declaration.)reST";
5998
5999static const char AttrDoc_OMPGroupPrivateDecl[] = R"reST()reST";
6000
6001static const char AttrDoc_OMPReferencedVar[] = R"reST()reST";
6002
6003static const char AttrDoc_OMPTargetIndirectCall[] = R"reST()reST";
6004
6005static const char AttrDoc_OMPThreadPrivateDecl[] = R"reST()reST";
6006
6007static const char AttrDoc_OSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6008(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6009convention (e.g. functions starting with "get" are assumed to return at
6010`+0`).
6011
6012It can be overridden using a family of the following attributes. In
6013Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6014a function communicates that the object is returned at `+1`, and the caller
6015is responsible for freeing it.
6016Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6017specifies that the object is returned at `+0` and the ownership remains with
6018the callee.
6019The annotation `__attribute__((ns_consumes_self))` specifies that
6020the Objective-C method call consumes the reference to `self`, e.g. by
6021attaching it to a supplied parameter.
6022Additionally, parameters can have an annotation
6023`__attribute__((ns_consumed))`, which specifies that passing an owned object
6024as that parameter effectively transfers the ownership, and the caller is no
6025longer responsible for it.
6026These attributes affect code generation when interacting with ARC code, and
6027they are used by the Clang Static Analyzer.
6028
6029In C programs using CoreFoundation, a similar set of attributes:
6030`__attribute__((cf_returns_not_retained))`,
6031`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6032have the same respective semantics when applied to CoreFoundation objects.
6033These attributes affect code generation when interacting with ARC code, and
6034they are used by the Clang Static Analyzer.
6035
6036Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6037the same attribute family is present:
6038`__attribute__((os_returns_not_retained))`,
6039`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6040with the same respective semantics.
6041Similar to `__attribute__((ns_consumes_self))`,
6042`__attribute__((os_consumes_this))` specifies that the method call consumes
6043the reference to "this" (e.g., when attaching it to a different object supplied
6044as a parameter).
6045Out parameters (parameters the function is meant to write into,
6046either via pointers-to-pointers or references-to-pointers)
6047may be annotated with `__attribute__((os_returns_retained))`
6048or `__attribute__((os_returns_not_retained))` which specifies that the object
6049written into the out parameter should (or respectively should not) be released
6050after use.
6051Since often out parameters may or may not be written depending on the exit
6052code of the function,
6053annotations `__attribute__((os_returns_retained_on_zero))`
6054and `__attribute__((os_returns_retained_on_non_zero))` specify that
6055an out parameter at `+1` is written if and only if the function returns a zero
6056(respectively non-zero) error code.
6057Observe that return-code-dependent out parameter annotations are only
6058available for retained out parameters, as non-retained object do not have to be
6059released by the callee.
6060These attributes are only used by the Clang Static Analyzer.
6061
6062The family of attributes `X_returns_X_retained` can be added to functions,
6063C++ methods, and Objective-C methods and properties.
6064Attributes `X_consumed` can be added to parameters of methods, functions,
6065and Objective-C methods.)reST";
6066
6067static const char AttrDoc_OSConsumesThis[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6068(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6069convention (e.g. functions starting with "get" are assumed to return at
6070`+0`).
6071
6072It can be overridden using a family of the following attributes. In
6073Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6074a function communicates that the object is returned at `+1`, and the caller
6075is responsible for freeing it.
6076Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6077specifies that the object is returned at `+0` and the ownership remains with
6078the callee.
6079The annotation `__attribute__((ns_consumes_self))` specifies that
6080the Objective-C method call consumes the reference to `self`, e.g. by
6081attaching it to a supplied parameter.
6082Additionally, parameters can have an annotation
6083`__attribute__((ns_consumed))`, which specifies that passing an owned object
6084as that parameter effectively transfers the ownership, and the caller is no
6085longer responsible for it.
6086These attributes affect code generation when interacting with ARC code, and
6087they are used by the Clang Static Analyzer.
6088
6089In C programs using CoreFoundation, a similar set of attributes:
6090`__attribute__((cf_returns_not_retained))`,
6091`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6092have the same respective semantics when applied to CoreFoundation objects.
6093These attributes affect code generation when interacting with ARC code, and
6094they are used by the Clang Static Analyzer.
6095
6096Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6097the same attribute family is present:
6098`__attribute__((os_returns_not_retained))`,
6099`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6100with the same respective semantics.
6101Similar to `__attribute__((ns_consumes_self))`,
6102`__attribute__((os_consumes_this))` specifies that the method call consumes
6103the reference to "this" (e.g., when attaching it to a different object supplied
6104as a parameter).
6105Out parameters (parameters the function is meant to write into,
6106either via pointers-to-pointers or references-to-pointers)
6107may be annotated with `__attribute__((os_returns_retained))`
6108or `__attribute__((os_returns_not_retained))` which specifies that the object
6109written into the out parameter should (or respectively should not) be released
6110after use.
6111Since often out parameters may or may not be written depending on the exit
6112code of the function,
6113annotations `__attribute__((os_returns_retained_on_zero))`
6114and `__attribute__((os_returns_retained_on_non_zero))` specify that
6115an out parameter at `+1` is written if and only if the function returns a zero
6116(respectively non-zero) error code.
6117Observe that return-code-dependent out parameter annotations are only
6118available for retained out parameters, as non-retained object do not have to be
6119released by the callee.
6120These attributes are only used by the Clang Static Analyzer.
6121
6122The family of attributes `X_returns_X_retained` can be added to functions,
6123C++ methods, and Objective-C methods and properties.
6124Attributes `X_consumed` can be added to parameters of methods, functions,
6125and Objective-C methods.)reST";
6126
6127static const char AttrDoc_OSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6128(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6129convention (e.g. functions starting with "get" are assumed to return at
6130`+0`).
6131
6132It can be overridden using a family of the following attributes. In
6133Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6134a function communicates that the object is returned at `+1`, and the caller
6135is responsible for freeing it.
6136Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6137specifies that the object is returned at `+0` and the ownership remains with
6138the callee.
6139The annotation `__attribute__((ns_consumes_self))` specifies that
6140the Objective-C method call consumes the reference to `self`, e.g. by
6141attaching it to a supplied parameter.
6142Additionally, parameters can have an annotation
6143`__attribute__((ns_consumed))`, which specifies that passing an owned object
6144as that parameter effectively transfers the ownership, and the caller is no
6145longer responsible for it.
6146These attributes affect code generation when interacting with ARC code, and
6147they are used by the Clang Static Analyzer.
6148
6149In C programs using CoreFoundation, a similar set of attributes:
6150`__attribute__((cf_returns_not_retained))`,
6151`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6152have the same respective semantics when applied to CoreFoundation objects.
6153These attributes affect code generation when interacting with ARC code, and
6154they are used by the Clang Static Analyzer.
6155
6156Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6157the same attribute family is present:
6158`__attribute__((os_returns_not_retained))`,
6159`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6160with the same respective semantics.
6161Similar to `__attribute__((ns_consumes_self))`,
6162`__attribute__((os_consumes_this))` specifies that the method call consumes
6163the reference to "this" (e.g., when attaching it to a different object supplied
6164as a parameter).
6165Out parameters (parameters the function is meant to write into,
6166either via pointers-to-pointers or references-to-pointers)
6167may be annotated with `__attribute__((os_returns_retained))`
6168or `__attribute__((os_returns_not_retained))` which specifies that the object
6169written into the out parameter should (or respectively should not) be released
6170after use.
6171Since often out parameters may or may not be written depending on the exit
6172code of the function,
6173annotations `__attribute__((os_returns_retained_on_zero))`
6174and `__attribute__((os_returns_retained_on_non_zero))` specify that
6175an out parameter at `+1` is written if and only if the function returns a zero
6176(respectively non-zero) error code.
6177Observe that return-code-dependent out parameter annotations are only
6178available for retained out parameters, as non-retained object do not have to be
6179released by the callee.
6180These attributes are only used by the Clang Static Analyzer.
6181
6182The family of attributes `X_returns_X_retained` can be added to functions,
6183C++ methods, and Objective-C methods and properties.
6184Attributes `X_consumed` can be added to parameters of methods, functions,
6185and Objective-C methods.)reST";
6186
6187static const char AttrDoc_OSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6188(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6189convention (e.g. functions starting with "get" are assumed to return at
6190`+0`).
6191
6192It can be overridden using a family of the following attributes. In
6193Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6194a function communicates that the object is returned at `+1`, and the caller
6195is responsible for freeing it.
6196Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6197specifies that the object is returned at `+0` and the ownership remains with
6198the callee.
6199The annotation `__attribute__((ns_consumes_self))` specifies that
6200the Objective-C method call consumes the reference to `self`, e.g. by
6201attaching it to a supplied parameter.
6202Additionally, parameters can have an annotation
6203`__attribute__((ns_consumed))`, which specifies that passing an owned object
6204as that parameter effectively transfers the ownership, and the caller is no
6205longer responsible for it.
6206These attributes affect code generation when interacting with ARC code, and
6207they are used by the Clang Static Analyzer.
6208
6209In C programs using CoreFoundation, a similar set of attributes:
6210`__attribute__((cf_returns_not_retained))`,
6211`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6212have the same respective semantics when applied to CoreFoundation objects.
6213These attributes affect code generation when interacting with ARC code, and
6214they are used by the Clang Static Analyzer.
6215
6216Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6217the same attribute family is present:
6218`__attribute__((os_returns_not_retained))`,
6219`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6220with the same respective semantics.
6221Similar to `__attribute__((ns_consumes_self))`,
6222`__attribute__((os_consumes_this))` specifies that the method call consumes
6223the reference to "this" (e.g., when attaching it to a different object supplied
6224as a parameter).
6225Out parameters (parameters the function is meant to write into,
6226either via pointers-to-pointers or references-to-pointers)
6227may be annotated with `__attribute__((os_returns_retained))`
6228or `__attribute__((os_returns_not_retained))` which specifies that the object
6229written into the out parameter should (or respectively should not) be released
6230after use.
6231Since often out parameters may or may not be written depending on the exit
6232code of the function,
6233annotations `__attribute__((os_returns_retained_on_zero))`
6234and `__attribute__((os_returns_retained_on_non_zero))` specify that
6235an out parameter at `+1` is written if and only if the function returns a zero
6236(respectively non-zero) error code.
6237Observe that return-code-dependent out parameter annotations are only
6238available for retained out parameters, as non-retained object do not have to be
6239released by the callee.
6240These attributes are only used by the Clang Static Analyzer.
6241
6242The family of attributes `X_returns_X_retained` can be added to functions,
6243C++ methods, and Objective-C methods and properties.
6244Attributes `X_consumed` can be added to parameters of methods, functions,
6245and Objective-C methods.)reST";
6246
6247static const char AttrDoc_OSReturnsRetainedOnNonZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6248(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6249convention (e.g. functions starting with "get" are assumed to return at
6250`+0`).
6251
6252It can be overridden using a family of the following attributes. In
6253Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6254a function communicates that the object is returned at `+1`, and the caller
6255is responsible for freeing it.
6256Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6257specifies that the object is returned at `+0` and the ownership remains with
6258the callee.
6259The annotation `__attribute__((ns_consumes_self))` specifies that
6260the Objective-C method call consumes the reference to `self`, e.g. by
6261attaching it to a supplied parameter.
6262Additionally, parameters can have an annotation
6263`__attribute__((ns_consumed))`, which specifies that passing an owned object
6264as that parameter effectively transfers the ownership, and the caller is no
6265longer responsible for it.
6266These attributes affect code generation when interacting with ARC code, and
6267they are used by the Clang Static Analyzer.
6268
6269In C programs using CoreFoundation, a similar set of attributes:
6270`__attribute__((cf_returns_not_retained))`,
6271`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6272have the same respective semantics when applied to CoreFoundation objects.
6273These attributes affect code generation when interacting with ARC code, and
6274they are used by the Clang Static Analyzer.
6275
6276Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6277the same attribute family is present:
6278`__attribute__((os_returns_not_retained))`,
6279`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6280with the same respective semantics.
6281Similar to `__attribute__((ns_consumes_self))`,
6282`__attribute__((os_consumes_this))` specifies that the method call consumes
6283the reference to "this" (e.g., when attaching it to a different object supplied
6284as a parameter).
6285Out parameters (parameters the function is meant to write into,
6286either via pointers-to-pointers or references-to-pointers)
6287may be annotated with `__attribute__((os_returns_retained))`
6288or `__attribute__((os_returns_not_retained))` which specifies that the object
6289written into the out parameter should (or respectively should not) be released
6290after use.
6291Since often out parameters may or may not be written depending on the exit
6292code of the function,
6293annotations `__attribute__((os_returns_retained_on_zero))`
6294and `__attribute__((os_returns_retained_on_non_zero))` specify that
6295an out parameter at `+1` is written if and only if the function returns a zero
6296(respectively non-zero) error code.
6297Observe that return-code-dependent out parameter annotations are only
6298available for retained out parameters, as non-retained object do not have to be
6299released by the callee.
6300These attributes are only used by the Clang Static Analyzer.
6301
6302The family of attributes `X_returns_X_retained` can be added to functions,
6303C++ methods, and Objective-C methods and properties.
6304Attributes `X_consumed` can be added to parameters of methods, functions,
6305and Objective-C methods.)reST";
6306
6307static const char AttrDoc_OSReturnsRetainedOnZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6308(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6309convention (e.g. functions starting with "get" are assumed to return at
6310`+0`).
6311
6312It can be overridden using a family of the following attributes. In
6313Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6314a function communicates that the object is returned at `+1`, and the caller
6315is responsible for freeing it.
6316Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6317specifies that the object is returned at `+0` and the ownership remains with
6318the callee.
6319The annotation `__attribute__((ns_consumes_self))` specifies that
6320the Objective-C method call consumes the reference to `self`, e.g. by
6321attaching it to a supplied parameter.
6322Additionally, parameters can have an annotation
6323`__attribute__((ns_consumed))`, which specifies that passing an owned object
6324as that parameter effectively transfers the ownership, and the caller is no
6325longer responsible for it.
6326These attributes affect code generation when interacting with ARC code, and
6327they are used by the Clang Static Analyzer.
6328
6329In C programs using CoreFoundation, a similar set of attributes:
6330`__attribute__((cf_returns_not_retained))`,
6331`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6332have the same respective semantics when applied to CoreFoundation objects.
6333These attributes affect code generation when interacting with ARC code, and
6334they are used by the Clang Static Analyzer.
6335
6336Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6337the same attribute family is present:
6338`__attribute__((os_returns_not_retained))`,
6339`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6340with the same respective semantics.
6341Similar to `__attribute__((ns_consumes_self))`,
6342`__attribute__((os_consumes_this))` specifies that the method call consumes
6343the reference to "this" (e.g., when attaching it to a different object supplied
6344as a parameter).
6345Out parameters (parameters the function is meant to write into,
6346either via pointers-to-pointers or references-to-pointers)
6347may be annotated with `__attribute__((os_returns_retained))`
6348or `__attribute__((os_returns_not_retained))` which specifies that the object
6349written into the out parameter should (or respectively should not) be released
6350after use.
6351Since often out parameters may or may not be written depending on the exit
6352code of the function,
6353annotations `__attribute__((os_returns_retained_on_zero))`
6354and `__attribute__((os_returns_retained_on_non_zero))` specify that
6355an out parameter at `+1` is written if and only if the function returns a zero
6356(respectively non-zero) error code.
6357Observe that return-code-dependent out parameter annotations are only
6358available for retained out parameters, as non-retained object do not have to be
6359released by the callee.
6360These attributes are only used by the Clang Static Analyzer.
6361
6362The family of attributes `X_returns_X_retained` can be added to functions,
6363C++ methods, and Objective-C methods and properties.
6364Attributes `X_consumed` can be added to parameters of methods, functions,
6365and Objective-C methods.)reST";
6366
6367static const char AttrDoc_ObjCBoxable[] = R"reST(Structs and unions marked with the `objc_boxable` attribute can be used
6368with the Objective-C boxed expression syntax, `@(...)`.
6369
6370**Usage**: `__attribute__((objc_boxable))`. This attribute
6371can only be placed on a declaration of a trivially-copyable struct or union:
6372
6373```objc
6374struct __attribute__((objc_boxable)) some_struct {
6375 int i;
6376};
6377union __attribute__((objc_boxable)) some_union {
6378 int i;
6379 float f;
6380};
6381typedef struct __attribute__((objc_boxable)) _some_struct some_struct;
6382
6383// ...
6384
6385some_struct ss;
6386NSValue *boxed = @(ss);
6387```)reST";
6388
6389static const char AttrDoc_ObjCBridge[] = R"reST(No documentation.)reST";
6390
6391static const char AttrDoc_ObjCBridgeMutable[] = R"reST(No documentation.)reST";
6392
6393static const char AttrDoc_ObjCBridgeRelated[] = R"reST(No documentation.)reST";
6394
6395static const char AttrDoc_ObjCClassStub[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
6396instantiated at runtime.
6397
6398Unlike `__attribute__((objc_runtime_visible))`, a class having this attribute
6399still has a "class stub" that is visible to the linker. This allows categories
6400to be defined. Static message sends with the class as a receiver use a special
6401access pattern to ensure the class is lazily instantiated from the class stub.
6402
6403Classes annotated with this attribute cannot be subclassed and cannot have
6404implementations defined for them. This attribute is intended for use in
6405Swift-generated headers for classes defined in Swift.
6406
6407Adding or removing this attribute to a class is an ABI-breaking change.)reST";
6408
6409static const char AttrDoc_ObjCDesignatedInitializer[] = R"reST(No documentation.)reST";
6410
6411static const char AttrDoc_ObjCDirect[] = R"reST(The `objc_direct` attribute can be used to mark an Objective-C method as
6412being *direct*. A direct method is treated statically like an ordinary method,
6413but dynamically it behaves more like a C function. This lowers some of the costs
6414associated with the method but also sacrifices some of the ordinary capabilities
6415of Objective-C methods.
6416
6417A message send of a direct method calls the implementation directly, as if it
6418were a C function, rather than using ordinary Objective-C method dispatch. This
6419is substantially faster and potentially allows the implementation to be inlined,
6420but it also means the method cannot be overridden in subclasses or replaced
6421dynamically, as ordinary Objective-C methods can.
6422
6423Furthermore, a direct method is not listed in the class's method lists. This
6424substantially reduces the code-size overhead of the method but also means it
6425cannot be called dynamically using ordinary Objective-C method dispatch at all;
6426in particular, this means that it cannot override a superclass method or satisfy
6427a protocol requirement.
6428
6429Because a direct method cannot be overridden, it is an error to perform
6430a `super` message send of one.
6431
6432Although a message send of a direct method causes the method to be called
6433directly as if it were a C function, it still obeys Objective-C semantics in other
6434ways:
6435
6436- If the receiver is `nil`, the message send does nothing and returns the zero value
6437 for the return type.
6438- A message send of a direct class method will cause the class to be initialized,
6439 including calling the `+initialize` method if present.
6440- The implicit `_cmd` parameter containing the method's selector is still defined.
6441 In order to minimize code-size costs, the implementation will not emit a reference
6442 to the selector if the parameter is unused within the method.
6443
6444Symbols for direct method implementations are implicitly given hidden
6445visibility, meaning that they can only be called within the same linkage unit.
6446
6447It is an error to do any of the following:
6448
6449- declare a direct method in a protocol,
6450- declare an override of a direct method with a method in a subclass,
6451- declare an override of a non-direct method with a direct method in a subclass,
6452- declare a method with different directness in different class interfaces, or
6453- implement a non-direct method (as declared in any class interface) with a direct method.
6454
6455If any of these rules would be violated if every method defined in an
6456`@implementation` within a single linkage unit were declared in an
6457appropriate class interface, the program is ill-formed with no diagnostic
6458required. If a violation of this rule is not diagnosed, behavior remains
6459well-defined; this paragraph is simply reserving the right to diagnose such
6460conflicts in the future, not to treat them as undefined behavior.
6461
6462Additionally, Clang will warn about any `@selector` expression that
6463names a selector that is only known to be used for direct methods.
6464
6465For the purpose of these rules, a "class interface" includes a class's primary
6466`@interface` block, its class extensions, its categories, its declared protocols,
6467and all the class interfaces of its superclasses.
6468
6469An Objective-C property can be declared with the `direct` property
6470attribute. If a direct property declaration causes an implicit declaration of
6471a getter or setter method (that is, if the given method is not explicitly
6472declared elsewhere), the method is declared to be direct.
6473
6474Some programmers may wish to make many methods direct at once. In order
6475to simplify this, the `objc_direct_members` attribute is provided; see its
6476documentation for more information.)reST";
6477
6478static const char AttrDoc_ObjCDirectMembers[] = R"reST(The `objc_direct_members` attribute can be placed on an Objective-C
6479`@interface` or `@implementation` to mark that methods declared
6480therein should be considered direct by default. See the documentation
6481for `objc_direct` for more information about direct methods.
6482
6483When `objc_direct_members` is placed on an `@interface` block, every
6484method in the block is considered to be declared as direct. This includes any
6485implicit method declarations introduced by property declarations. If the method
6486redeclares a non-direct method, the declaration is ill-formed, exactly as if the
6487method was annotated with the `objc_direct` attribute.
6488
6489When `objc_direct_members` is placed on an `@implementation` block,
6490methods defined in the block are considered to be declared as direct unless
6491they have been previously declared as non-direct in any interface of the class.
6492This includes the implicit method definitions introduced by synthesized
6493properties, including auto-synthesized properties.)reST";
6494
6495static const char AttrDoc_ObjCException[] = R"reST(No documentation.)reST";
6496
6497static const char AttrDoc_ObjCExplicitProtocolImpl[] = R"reST(No documentation.)reST";
6498
6499static const char AttrDoc_ObjCExternallyRetained[] = R"reST(The `objc_externally_retained` attribute can be applied to strong local
6500variables, functions, methods, or blocks to opt into
6501{ref}`externally-retained semantics <arc.misc.externally_retained>`.
6502
6503When applied to the definition of a function, method, or block, every parameter
6504of the function with implicit strong retainable object pointer type is
6505considered externally-retained, and becomes `const`. By explicitly annotating
6506a parameter with `__strong`, you can opt back into the default
6507non-externally-retained behavior for that parameter. For instance,
6508`first_param` is externally-retained below, but not `second_param`:
6509
6510```objc
6511__attribute__((objc_externally_retained))
6512void f(NSArray *first_param, __strong NSArray *second_param) {
6513 // ...
6514}
6515```
6516
6517Likewise, when applied to a strong local variable, that variable becomes
6518`const` and is considered externally-retained.
6519
6520When compiled without `-fobjc-arc`, this attribute is ignored.)reST";
6521
6522static const char AttrDoc_ObjCGC[] = R"reST(No documentation.)reST";
6523
6524static const char AttrDoc_ObjCIndependentClass[] = R"reST(No documentation.)reST";
6525
6526static const char AttrDoc_ObjCInertUnsafeUnretained[] = R"reST()reST";
6527
6528static const char AttrDoc_ObjCKindOf[] = R"reST(No documentation.)reST";
6529
6530static const char AttrDoc_ObjCMethodFamily[] = R"reST(Many methods in Objective-C have conventional meanings determined by their
6531selectors. It is sometimes useful to be able to mark a method as having a
6532particular conventional meaning despite not having the right selector, or as
6533not having the conventional meaning that its selector would suggest. For these
6534use cases, we provide an attribute to specifically describe the "method family"
6535that a method belongs to.
6536
6537**Usage**: `__attribute__((objc_method_family(X)))`, where `X` is one of
6538`none`, `alloc`, `copy`, `init`, `mutableCopy`, or `new`. This
6539attribute can only be placed at the end of a method declaration:
6540
6541```objc
6542- (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
6543```
6544
6545Users who do not wish to change the conventional meaning of a method, and who
6546merely want to document its non-standard retain and release semantics, should
6547use the retaining behavior attributes (`ns_returns_retained`,
6548`ns_returns_not_retained`, etc).
6549
6550Query for this feature with `__has_attribute(objc_method_family)`.)reST";
6551
6552static const char AttrDoc_ObjCNSObject[] = R"reST(No documentation.)reST";
6553
6554static const char AttrDoc_ObjCNonLazyClass[] = R"reST(This attribute can be added to an Objective-C `@interface` or
6555`@implementation` declaration to add the class to the list of non-lazily
6556initialized classes. A non-lazy class will be initialized eagerly when the
6557Objective-C runtime is loaded. This is required for certain system classes which
6558have instances allocated in non-standard ways, such as the classes for blocks
6559and constant strings. Adding this attribute is essentially equivalent to
6560providing a trivial `+load` method but avoids the (fairly small) load-time
6561overheads associated with defining and calling such a method.)reST";
6562
6563static const char AttrDoc_ObjCNonRuntimeProtocol[] = R"reST(The `objc_non_runtime_protocol` attribute can be used to mark that an
6564Objective-C protocol is only used during static type-checking and doesn't need
6565to be represented dynamically. This avoids several small code-size and run-time
6566overheads associated with handling the protocol's metadata. A non-runtime
6567protocol cannot be used as the operand of a `@protocol` expression, and
6568dynamic attempts to find it with `objc_getProtocol` will fail.
6569
6570If a non-runtime protocol inherits from any ordinary protocols, classes and
6571derived protocols that declare conformance to the non-runtime protocol will
6572dynamically list their conformance to those bare protocols.)reST";
6573
6574static const char AttrDoc_ObjCOwnership[] = R"reST(No documentation.)reST";
6575
6576static const char AttrDoc_ObjCPreciseLifetime[] = R"reST(No documentation.)reST";
6577
6578static const char AttrDoc_ObjCRequiresPropertyDefs[] = R"reST(No documentation.)reST";
6579
6580static const char AttrDoc_ObjCRequiresSuper[] = R"reST(Some Objective-C classes allow a subclass to override a particular method in a
6581parent class but expect that the overriding method also calls the overridden
6582method in the parent class. For these cases, we provide an attribute to
6583designate that a method requires a "call to `super`" in the overriding
6584method in the subclass.
6585
6586**Usage**: `__attribute__((objc_requires_super))`. This attribute can only
6587be placed at the end of a method declaration:
6588
6589```objc
6590- (void)foo __attribute__((objc_requires_super));
6591```
6592
6593This attribute can only be applied the method declarations within a class, and
6594not a protocol. Currently this attribute does not enforce any placement of
6595where the call occurs in the overriding method (such as in the case of
6596`-dealloc` where the call must appear at the end). It checks only that it
6597exists.
6598
6599Note that on both OS X and iOS that the Foundation framework provides a
6600convenience macro `NS_REQUIRES_SUPER` that provides syntactic sugar for this
6601attribute:
6602
6603```objc
6604- (void)foo NS_REQUIRES_SUPER;
6605```
6606
6607This macro is conditionally defined depending on the compiler's support for
6608this attribute. If the compiler does not support the attribute the macro
6609expands to nothing.
6610
6611Operationally, when a method has this annotation the compiler will warn if the
6612implementation of an override in a subclass does not call super. For example:
6613
6614```objc
6615warning: method possibly missing a [super AnnotMeth] call
6616- (void) AnnotMeth{};
6617 ^
6618```)reST";
6619
6620static const char AttrDoc_ObjCReturnsInnerPointer[] = R"reST(No documentation.)reST";
6621
6622static const char AttrDoc_ObjCRootClass[] = R"reST(No documentation.)reST";
6623
6624static const char AttrDoc_ObjCRuntimeName[] = R"reST(By default, the Objective-C interface or protocol identifier is used
6625in the metadata name for that object. The `objc_runtime_name`
6626attribute allows annotated interfaces or protocols to use the
6627specified string argument in the object's metadata name instead of the
6628default name.
6629
6630**Usage**: `__attribute__((objc_runtime_name("MyLocalName")))`. This attribute
6631can only be placed before an @protocol or @interface declaration:
6632
6633```objc
6634__attribute__((objc_runtime_name("MyLocalName")))
6635@interface Message
6636@end
6637```)reST";
6638
6639static const char AttrDoc_ObjCRuntimeVisible[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
6640visible to the Objective-C runtime but not to the linker. Classes annotated
6641with this attribute cannot be subclassed and cannot have categories defined for
6642them.)reST";
6643
6644static const char AttrDoc_ObjCSubclassingRestricted[] = R"reST(This attribute can be added to an Objective-C `@interface` declaration to
6645ensure that this class cannot be subclassed.)reST";
6646
6647static const char AttrDoc_OpenACCRoutineAnnot[] = R"reST()reST";
6648
6649static const char AttrDoc_OpenACCRoutineDecl[] = R"reST()reST";
6650
6651static const char AttrDoc_OpenCLAccess[] = R"reST(The access qualifiers must be used with image object arguments or pipe arguments
6652to declare if they are being read or written by a kernel or function.
6653
6654The read_only/\_\_read_only, write_only/\_\_write_only and read_write/\_\_read_write
6655names are reserved for use as access qualifiers and shall not be used otherwise.
6656
6657```c
6658kernel void
6659foo (read_only image2d_t imageA,
6660 write_only image2d_t imageB) {
6661 ...
6662}
6663```
6664
6665In the above example imageA is a read-only 2D image object, and imageB is a
6666write-only 2D image object.
6667
6668The read_write (or \_\_read_write) qualifier can not be used with pipe.
6669
6670More details can be found in the OpenCL C language Spec v2.0, Section 6.6.)reST";
6671
6672static const char AttrDoc_OpenCLConstantAddressSpace[] = R"reST(The constant address space attribute signals that an object is located in
6673a constant (non-modifiable) memory region. It is available to all work items.
6674Any type can be annotated with the constant address space attribute. Objects
6675with the constant address space qualifier can be declared in any scope and must
6676have an initializer.)reST";
6677
6678static const char AttrDoc_OpenCLGenericAddressSpace[] = R"reST(The generic address space attribute is only available with OpenCL v2.0 and later.
6679It can be used with pointer types. Variables in global and local scope and
6680function parameters in non-kernel functions can have the generic address space
6681type attribute. It is intended to be a placeholder for any other address space
6682except for '\_\_constant' in OpenCL code which can be used with multiple address
6683spaces.)reST";
6684
6685static const char AttrDoc_OpenCLGlobalAddressSpace[] = R"reST(The global address space attribute specifies that an object is allocated in
6686global memory, which is accessible by all work items. The content stored in this
6687memory area persists between kernel executions. Pointer types to the global
6688address space are allowed as function parameters or local variables. Starting
6689with OpenCL v2.0, the global address space can be used with global (program
6690scope) variables and static local variable as well.)reST";
6691
6692static const char AttrDoc_OpenCLGlobalDeviceAddressSpace[] = R"reST(The `global_device` and `global_host` address space attributes specify that
6693an object is allocated in global memory on the device/host. It helps to
6694distinguish USM (Unified Shared Memory) pointers that access global device
6695memory from those that access global host memory. These new address spaces are
6696a subset of the `__global/opencl_global` address space, the full address space
6697set model for OpenCL 2.0 with the extension looks as follows:
6698
6699```text
6700generic->global->host
6701 ->device
6702 ->private
6703 ->local
6704constant
6705```
6706
6707As `global_device` and `global_host` are a subset of
6708`__global/opencl_global` address spaces it is allowed to convert
6709`global_device` and `global_host` address spaces to
6710`__global/opencl_global` address spaces (following ISO/IEC TR 18037 5.1.3
6711"Address space nesting and rules for pointers").
6712
6713These attributes are deprecated and may be removed in a future version of Clang.)reST";
6714
6715static const char AttrDoc_OpenCLGlobalHostAddressSpace[] = R"reST(The `global_device` and `global_host` address space attributes specify that
6716an object is allocated in global memory on the device/host. It helps to
6717distinguish USM (Unified Shared Memory) pointers that access global device
6718memory from those that access global host memory. These new address spaces are
6719a subset of the `__global/opencl_global` address space, the full address space
6720set model for OpenCL 2.0 with the extension looks as follows:
6721
6722```text
6723generic->global->host
6724 ->device
6725 ->private
6726 ->local
6727constant
6728```
6729
6730As `global_device` and `global_host` are a subset of
6731`__global/opencl_global` address spaces it is allowed to convert
6732`global_device` and `global_host` address spaces to
6733`__global/opencl_global` address spaces (following ISO/IEC TR 18037 5.1.3
6734"Address space nesting and rules for pointers").
6735
6736These attributes are deprecated and may be removed in a future version of Clang.)reST";
6737
6738static const char AttrDoc_OpenCLIntelReqdSubGroupSize[] = R"reST(The optional attribute intel_reqd_sub_group_size can be used to indicate that
6739the kernel must be compiled and executed with the specified subgroup size. When
6740this attribute is present, get_max_sub_group_size() is guaranteed to return the
6741specified integer value. This is important for the correctness of many subgroup
6742algorithms, and in some cases may be used by the compiler to generate more optimal
6743code. See `cl_intel_required_subgroup_size
6744<https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.txt>`
6745for details.)reST";
6746
6747static const char AttrDoc_OpenCLLocalAddressSpace[] = R"reST(The local address space specifies that an object is allocated in the local (work
6748group) memory area, which is accessible to all work items in the same work
6749group. The content stored in this memory region is not accessible after
6750the kernel execution ends. In a kernel function scope, any variable can be in
6751the local address space. In other scopes, only pointer types to the local address
6752space are allowed. Local address space variables cannot have an initializer.)reST";
6753
6754static const char AttrDoc_OpenCLPrivateAddressSpace[] = R"reST(The private address space specifies that an object is allocated in the private
6755(work item) memory. Other work items cannot access the same memory area and its
6756content is destroyed after work item execution ends. Local variables can be
6757declared in the private address space. Function arguments are always in the
6758private address space. Kernel function arguments of a pointer or an array type
6759cannot point to the private address space.)reST";
6760
6761static const char AttrDoc_OpenCLUnrollHint[] = R"reST(The opencl_unroll_hint attribute qualifier can be used to specify that a loop
6762(for, while and do loops) can be unrolled. This attribute qualifier can be
6763used to specify full unrolling or partial unrolling by a specified amount.
6764This is a compiler hint and the compiler may ignore this directive. See
6765[OpenCL v2.0](https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf)
6766s6.11.5 for details.)reST";
6767
6768static const char AttrDoc_OptimizeNone[] = R"reST(The `optnone` attribute suppresses essentially all optimizations
6769on a function or method, regardless of the optimization level applied to
6770the compilation unit as a whole. This is particularly useful when you
6771need to debug a particular function, but it is infeasible to build the
6772entire application without optimization. Avoiding optimization on the
6773specified function can improve the quality of the debugging information
6774for that function.
6775
6776This attribute is incompatible with the `always_inline` and `minsize`
6777attributes.
6778
6779Note that this attribute does not apply recursively to nested functions such as
6780lambdas or blocks when using declaration-specific attribute syntaxes such as double
6781square brackets (`[[]]`) or `__attribute__`. The `#pragma` syntax can be
6782used to apply the attribute to all functions, including nested functions, in a
6783range of source code.)reST";
6784
6785static const char AttrDoc_OverflowBehavior[] = R"reST(The `overflow_behavior` attribute provides fine-grained, type-level control
6786over how arithmetic operations on an integer type behave on overflow. It may be
6787applied to a `typedef`, to a variable or data member, or to an integer type
6788directly, and accepts one of two behaviors as its argument:
6789
6790- `wrap`: arithmetic on the attributed type wraps on overflow, using two's
6791 complement semantics. This is equivalent to `-fwrapv` but scoped to the
6792 attributed type, and works for both signed and unsigned types. UBSan's
6793 `signed-integer-overflow`, `unsigned-integer-overflow`,
6794 `implicit-signed-integer-truncation`, and
6795 `implicit-unsigned-integer-truncation` checks are suppressed for the type.
6796- `trap`: arithmetic on the attributed type is checked for overflow, enabling
6797 overflow checks for the type even when `-fwrapv` is in effect globally.
6798
6799```c++
6800typedef unsigned int __attribute__((overflow_behavior(trap))) non_wrapping_uint;
6801
6802non_wrapping_uint add_one(non_wrapping_uint a) {
6803 return a + 1; // Overflow is checked for this operation.
6804}
6805
6806int mul_alot(int n) {
6807 int __attribute__((overflow_behavior(wrap))) a = n;
6808 return a * 1337; // Overflow is not checked and is well-defined.
6809}
6810```
6811
6812The keyword spellings `__ob_wrap` and `__ob_trap` are equivalent to
6813`overflow_behavior(wrap)` and `overflow_behavior(trap)` respectively.
6814
6815The attribute wholly overrides global flags (`-ftrapv`, `-fwrapv`,
6816sanitizers, and Sanitizer Special Case Lists) for the attributed type. It can
6817only be applied to integer types.
6818
6819This feature is experimental and must be enabled with the `-cc1` option
6820`-fexperimental-overflow-behavior-types`. For full details on promotion and
6821conversion rules, pointer semantics, diagnostics, and interaction with
6822sanitizers, see {doc}`OverflowBehaviorTypes`.)reST";
6823
6824static const char AttrDoc_Overloadable[] = R"reST(Clang provides support for C++ function overloading in C. Function overloading
6825in C is introduced using the `overloadable` attribute. For example, one
6826might provide several overloaded versions of a `tgsin` function that invokes
6827the appropriate standard function computing the sine of a value with `float`,
6828`double`, or `long double` precision:
6829
6830```c
6831#include <math.h>
6832float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
6833double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
6834long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
6835```
6836
6837Given these declarations, one can call `tgsin` with a `float` value to
6838receive a `float` result, with a `double` to receive a `double` result,
6839etc. Function overloading in C follows the rules of C++ function overloading
6840to pick the best overload given the call arguments, with a few C-specific
6841semantics:
6842
6843- Conversion from `float` or `double` to `long double` is ranked as a
6844 floating-point promotion (per C99) rather than as a floating-point conversion
6845 (as in C++).
6846- A conversion from a pointer of type `T*` to a pointer of type `U*` is
6847 considered a pointer conversion (with conversion rank) if `T` and `U` are
6848 compatible types.
6849- A conversion from type `T` to a value of type `U` is permitted if `T`
6850 and `U` are compatible types. This conversion is given "conversion" rank.
6851- If no viable candidates are otherwise available, we allow a conversion from a
6852 pointer of type `T*` to a pointer of type `U*`, where `T` and `U` are
6853 incompatible. This conversion is ranked below all other types of conversions.
6854 Please note: `U` lacking qualifiers that are present on `T` is sufficient
6855 for `T` and `U` to be incompatible.
6856
6857The declaration of `overloadable` functions is restricted to function
6858declarations and definitions. If a function is marked with the `overloadable`
6859attribute, then all declarations and definitions of functions with that name,
6860except for at most one (see the note below about unmarked overloads), must have
6861the `overloadable` attribute. In addition, redeclarations of a function with
6862the `overloadable` attribute must have the `overloadable` attribute, and
6863redeclarations of a function without the `overloadable` attribute must *not*
6864have the `overloadable` attribute. e.g.,
6865
6866```c
6867int f(int) __attribute__((overloadable));
6868float f(float); // error: declaration of "f" must have the "overloadable" attribute
6869int f(int); // error: redeclaration of "f" must have the "overloadable" attribute
6870
6871int g(int) __attribute__((overloadable));
6872int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
6873
6874int h(int);
6875int h(int) __attribute__((overloadable)); // error: declaration of "h" must not
6876 // have the "overloadable" attribute
6877```
6878
6879Functions marked `overloadable` must have prototypes. Therefore, the
6880following code is ill-formed:
6881
6882```c
6883int h() __attribute__((overloadable)); // error: h does not have a prototype
6884```
6885
6886However, `overloadable` functions are allowed to use a ellipsis even if there
6887are no named parameters (as is permitted in C++). This feature is particularly
6888useful when combined with the `unavailable` attribute:
6889
6890```c++
6891void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
6892```
6893
6894Functions declared with the `overloadable` attribute have their names mangled
6895according to the same rules as C++ function names. For example, the three
6896`tgsin` functions in our motivating example get the mangled names
6897`_Z5tgsinf`, `_Z5tgsind`, and `_Z5tgsine`, respectively. There are two
6898caveats to this use of name mangling:
6899
6900- Future versions of Clang may change the name mangling of functions overloaded
6901 in C, so you should not depend on an specific mangling. To be completely
6902 safe, we strongly urge the use of `static inline` with `overloadable`
6903 functions.
6904- The `overloadable` attribute has almost no meaning when used in C++,
6905 because names will already be mangled and functions are already overloadable.
6906 However, when an `overloadable` function occurs within an `extern "C"`
6907 linkage specification, its name *will* be mangled in the same way as it
6908 would in C.
6909
6910For the purpose of backwards compatibility, at most one function with the same
6911name as other `overloadable` functions may omit the `overloadable`
6912attribute. In this case, the function without the `overloadable` attribute
6913will not have its name mangled.
6914
6915For example:
6916
6917```c
6918// Notes with mangled names assume Itanium mangling.
6919int f(int);
6920int f(double) __attribute__((overloadable));
6921void foo() {
6922 f(5); // Emits a call to f (not _Z1fi, as it would with an overload that
6923 // was marked with overloadable).
6924 f(1.0); // Emits a call to _Z1fd.
6925}
6926```
6927
6928Support for unmarked overloads is not present in some versions of clang. You may
6929query for it using `__has_extension(overloadable_unmarked)`.
6930
6931Query for this attribute with `__has_attribute(overloadable)`.)reST";
6932
6933static const char AttrDoc_Override[] = R"reST()reST";
6934
6935static const char AttrDoc_Owner[] = R"reST(:::{Note}
6936This attribute is experimental and its effect on analysis is subject to change in
6937a future version of clang.
6938:::
6939
6940The attribute `[[gsl::Owner(T)]]` applies to structs and classes that own an
6941object of type `T`:
6942
6943```
6944class [[gsl::Owner(int)]] IntOwner {
6945private:
6946 int value;
6947public:
6948 int *getInt() { return &value; }
6949};
6950```
6951
6952The argument `T` is optional and is ignored.
6953This attribute may be used by analysis tools and has no effect on code
6954generation. A `void` argument means that the class can own any type.
6955
6956See [Pointer] for an example.)reST";
6957
6958static const char AttrDoc_Ownership[] = R"reST(:::{note}
6959In order for the Clang Static Analyzer to acknowledge these attributes, the
6960`Optimistic` config needs to be set to true for the checker
6961`unix.DynamicMemoryModeling`:
6962
6963`-Xclang -analyzer-config -Xclang unix.DynamicMemoryModeling:Optimistic=true`
6964:::
6965
6966These attributes are used by the Clang Static Analyzer's dynamic memory modeling
6967facilities to mark custom allocating/deallocating functions.
6968
6969All 3 attributes' first parameter of type string is the type of the allocation:
6970`malloc`, `new`, etc. to allow for catching {ref}`mismatched deallocation
6971<unix-MismatchedDeallocator>` bugs. The allocation type can be any string, e.g.
6972a function annotated with
6973returning a piece of memory of type `lasagna` but freed with a function
6974annotated to release `cheese` typed memory will result in mismatched
6975deallocation warning.
6976
6977The (currently) only allocation type having special meaning is `malloc` --
6978the Clang Static Analyzer makes sure that allocating functions annotated with
6979`malloc` are treated like they used the standard `malloc()`, and can be
6980safely deallocated with the standard `free()`.
6981
6982- Use `ownership_returns` to mark a function as an allocating function.
6983 It takes 1 or 2 arguments.
6984 The first argument is a user-provided identifier representing the "kind" of the allocation.
6985 This is basically what is enforced when checking the deallocation. This is mandatory.
6986 The second argument is optional.
6987 It represents the index of the parameter that represents the allocation size in bytes (counting from 1).
6988 The referenced parameter must have some integral type.
6989 This attribute may appear at most once per declaration.
6990 If this argument is not set, then tooling, such as the Clang Static Analyzer,
6991 won't be able to reason about the size of the allocation, thus check potential out-of-bounds accesses.
6992 However, such tooling could still warn if the wrong deallocation function
6993 was used for the `ownership_returns` attributed resource.
6994 If forward declarations have this attribute, those must have the same arguments.
6995- Use `ownership_takes` to mark a function as a deallocating function. Takes 2
6996 arguments: the allocation type, and the index of the parameter that is being
6997 deallocated (counting from 1).
6998- Use `ownership_holds` to mark that a function takes over the ownership of a
6999 piece of memory and will free it at some unspecified point in the future. Like
7000 `ownership_takes`, this takes 2 arguments: the allocation type, and the
7001 index of the parameter whose ownership will be taken over (counting from 1).
7002
7003The annotations `ownership_takes` and `ownership_holds` both prevent memory
7004leak reports (concerning the specified parameter); the difference between them
7005is that using taken memory is a use-after-free error, while using held memory
7006is assumed to be legitimate. However, releasing the held memory or passing it
7007to another holding call is reported by the analyzer as an "attempt to release
7008non-owned memory".
7009
7010Example:
7011
7012```c
7013// Denotes that my_malloc will return with a dynamically allocated piece of
7014// memory using malloc().
7015void __attribute((ownership_returns(malloc))) *my_malloc(size_t sz);
7016
7017// 'sz' (parameter 1) is the allocation size.
7018void __attribute((ownership_returns(malloc, 1))) *my_sized_malloc(size_t sz);
7019
7020// Denotes that my_free will deallocate its argument using free().
7021void __attribute((ownership_takes(malloc, 1))) my_free(void *);
7022
7023// Denotes that my_hold will take over the ownership of its argument that was
7024// allocated via malloc().
7025void __attribute((ownership_holds(malloc, 1))) my_hold(void *);
7026```
7027
7028Further reading about dynamic memory modeling in the Clang Static Analyzer is
7029found in these checker docs:
7030{ref}`unix.Malloc <unix-Malloc>`, {ref}`unix.MallocSizeof <unix-MallocSizeof>`,
7031{ref}`unix.MismatchedDeallocator <unix-MismatchedDeallocator>`,
7032{ref}`cplusplus.NewDelete <cplusplus-NewDelete>`,
7033{ref}`cplusplus.NewDeleteLeaks <cplusplus-NewDeleteLeaks>`,
7034{ref}`optin.taint.TaintedAlloc <optin-taint-TaintedAlloc>`.
7035Mind that many more checkers are affected by dynamic memory modeling changes to
7036some extent.
7037
7038Further reading for other annotations:
7039{doc}`Static Analyzer source annotations <analyzer/user-docs/Annotations>`.)reST";
7040
7041static const char AttrDoc_Packed[] = R"reST(No documentation.)reST";
7042
7043static const char AttrDoc_ParamTypestate[] = R"reST(This attribute specifies expectations about function parameters. Calls to an
7044function with annotated parameters will issue a warning if the corresponding
7045argument isn't in the expected state. The attribute is also used to set the
7046initial state of the parameter when analyzing the function's body.)reST";
7047
7048static const char AttrDoc_Pascal[] = R"reST(No documentation.)reST";
7049
7050static const char AttrDoc_PassObjectSize[] = R"reST(:::{Note}
7051The mangling of functions with parameters that are annotated with
7052`pass_object_size` is subject to change. You can get around this by
7053using `__asm__("foo")` to explicitly name your functions, thus preserving
7054your ABI; also, non-overloadable C functions with `pass_object_size` are
7055not mangled.
7056:::
7057
7058The `pass_object_size(Type)` attribute can be placed on function parameters to
7059instruct clang to call `__builtin_object_size(param, Type)` at each callsite
7060of said function, and implicitly pass the result of this call in as an invisible
7061argument of type `size_t` directly after the parameter annotated with
7062`pass_object_size`. Clang will also replace any calls to
7063`__builtin_object_size(param, Type)` in the function by said implicit
7064parameter.
7065
7066Example usage:
7067
7068```c
7069int bzero1(char *const p __attribute__((pass_object_size(0))))
7070 __attribute__((noinline)) {
7071 int i = 0;
7072 for (/**/; i < (int)__builtin_object_size(p, 0); ++i) {
7073 p[i] = 0;
7074 }
7075 return i;
7076}
7077
7078int main() {
7079 char chars[100];
7080 int n = bzero1(&chars[0]);
7081 assert(n == sizeof(chars));
7082 return 0;
7083}
7084```
7085
7086If successfully evaluating `__builtin_object_size(param, Type)` at the
7087callsite is not possible, then the "failed" value is passed in. So, using the
7088definition of `bzero1` from above, the following code would exit cleanly:
7089
7090```c
7091int main2(int argc, char *argv[]) {
7092 int n = bzero1(argv);
7093 assert(n == -1);
7094 return 0;
7095}
7096```
7097
7098`pass_object_size` plays a part in overload resolution. If two overload
7099candidates are otherwise equally good, then the overload with one or more
7100parameters with `pass_object_size` is preferred. This implies that the choice
7101between two identical overloads both with `pass_object_size` on one or more
7102parameters will always be ambiguous; for this reason, having two such overloads
7103is illegal. For example:
7104
7105```c++
7106#define PS(N) __attribute__((pass_object_size(N)))
7107// OK
7108void Foo(char *a, char *b); // Overload A
7109// OK -- overload A has no parameters with pass_object_size.
7110void Foo(char *a PS(0), char *b PS(0)); // Overload B
7111// Error -- Same signature (sans pass_object_size) as overload B, and both
7112// overloads have one or more parameters with the pass_object_size attribute.
7113void Foo(void *a PS(0), void *b);
7114
7115// OK
7116void Bar(void *a PS(0)); // Overload C
7117// OK
7118void Bar(char *c PS(1)); // Overload D
7119
7120void main() {
7121 char known[10], *unknown;
7122 Foo(unknown, unknown); // Calls overload B
7123 Foo(known, unknown); // Calls overload B
7124 Foo(unknown, known); // Calls overload B
7125 Foo(known, known); // Calls overload B
7126
7127 Bar(known); // Calls overload D
7128 Bar(unknown); // Calls overload D
7129}
7130```
7131
7132Currently, `pass_object_size` is a bit restricted in terms of its usage:
7133
7134- Only one use of `pass_object_size` is allowed per parameter.
7135- It is an error to take the address of a function with `pass_object_size` on
7136 any of its parameters. If you wish to do this, you can create an overload
7137 without `pass_object_size` on any parameters.
7138- It is an error to apply the `pass_object_size` attribute to parameters that
7139 are not pointers. Additionally, any parameter that `pass_object_size` is
7140 applied to must be marked `const` at its function's definition.
7141
7142Clang also supports the `pass_dynamic_object_size` attribute, which behaves
7143identically to `pass_object_size`, but evaluates a call to
7144`__builtin_dynamic_object_size` at the callee instead of
7145`__builtin_object_size`. `__builtin_dynamic_object_size` provides some extra
7146runtime checks when the object size can't be determined at compile-time. You can
7147read more about `__builtin_dynamic_object_size` in
7148{ref}`Evaluating Object Size <langext-evaluating-object-size>`.)reST";
7149
7150static const char AttrDoc_PatchableFunctionEntry[] = R"reST(`__attribute__((patchable_function_entry(N,M,Section)))` is used to generate M
7151NOPs before the function entry and N-M NOPs after the function entry, with a record of
7152the entry stored in section `Section`. This attribute takes precedence over the
7153command line option `-fpatchable-function-entry=N,M,Section`. `M` defaults to 0
7154if omitted. `Section` defaults to the `-fpatchable-function-entry` section name if
7155set, or to `__patchable_function_entries` otherwise.
7156
7157This attribute is only supported on
7158aarch64/aarch64-be/loongarch32/loongarch64/riscv32/riscv64/i386/x86-64/ppc/ppc64/ppc64le/s390x targets.
7159For ppc/ppc64 targets, AIX is still not supported.)reST";
7160
7161static const char AttrDoc_Pcs[] = R"reST(On ARM targets, this attribute can be used to select calling conventions
7162similar to `stdcall` on x86. Valid parameter values are "aapcs" and
7163"aapcs-vfp".)reST";
7164
7165static const char AttrDoc_Personality[] = R"reST(`__attribute__((personality(<routine>)))` is used to specify a personality
7166routine that is different from the language that is being used to implement the
7167function. This is a targeted, low-level feature aimed at language runtime
7168implementors who write runtime support code in C/C++ but need that code to
7169participate in a foreign language's exception-handling or unwinding model.
7170
7171A personality routine is a language-specific callback attached to each stack
7172frame that the unwinder invokes to determine whether that frame handles a given
7173exception and what cleanup actions to perform. It effectively colors the
7174language-agnostic unwinding mechanism with language-specific semantics, enabling
7175different languages to coexist on the same call stack while each interpreting
7176exceptions according to their own rules.)reST";
7177
7178static const char AttrDoc_Pointer[] = R"reST(:::{Note}
7179This attribute is experimental and its effect on analysis is subject to change in
7180a future version of clang.
7181:::
7182
7183The attribute `[[gsl::Pointer(T)]]` applies to structs and classes that behave
7184like pointers to an object of type `T`:
7185
7186```
7187class [[gsl::Pointer(int)]] IntPointer {
7188private:
7189 int *valuePointer;
7190public:
7191 IntPointer(const IntOwner&);
7192 int *getInt() { return valuePointer; }
7193};
7194```
7195
7196The argument `T` is optional and is ignored.
7197This attribute may be used by analysis tools and has no effect on code
7198generation. A `void` argument means that the pointer can point to any type.
7199
7200Example:
7201When constructing an instance of a class annotated like this (a Pointer) from
7202an instance of a class annotated with `[[gsl::Owner]]` (an Owner),
7203then the analysis will consider the Pointer to point inside the Owner.
7204When the Owner's lifetime ends, it will consider the Pointer to be dangling.
7205
7206```c++
7207int f() {
7208 IntPointer P(IntOwner{}); // P "points into" a temporary IntOwner object
7209 P.getInt(); // P is dangling
7210}
7211```
7212
7213**Transparent Member Functions**
7214
7215The analysis automatically tracks certain member functions of `[[gsl::Pointer]]` types
7216that provide transparent access to the pointed-to object. These include:
7217
7218- Dereference operators: `operator*`, `operator->`
7219- Data access methods: `data()`, `c_str()`, `get()`
7220- Iterator operations: `begin()`, `end()`, `rbegin()`, `rend()`, `cbegin()`, `cend()`, `crbegin()`, `crend()`, `operator+`, `operator-`, `operator++`, `operator--`
7221
7222When these methods return pointers, view types, or references, the analysis treats them as
7223transparently borrowing from the same object that the pointer itself borrows from,
7224enabling detection of use-after-free through these access patterns:
7225
7226```c++
7227// For example, .data() here returns a borrow to 's' instead of 'v'.
7228const char* f() {
7229 std::string s = "hello";
7230 std::string_view v = s; // warning: address of stack memory returned
7231 return v.data(); // note: returned here
7232}
7233
7234const MyObj& g(MyObj obj) {
7235 View v = obj; // warning: address of stack memory returned
7236 return *v; // note: returned here
7237}
7238```
7239
7240This tracking also applies to range-based for loops, where the `begin()` and `end()`
7241iterators are used to access elements:
7242
7243```c++
7244std::string_view f(std::vector<std::string> vec) {
7245 for (const std::string& s : vec) { // warning: address of stack memory returned
7246 return s; // note: returned here
7247 }
7248}
7249```
7250
7251**Container Template Specialization**
7252
7253If a template class is annotated with `[[gsl::Owner]]`, and the first
7254instantiated template argument is a pointer type (raw pointer, or `[[gsl::Pointer]]`),
7255the analysis will consider the instantiated class as a container of the pointer.
7256When constructing such an object from a GSL owner object, the analysis will
7257assume that the container holds a pointer to the owner object. Consequently,
7258when the owner object is destroyed, the pointer will be considered dangling.
7259
7260```c++
7261int f() {
7262 std::vector<std::string_view> v = {std::string()}; // v holds a dangling pointer.
7263 std::optional<std::string_view> o = std::string(); // o holds a dangling pointer.
7264}
7265```)reST";
7266
7267static const char AttrDoc_PointerAuth[] = R"reST(The `__ptrauth` qualifier allows the programmer to directly control
7268how pointers are signed when they are stored in a particular variable.
7269This can be used to strengthen the default protections of pointer
7270authentication and make it more difficult for an attacker to escalate
7271an ability to alter memory into full control of a process.
7272
7273```c
7274#include <ptrauth.h>
7275
7276typedef void (*my_callback)(const void*);
7277my_callback __ptrauth(ptrauth_key_process_dependent_code, 1, 0xe27a) callback;
7278```
7279
7280The first argument to `__ptrauth` is the name of the signing key.
7281Valid key names for the target are defined in `<ptrauth.h>`.
7282
7283The second argument to `__ptrauth` is a flag (0 or 1) specifying whether
7284the object should use address discrimination.
7285
7286The third argument to `__ptrauth` is a 16-bit non-negative integer which
7287allows additional discrimination between objects.)reST";
7288
7289static const char AttrDoc_PointerFieldProtection[] = R"reST(No documentation.)reST";
7290
7291static const char AttrDoc_PragmaClangBSSSection[] = R"reST()reST";
7292
7293static const char AttrDoc_PragmaClangDataSection[] = R"reST()reST";
7294
7295static const char AttrDoc_PragmaClangRelroSection[] = R"reST()reST";
7296
7297static const char AttrDoc_PragmaClangRodataSection[] = R"reST()reST";
7298
7299static const char AttrDoc_PragmaClangTextSection[] = R"reST()reST";
7300
7301static const char AttrDoc_PreferredName[] = R"reST(The `preferred_name` attribute can be applied to a class template, and
7302specifies a preferred way of naming a specialization of the template. The
7303preferred name will be used whenever the corresponding template specialization
7304would otherwise be printed in a diagnostic or similar context.
7305
7306The preferred name must be a typedef or type alias declaration that refers to a
7307specialization of the class template (not including any type qualifiers). In
7308general this requires the template to be declared at least twice. For example:
7309
7310```c++
7311template<typename T> struct basic_string;
7312using string = basic_string<char>;
7313using wstring = basic_string<wchar_t>;
7314template<typename T> struct [[clang::preferred_name(string),
7315 clang::preferred_name(wstring)]] basic_string {
7316 // ...
7317};
7318```
7319
7320Note that the `preferred_name` attribute will be ignored when the compiler
7321writes a C++20 Module interface now. This is due to a compiler issue
7322(<https://github.com/llvm/llvm-project/issues/56490>) that blocks users to modularize
7323declarations with `preferred_name`. This is intended to be fixed in the future.)reST";
7324
7325static const char AttrDoc_PreferredType[] = R"reST(This attribute allows adjusting the type of a bit-field in debug information.
7326This can be helpful when a bit-field is intended to store an enumeration value,
7327but has to be specified as having the enumeration's underlying type in order to
7328facilitate compiler optimizations or bit-field packing behavior. Normally, the
7329underlying type is what is emitted in debug information, which can make it hard
7330for debuggers to know to map a bit-field's value back to a particular enumeration.
7331
7332```c++
7333enum Colors { Red, Green, Blue };
7334
7335struct S {
7336 [[clang::preferred_type(Colors)]] unsigned ColorVal : 2;
7337 [[clang::preferred_type(bool)]] unsigned UseAlternateColorSpace : 1;
7338} s = { Green, false };
7339```
7340
7341Without the attribute, a debugger is likely to display the value `1` for `ColorVal`
7342and `0` for `UseAlternateColorSpace`. With the attribute, the debugger may now
7343display `Green` and `false` instead.
7344
7345This can be used to map a bit-field to an arbitrary type that isn't integral
7346or an enumeration type. For example:
7347
7348```c++
7349struct A {
7350 short a1;
7351 short a2;
7352};
7353
7354struct B {
7355 [[clang::preferred_type(A)]] unsigned b1 : 32 = 0x000F'000C;
7356};
7357```
7358
7359will associate the type `A` with the `b1` bit-field and is intended to display
7360something like this in the debugger:
7361
7362```text
7363Process 2755547 stopped
7364* thread #1, name = 'test-preferred-', stop reason = step in
7365 frame #0: 0x0000555555555148 test-preferred-type`main at test.cxx:13:14
7366 10 int main()
7367 11 {
7368 12 B b;
7369-> 13 return b.b1;
7370 14 }
7371(lldb) v -T
7372(B) b = {
7373 (A:32) b1 = {
7374 (short) a1 = 12
7375 (short) a2 = 15
7376 }
7377}
7378```
7379
7380Note that debuggers may not be able to handle more complex mappings, and so
7381this usage is debugger-dependent.)reST";
7382
7383static const char AttrDoc_PreserveAll[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
7384a function. The `preserve_all` calling convention attempts to make the code
7385in the caller even less intrusive than the `preserve_most` calling convention.
7386This calling convention also behaves identical to the `C` calling convention
7387on how arguments and return values are passed, but it uses a different set of
7388caller/callee-saved registers. This removes the burden of saving and
7389recovering a large register set before and after the call in the caller. If
7390the arguments are passed in callee-saved registers, then they will be
7391preserved by the callee across the call. This doesn't apply for values
7392returned in callee-saved registers.
7393
7394- On X86-64 the callee preserves all general purpose registers, except for
7395 R11. R11 can be used as a scratch register. Furthermore it also preserves
7396 all floating-point registers (XMMs/YMMs).
7397- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
7398 X16-X18. Furthermore it also preserves lower 128 bits of V8-V31 SIMD - floating
7399 point registers.
7400
7401The idea behind this convention is to support calls to runtime functions
7402that don't need to call out to any other functions.
7403
7404This calling convention, like the `preserve_most` calling convention, will be
7405used by a future version of the Objective-C runtime and should be considered
7406experimental at this time.)reST";
7407
7408static const char AttrDoc_PreserveMost[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
7409a function. The `preserve_most` calling convention attempts to make the code
7410in the caller as unintrusive as possible. This convention behaves identically
7411to the `C` calling convention on how arguments and return values are passed,
7412but it uses a different set of caller/callee-saved registers. This alleviates
7413the burden of saving and recovering a large register set before and after the
7414call in the caller. If the arguments are passed in callee-saved registers,
7415then they will be preserved by the callee across the call. This doesn't
7416apply for values returned in callee-saved registers.
7417
7418- On X86-64 the callee preserves all general purpose registers, except for
7419 R11. R11 can be used as a scratch register. Floating-point registers
7420 (XMMs/YMMs) are not preserved and need to be saved by the caller.
7421- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
7422 X16-X18.
7423
7424The idea behind this convention is to support calls to runtime functions
7425that have a hot path and a cold path. The hot path is usually a small piece
7426of code that doesn't use many registers. The cold path might need to call out to
7427another function and therefore only needs to preserve the caller-saved
7428registers, which haven't already been saved by the caller. The
7429`preserve_most` calling convention is very similar to the `cold` calling
7430convention in terms of caller/callee-saved registers, but they are used for
7431different types of function calls. `coldcc` is for function calls that are
7432rarely executed, whereas `preserve_most` function calls are intended to be
7433on the hot path and definitely executed a lot. Furthermore `preserve_most`
7434doesn't prevent the inliner from inlining the function call.
7435
7436This calling convention will be used by a future version of the Objective-C
7437runtime and should therefore still be considered experimental at this time.
7438Although this convention was created to optimize certain runtime calls to
7439the Objective-C runtime, it is not limited to this runtime and might be used
7440by other runtimes in the future too. The current implementation only
7441supports X86-64 and AArch64, but the intention is to support more architectures
7442in the future.)reST";
7443
7444static const char AttrDoc_PreserveNone[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of a function.
7445The `preserve_none` calling convention tries to preserve as few general
7446registers as possible. So all general registers are caller saved registers. It
7447also uses more general registers to pass arguments. This attribute doesn't
7448impact floating-point registers. `preserve_none`'s ABI is still unstable, and
7449may be changed in the future.
7450
7451- On X86-64, only RSP and RBP are preserved by the callee.
7452 Registers R12, R13, R14, R15, RDI, RSI, RDX, RCX, R8, R9, R11, and RAX now can
7453 be used to pass function arguments. Floating-point registers (XMMs/YMMs) still
7454 follow the C calling convention.
7455- On AArch64, only LR and FP are preserved by the callee.
7456 Registers X20-X28, X0-X7, and X9-X14 are used to pass function arguments.
7457 X8, X16-X19, SIMD and floating-point registers follow the AAPCS calling
7458 convention. X15 is not available for argument passing on Windows, but is
7459 used to pass arguments on other platforms.)reST";
7460
7461static const char AttrDoc_PtGuardedBy[] = R"reST(No documentation.)reST";
7462
7463static const char AttrDoc_PtGuardedVar[] = R"reST(No documentation.)reST";
7464
7465static const char AttrDoc_Ptr32[] = R"reST(The `__ptr32` qualifier represents a native pointer on a 32-bit system. On a
746664-bit system, a pointer with `__ptr32` is extended to a 64-bit pointer. The
7467`__sptr` and `__uptr` qualifiers can be used to specify whether the pointer
7468is sign extended or zero extended. This qualifier is enabled under
7469`-fms-extensions`.)reST";
7470
7471static const char AttrDoc_Ptr64[] = R"reST(The `__ptr64` qualifier represents a native pointer on a 64-bit system. On a
747232-bit system, a `__ptr64` pointer is truncated to a 32-bit pointer. This
7473qualifier is enabled under `-fms-extensions`.)reST";
7474
7475static const char AttrDoc_Pure[] = R"reST(No documentation.)reST";
7476
7477static const char AttrDoc_RISCVInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt))` attribute on RISCV
7478targets. This attribute may be attached to a function definition and instructs
7479the backend to generate appropriate function entry/exit code so that it can be
7480used directly as an interrupt service routine.
7481
7482Permissible values for this parameter are `machine`, `supervisor`,
7483`rnmi`, `qci-nest`, `qci-nonest`, `SiFive-CLIC-preemptible`, and
7484`SiFive-CLIC-stack-swap`. If there is no parameter, then it defaults to
7485`machine`.
7486
7487The `rnmi` value is used for resumable non-maskable interrupts. It requires the
7488standard Smrnmi extension.
7489
7490The `qci-nest` and `qci-nonest` values require Qualcomm's Xqciint extension
7491and are used for Machine-mode Interrupts and Machine-mode Non-maskable
7492interrupts. These use the following instructions from Xqciint to save and
7493restore interrupt state to the stack -- the `qci-nest` value will use
7494`qc.c.mienter.nest` and the `qci-nonest` value will use `qc.c.mienter` to
7495begin the interrupt handler. Both of these will use `qc.c.mileaveret` to
7496restore the state and return to the previous context.
7497
7498The `SiFive-CLIC-preemptible` and `SiFive-CLIC-stack-swap` values are used
7499for machine-mode interrupts. For `SiFive-CLIC-preemptible` interrupts, the
7500values of `mcause` and `mepc` are saved onto the stack, and interrupts are
7501re-enabled. For `SiFive-CLIC-stack-swap` interrupts, the stack pointer is
7502swapped with `mscratch` before its first use and after its last use.
7503
7504The SiFive CLIC values may be combined with each other and with the `machine`
7505attribute value. Any other combination of different values is not allowed.
7506
7507Repeated interrupt attribute on the same declaration will cause a warning
7508to be emitted. In case of repeated declarations, the last one prevails.
7509
7510Refer to:
7511<https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html>
7512<https://riscv.org/specifications/privileged-isa/>
7513The RISC-V Instruction Set Manual Volume II: Privileged Architecture
7514Version 1.10.
7515<https://github.com/quic/riscv-unified-db/releases/tag/Xqci-0.13.0>
7516<https://sifive.cdn.prismic.io/sifive/d1984d2b-c9b9-4c91-8de0-d68a5e64fa0f_sifive-interrupt-cookbook-v1p2.pdf>)reST";
7517
7518static const char AttrDoc_RISCVVLSCC[] = R"reST(The `riscv_vls_cc` attribute can be applied to a function. Functions
7519declared with this attribute will utilize the standard fixed-length vector
7520calling convention variant instead of the default calling convention defined by
7521the ABI. This variant aims to pass fixed-length vectors via vector registers,
7522if possible, rather than through general-purpose registers.)reST";
7523
7524static const char AttrDoc_RISCVVectorCC[] = R"reST(The `riscv_vector_cc` attribute can be applied to a function. It preserves 15
7525registers namely, v1-v7 and v24-v31 as callee-saved. Callers thus don't need
7526to save these registers before function calls, and callees only need to save
7527them if they use them.)reST";
7528
7529static const char AttrDoc_RandomizeLayout[] = R"reST(The attribute `randomize_layout`, when attached to a C structure, selects it
7530for structure layout field randomization; a compile-time hardening technique. A
7531"seed" value, is specified via the `-frandomize-layout-seed=` command line flag.
7532For example:
7533
7534```bash
7535SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
7536make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
7537```
7538
7539You can also supply the seed in a file with `-frandomize-layout-seed-file=`.
7540For example:
7541
7542```bash
7543od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
7544make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
7545```
7546
7547The randomization is deterministic based for a given seed, so the entire
7548program should be compiled with the same seed, but keep the seed safe
7549otherwise.
7550
7551The attribute `no_randomize_layout`, when attached to a C structure,
7552instructs the compiler that this structure should not have its field layout
7553randomized.)reST";
7554
7555static const char AttrDoc_ReadOnlyPlacement[] = R"reST(This attribute is attached to a structure, class or union declaration.
7556
7557: When attached to a record declaration/definition, it checks if all instances
7558 of this type can be placed in the read-only data segment of the program. If it
7559 finds an instance that can not be placed in a read-only segment, the compiler
7560 emits a warning at the source location where the type was used.
7561
7562 Examples:
7563 \* `struct __attribute__((enforce_read_only_placement)) Foo;`
7564 \* `struct __attribute__((enforce_read_only_placement)) Bar { ... };`
7565
7566 Both `Foo` and `Bar` types have the `enforce_read_only_placement` attribute.
7567
7568 The goal of introducing this attribute is to assist developers with writing secure
7569 code. A `const`-qualified global is generally placed in the read-only section
7570 of the memory that has additional run time protection from malicious writes. By
7571 attaching this attribute to a declaration, the developer can express the intent
7572 to place all instances of the annotated type in the read-only program memory.
7573
7574 Note 1: The attribute doesn't guarantee that the object will be placed in the
7575 read-only data segment as it does not instruct the compiler to ensure such
7576 a placement. It emits a warning if something in the code can be proven to prevent
7577 an instance from being placed in the read-only data segment.
7578
7579 Note 2: Currently, clang only checks if all global declarations of a given type 'T'
7580 are `const`-qualified. The following conditions would also prevent the data to be
7581 put into read only segment, but the corresponding warnings are not yet implemented.
7582
7583 1. An instance of type `T` is allocated on the heap/stack.
7584 2. Type `T` defines/inherits a mutable field.
7585 3. Type `T` defines/inherits non-constexpr constructor(s) for initialization.
7586 4. A field of type `T` is defined by type `Q`, which does not bear the
7587 `enforce_read_only_placement` attribute.
7588 5. A type `Q` inherits from type `T` and it does not have the
7589 `enforce_read_only_placement` attribute.)reST";
7590
7591static const char AttrDoc_ReentrantCapability[] = R"reST(No documentation.)reST";
7592
7593static const char AttrDoc_RegCall[] = R"reST(On x86 targets, this attribute changes the calling convention to
7594[\_\_regcall][__regcall] convention. This convention aims to pass as many arguments
7595as possible in registers. It also tries to utilize registers for the
7596return value whenever it is possible.
7597
7598[__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";
7599
7600static const char AttrDoc_Reinitializes[] = R"reST(The `reinitializes` attribute can be applied to a non-static, non-const C++
7601member function to indicate that this member function reinitializes the entire
7602object to a known state, independent of the previous state of the object.
7603
7604This attribute can be interpreted by static analyzers that warn about uses of an
7605object that has been left in an indeterminate state by a move operation. If a
7606member function marked with the `reinitializes` attribute is called on a
7607moved-from object, the analyzer can conclude that the object is no longer in an
7608indeterminate state.
7609
7610A typical example where this attribute would be used is on functions that clear
7611a container class:
7612
7613```c++
7614template <class T>
7615class Container {
7616public:
7617 ...
7618 [[clang::reinitializes]] void Clear();
7619 ...
7620};
7621```)reST";
7622
7623static const char AttrDoc_ReleaseCapability[] = R"reST(Marks a function as releasing a capability.)reST";
7624
7625static const char AttrDoc_ReleaseHandle[] = R"reST(If a function parameter is annotated with `release_handle(tag)` it is assumed to
7626close the handle. It is also assumed to require an open handle to work with. The
7627attribute requires a string literal argument to identify the handle being released.
7628
7629```c++
7630zx_status_t zx_handle_close(zx_handle_t handle [[clang::release_handle("tag")]]);
7631```)reST";
7632
7633static const char AttrDoc_ReqdWorkGroupSize[] = R"reST(No documentation.)reST";
7634
7635static const char AttrDoc_RequiresCapability[] = R"reST(No documentation.)reST";
7636
7637static const char AttrDoc_Restrict[] = R"reST(The `malloc` attribute has two forms with different functionality. The first
7638is when it is used without arguments, where it marks that a function acts like
7639a system memory allocation function, returning a pointer to allocated storage
7640that does not alias storage from any other object accessible to the caller.
7641
7642The second form is when `malloc` takes one or two arguments. The first
7643argument names a function that should be associated with this function as its
7644deallocation function. When this form is used, it enables the compiler to
7645diagnose when the incorrect deallocation function is used with this variable.
7646However the associated warning, spelled `-Wmismatched-dealloc` in GCC, is not
7647yet implemented in clang.)reST";
7648
7649static const char AttrDoc_Retain[] = R"reST(This attribute, when attached to a function or variable definition, prevents
7650section garbage collection in the linker. It does not prevent other discard
7651mechanisms, such as archive member selection, and COMDAT group resolution.
7652
7653If the compiler does not emit the definition, e.g. because it was not used in
7654the translation unit or the compiler was able to eliminate all of the uses,
7655this attribute has no effect. This attribute is typically combined with the
7656`used` attribute to force the definition to be emitted and preserved into the
7657final linked image.
7658
7659This attribute is only necessary on ELF targets; other targets prevent section
7660garbage collection by the linker when using the `used` attribute alone.
7661Using the attributes together should result in consistent behavior across
7662targets.
7663
7664This attribute requires the linker to support the `SHF_GNU_RETAIN` extension.
7665This support is available in GNU `ld` and `gold` as of binutils 2.36, as
7666well as in `ld.lld` 13.)reST";
7667
7668static const char AttrDoc_ReturnTypestate[] = R"reST(The `return_typestate` attribute can be applied to functions or parameters.
7669When applied to a function the attribute specifies the state of the returned
7670value. The function's body is checked to ensure that it always returns a value
7671in the specified state. On the caller side, values returned by the annotated
7672function are initialized to the given state.
7673
7674When applied to a function parameter it modifies the state of an argument after
7675a call to the function returns. The function's body is checked to ensure that
7676the parameter is in the expected state before returning.)reST";
7677
7678static const char AttrDoc_ReturnsNonNull[] = R"reST(The `returns_nonnull` attribute indicates that a particular function (or
7679Objective-C method) always returns a non-null pointer. For example, a
7680particular system `malloc` might be defined to terminate a process when
7681memory is not available rather than returning a null pointer:
7682
7683```c
7684extern void * malloc (size_t size) __attribute__((returns_nonnull));
7685```
7686
7687The `returns_nonnull` attribute implies that returning a null pointer is
7688undefined behavior, which the optimizer may take advantage of. The `_Nonnull`
7689type qualifier indicates that a pointer cannot be null in a more general manner
7690(because it is part of the type system) and does not imply undefined behavior,
7691making it more widely applicable)reST";
7692
7693static const char AttrDoc_ReturnsTwice[] = R"reST(No documentation.)reST";
7694
7695static const char AttrDoc_RootSignature[] = R"reST(The `RootSignature` attribute applies to HLSL entry functions to define what
7696types of resources are bound to the graphics pipeline.
7697
7698For details about the use and specification of Root Signatures please see here:
7699<https://learn.microsoft.com/en-us/windows/win32/direct3d12/root-signatures>)reST";
7700
7701static const char AttrDoc_SPtr[] = R"reST(The `__sptr` qualifier specifies that a 32-bit pointer should be sign
7702extended when converted to a 64-bit pointer.)reST";
7703
7704static const char AttrDoc_SYCLExternal[] = R"reST(The `sycl_external` attribute indicates that a function defined in another
7705translation unit may be called by a device function defined in the current
7706translation unit or, if defined in the current translation unit, the function
7707may be called by device functions defined in other translation units.
7708The attribute is intended for use in the implementation of the `SYCL_EXTERNAL`
7709macro as specified in section 5.10.1, "SYCL functions and member functions
7710linkage", of the SYCL 2020 specification.
7711
7712The attribute only appertains to functions and only those that meet the
7713following requirements:
7714
7715- Has external linkage
7716- Is not explicitly defined as deleted (the function may be an explicitly
7717 defaulted function that is defined as deleted)
7718
7719The attribute shall be present on the first declaration of a function and
7720may optionally be present on subsequent declarations.
7721
7722When compiling for a SYCL device target that does not support the generic
7723address space, the function shall not specify a raw pointer or reference type
7724as the return type or as a parameter type.
7725See section 5.10, "SYCL offline linking", of the SYCL 2020 specification.
7726The following examples demonstrate the use of this attribute:
7727
7728```c++
7729[[clang::sycl_external]] void Foo(); // Ok.
7730
7731[[clang::sycl_external]] void Bar() { /* ... */ } // Ok.
7732
7733[[clang::sycl_external]] extern void Baz(); // Ok.
7734
7735[[clang::sycl_external]] static void Quux() { /* ... */ } // error: Quux() has internal linkage.
7736```)reST";
7737
7738static const char AttrDoc_SYCLKernel[] = R"reST(The `sycl_kernel` attribute specifies that a function template will be used
7739to outline device code and to generate an OpenCL kernel.
7740Here is a code example of the SYCL program, which demonstrates the compiler's
7741outlining job:
7742
7743```c++
7744int foo(int x) { return ++x; }
7745
7746using namespace cl::sycl;
7747queue Q;
7748buffer<int, 1> a(range<1>{1024});
7749Q.submit([&](handler& cgh) {
7750 auto A = a.get_access<access::mode::write>(cgh);
7751 cgh.parallel_for<init_a>(range<1>{1024}, [=](id<1> index) {
7752 A[index] = index[0] + foo(42);
7753 });
7754}
7755```
7756
7757A C++ function object passed to the `parallel_for` is called a "SYCL kernel".
7758A SYCL kernel defines the entry point to the "device part" of the code. The
7759compiler will emit all symbols accessible from a "kernel". In this code
7760example, the compiler will emit "foo" function. More details about the
7761compilation of functions for the device part can be found in the SYCL 1.2.1
7762specification Section 6.4.
7763To show to the compiler entry point to the "device part" of the code, the SYCL
7764runtime can use the `sycl_kernel` attribute in the following way:
7765
7766```c++
7767namespace cl {
7768namespace sycl {
7769class handler {
7770 template <typename KernelName, typename KernelType/*, ...*/>
7771 __attribute__((sycl_kernel)) void sycl_kernel_function(KernelType KernelFuncObj) {
7772 // ...
7773 KernelFuncObj();
7774 }
7775
7776 template <typename KernelName, typename KernelType, int Dims>
7777 void parallel_for(range<Dims> NumWorkItems, KernelType KernelFunc) {
7778#ifdef __SYCL_DEVICE_ONLY__
7779 sycl_kernel_function<KernelName, KernelType, Dims>(KernelFunc);
7780#else
7781 // Host implementation
7782#endif
7783 }
7784};
7785} // namespace sycl
7786} // namespace cl
7787```
7788
7789The compiler will also generate an OpenCL kernel using the function marked with
7790the `sycl_kernel` attribute.
7791Here is the list of SYCL device compiler expectations with regard to the
7792function marked with the `sycl_kernel` attribute:
7793
7794- The function must be a template with at least two type template parameters.
7795 The compiler generates an OpenCL kernel and uses the first template parameter
7796 as a unique name for the generated OpenCL kernel. The host application uses
7797 this unique name to invoke the OpenCL kernel generated for the SYCL kernel
7798 specialized by this name and second template parameter `KernelType` (which
7799 might be an unnamed function object type).
7800- The function must have at least one parameter. The first parameter is
7801 required to be a function object type (named or unnamed i.e. lambda). The
7802 compiler uses function object type fields to generate OpenCL kernel
7803 parameters.
7804- The function must return void. The compiler reuses the body of marked functions to
7805 generate the OpenCL kernel body, and the OpenCL kernel must return `void`.
7806
7807The SYCL kernel in the previous code sample meets these expectations.)reST";
7808
7809static const char AttrDoc_SYCLKernelEntryPoint[] = R"reST(The `sycl_kernel_entry_point` attribute facilitates the launch of a SYCL
7810kernel and the generation of an offload kernel entry point, sometimes called
7811a SYCL kernel caller function, suitable for invoking a SYCL kernel on an
7812offload device. The attribute is intended for use in the implementation of
7813SYCL kernel invocation functions like the `single_task` and `parallel_for`
7814member functions of the `sycl::handler` class specified in section 4.9.4,
7815"Command group `handler` class", of the SYCL 2020 specification.
7816
7817The attribute requires a single type argument that meets the requirements for
7818a SYCL kernel name as described in section 5.2, "Naming of kernels", of the
7819SYCL 2020 specification. A unique kernel name type is required for each
7820function declared with the attribute. The attribute may not first appear on a
7821declaration that follows a definition of the function.
7822
7823The attribute only appertains to functions and only those that meet the
7824following requirements.
7825
7826- Has a non-deduced `void` return type.
7827- Is not a constructor or destructor.
7828- Is not a non-static member function with an explicit object parameter.
7829- Is not a C variadic function.
7830- Is not a coroutine.
7831- Is not defined as deleted or as defaulted.
7832- Is not defined with a function try block.
7833- Is not declared with the `constexpr` or `consteval` specifiers.
7834- Is not declared with the `[[noreturn]]` attribute.
7835
7836Use in the implementation of a SYCL kernel invocation function might look as
7837follows.
7838
7839```c++
7840namespace sycl {
7841class handler {
7842 template<typename KernelName, typename... Ts>
7843 void sycl_kernel_launch(const char* kernelSymbol, Ts&&... kernelArgs) {
7844 // This code will run on the host and is responsible for calling functions
7845 // appropriate for the desired offload backend (OpenCL, CUDA, HIP,
7846 // Level Zero, etc...) to copy the kernel arguments denoted by kernelArgs
7847 // to a device and to schedule an invocation of the offload kernel entry
7848 // point denoted by kernelSymbol with the copied arguments.
7849 }
7850
7851 template<typename KernelName, typename KernelType>
7852 [[ clang::sycl_kernel_entry_point(KernelName) ]]
7853 void kernel_entry_point(KernelType kernelFunc) {
7854 // This code will run on the device. The call to kernelFunc() invokes
7855 // the SYCL kernel.
7856 kernelFunc();
7857 }
7858
7859public:
7860 template<typename KernelName, typename KernelType>
7861 void single_task(const KernelType& kernelFunc) {
7862 // This code will run on the host. kernel_entry_point() is called to
7863 // trigger generation of an offload kernel entry point and to schedule
7864 // an invocation of it on a device with kernelFunc (a SYCL kernel object)
7865 // passed as a kernel argument. This call will result in an implicit call
7866 // to sycl_kernel_launch() with the symbol name for the generated offload
7867 // kernel entry point passed as the first function argument followed by
7868 // kernelFunc.
7869 kernel_entry_point<KernelName>(kernelFunc);
7870 }
7871};
7872} // namespace sycl
7873```
7874
7875A SYCL kernel object is a callable object of class type that is constructed on
7876a host, often via a lambda expression, and then passed to a SYCL kernel
7877invocation function to be executed on an offload device. The `kernelFunc`
7878parameters in the example code above correspond to SYCL kernel objects.
7879
7880A SYCL kernel object type is required to satisfy the device copyability
7881requirements specified in section 3.13.1, "Device copyable", of the SYCL 2020
7882specification. Additionally, any data members of the kernel object type are
7883required to satisfy section 4.12.4, "Rules for parameter passing to kernels".
7884For most types, these rules require that the type is trivially copyable.
7885However, the SYCL specification mandates that certain special SYCL types, such
7886as `sycl::accessor` and `sycl::stream`, be device copyable even if they are
7887not trivially copyable. These types require special handling because they cannot
7888necessarily be copied to device memory as if by `memcpy()`.
7889
7890The SYCL kernel object and its data members constitute the parameters of an
7891offload kernel. An offload kernel consists of an offload entry point function
7892and the set of all functions and variables that are directly or indirectly used
7893by the entry point function.
7894
7895A SYCL kernel invocation function is responsible for performing the following
7896tasks (likely with the help of an offload backend like OpenCL):
7897
78981. Identifying the offload kernel entry point to be used for the SYCL kernel.
78992. Validating that the SYCL kernel object type and its data members meet the
7900 SYCL device copyability and kernel parameter requirements noted above.
79013. Copying the SYCL kernel object and any other kernel arguments to device
7902 memory including any special handling required for SYCL special types.
79034. Initiating execution of the offload kernel entry point.
7904
7905The offload kernel entry point for a SYCL kernel performs the following tasks:
7906
79071. Calling the `operator()` member function of the SYCL kernel object.
7908
7909The `sycl_kernel_entry_point` attribute facilitates or automates these tasks
7910by providing generation of an offload kernel entry point with a unique symbol
7911name, type checking of kernel argument requirements, and initiation of kernel
7912execution via synthesized calls to a `sycl_kernel_launch` template.
7913
7914A function declared with the `sycl_kernel_entry_point` attribute specifies
7915the parameters and body of an offload entry point function. Consider the
7916following call to the `single_task()` SYCL kernel invocation function assuming
7917an implementation similar to the one shown above.
7918
7919```c++
7920struct S { int i; };
7921void f(sycl::handler &handler, sycl::stream &sout, S s) {
7922 handler.single_task<struct KN>([=] {
7923 sout << "The value of s.i is " << s.i << "\n";
7924 });
7925}
7926```
7927
7928The SYCL kernel object is the result of the lambda expression. The call to
7929`kernel_entry_point()` via the call to `single_task()` triggers the
7930generation of an offload kernel entry point function that looks approximately
7931as follows.
7932
7933```c++
7934void sycl-kernel-caller-for-KN(kernel-type kernelFunc) {
7935 kernelFunc();
7936}
7937```
7938
7939There are a few items worthy of note:
7940
79411. `sycl-kernel-caller-for-KN` is an exposition only name; the actual name
7942 generated for an entry point is an implementation detail and subject to
7943 change. However, the name will incorporate the SYCL kernel name, `KN`,
7944 that was passed as the `KernelName` template parameter to
7945 `single_task()` and eventually provided as the argument to the
7946 `sycl_kernel_entry_point` attribute in order to ensure that a unique
7947 name is generated for each entry point. There is a one-to-one correspondence
7948 between SYCL kernel names and offload kernel entry points.
79492. The SYCL kernel is a lambda closure type and therefore has no name;
7950 `kernel-type` is substituted above and corresponds to the `KernelType`
7951 template parameter deduced in the call to `single_task()`.
79523. The parameter and the call to `kernelFunc()` in the function body
7953 correspond to the definition of `kernel_entry_point()` as called by
7954 `single_task()`.
79554. The parameter is type checked for conformance with the SYCL device
7956 copyability and kernel parameter requirements.
7957
7958Within `single_task()`, the call to `kernel_entry_point()` is effectively
7959replaced with a synthesized call to a ''sycl_kernel_launch\`\` template that
7960looks approximately as follows.
7961
7962```c++
7963sycl_kernel_launch<KN>("sycl-kernel-caller-for-KN", kernelFunc);
7964```
7965
7966There are a few items worthy of note:
7967
79681. Lookup for the `sycl_kernel_launch` template is performed as if from the
7969 body of the (possibly instantiated) definition of `kernel_entry_point()`.
7970 If name lookup or overload resolution fails, the program is ill-formed.
7971 If the selected overload is a non-static member function, then `this` is
7972 passed as the implicit object parameter.
79732. Function arguments passed to `sycl_kernel_launch()` are passed
7974 as if by `std::move(x)`.
79753. The `sycl_kernel_launch` template is expected to be provided by the SYCL
7976 library implementation. It is responsible for copying the kernel arguments
7977 to device memory and for scheduling execution of the generated offload
7978 kernel entry point identified by the symbol name passed as the first
7979 function argument. `sycl-kernel-caller-for-KN` is substituted above for
7980 the actual symbol name that would be generated for the offload kernel entry
7981 point.
7982
7983It is not necessary for a function declared with the `sycl_kernel_entry_point`
7984attribute to be called for the offload kernel entry point to be emitted. For
7985inline functions and function templates, any ODR-use will suffice. For other
7986functions, an ODR-use is not required; the offload kernel entry point will be
7987emitted if the function is defined. In any case, a call to the function is
7988required for the synthesized call to `sycl_kernel_launch()` to occur.
7989
7990A function declared with the `sycl_kernel_entry_point` attribute may include
7991an exception specification. If a non-throwing exception specification is
7992present, an exception propagating from the implicit call to the
7993`sycl_kernel_launch` template will result in a call to `std::terminate()`.
7994Otherwise, such an exception will propagate normally.
7995
7996Functions declared with the `sycl_kernel_entry_point` attribute are not
7997limited to the simple example shown above. They may have additional template
7998parameters, declare additional function parameters, and have complex control
7999flow in the function body. The function must abide by the language feature
8000restrictions described in section 5.4, "Language restrictions for device
8001functions" in the SYCL 2020 specification. If the function is a non-static
8002member function, `this` shall not be used in a potentially evaluated
8003expression.)reST";
8004
8005static const char AttrDoc_SYCLSpecialClass[] = R"reST(SYCL defines some special classes (accessor, sampler, and stream) which require
8006specific handling during the generation of the SPIR entry point.
8007The `__attribute__((sycl_special_class))` attribute is used in SYCL
8008headers to indicate that a class or a struct needs a specific handling when
8009it is passed from host to device.
8010Special classes will have a mandatory `__init` method and an optional
8011`__finalize` method (the `__finalize` method is used only with the
8012`stream` type). Kernel parameters types are extract from the `__init` method
8013parameters. The kernel function arguments list is derived from the
8014arguments of the `__init` method. The arguments of the `__init` method are
8015copied into the kernel function argument list and the `__init` and
8016`__finalize` methods are called at the beginning and the end of the kernel,
8017respectively.
8018The `__init` and `__finalize` methods must be defined inside the
8019special class.
8020Please note that this is an attribute that is used as an internal
8021implementation detail and not intended to be used by external users.
8022
8023The syntax of the attribute is as follows:
8024
8025```text
8026class __attribute__((sycl_special_class)) accessor {};
8027class [[clang::sycl_special_class]] accessor {};
8028```
8029
8030This is a code example that illustrates the use of the attribute:
8031
8032```c++
8033class __attribute__((sycl_special_class)) SpecialType {
8034 int F1;
8035 int F2;
8036 void __init(int f1) {
8037 F1 = f1;
8038 F2 = f1;
8039 }
8040 void __finalize() {}
8041public:
8042 SpecialType() = default;
8043 int getF2() const { return F2; }
8044};
8045
8046int main () {
8047 SpecialType T;
8048 cgh.single_task([=] {
8049 T.getF2();
8050 });
8051}
8052```
8053
8054This would trigger the following kernel entry point in the AST:
8055
8056```c++
8057void __sycl_kernel(int f1) {
8058 SpecialType T;
8059 T.__init(f1);
8060 ...
8061 T.__finalize()
8062}
8063```)reST";
8064
8065static const char AttrDoc_ScopedLockable[] = R"reST(No documentation.)reST";
8066
8067static const char AttrDoc_Section[] = R"reST(The `section` attribute allows you to specify a specific section a
8068global variable or function should be in after translation.)reST";
8069
8070static const char AttrDoc_SelectAny[] = R"reST(This attribute appertains to a global symbol, causing it to have a weak
8071definition (
8072[linkonce](https://llvm.org/docs/LangRef.html#linkage-types)
8073), allowing the linker to select any definition.
8074
8075For more information see
8076[gcc documentation](https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html)
8077or [msvc documentation](https://docs.microsoft.com/pl-pl/cpp/cpp/selectany).)reST";
8078
8079static const char AttrDoc_Sentinel[] = R"reST(The `sentinel` attribute can be applied to variadic functions and pointers to
8080variadic functions, to diagnose each function call that does not pass a
8081sentinel value (a null pointer constant) as the last argument to the function
8082call. The attribute accepts two optional arguments: the first argument is the
8083position of the expected sentinel value, starting from the last parameter. The
8084second argument describes whether the last fixed parameter is treated as a
8085valid sentinel value when set to '1'.
8086All arguments described above default to '0' when elided.
8087The attribute is also supported with blocks and in Objective-C.
8088
8089```c
8090void foo(const char*, ...) __attribute__((sentinel));
8091void bar(int, ...) __attribute__((sentinel(1)));
8092void baz(const char*, const char*, ...) __attribute__((sentinel(0, 1)));
8093
8094void example() {
8095 foo("Example", (void*)0);
8096 foo("Another", "example", NULL);
8097 foo("Missing", "sentinel"); // Not OK
8098
8099 bar(1, 2, NULL, 3); // OK: sentinel value at the 2nd to last position
8100 bar(1, 2, 3, nullptr, 4); // OK: `nullptr` is valid in C23
8101 bar(1, 2, 3, 4, NULL); // Not OK
8102
8103 baz("Test", "with", "multiple", "args", NULL);
8104 baz("One", NULL); // OK: last fixed parameter is a valid sentinel
8105
8106 void (*ptr) (int arg, ...) __attribute__ ((__sentinel__));
8107 ptr(1, 2, 3, NULL);
8108}
8109```
8110
8111```c++
8112struct Ty {
8113 int value;
8114
8115 template<typename T>
8116 auto&& foo(T&& val, ...) __attribute__((sentinel(1))) {
8117 return std::forward<T>(val);
8118 }
8119
8120 template<class Self>
8121 auto&& bar(this Self&& self, ...) __attribute__((sentinel(1))) {
8122 return std::forward<Self>(self).value;
8123 }
8124};
8125
8126void example2() {
8127 auto sty = Ty{};
8128 sty.foo(1, nullptr, 3);
8129 sty.bar(1, nullptr, 3);
8130
8131 auto lmbd = [](int a, ...) __attribute__((sentinel)) {};
8132 lmbd(1, 2, nullptr);
8133}
8134```)reST";
8135
8136static const char AttrDoc_SetTypestate[] = R"reST(Annotate methods that transition an object into a new state with
8137`__attribute__((set_typestate(new_state)))`. The new state must be
8138unconsumed, consumed, or unknown.)reST";
8139
8140static const char AttrDoc_SizedBy[] = R"reST(The `sized_by` attribute is applied to a pointer to indicate that the pointer
8141points to memory containing at least the number of *bytes* given by the
8142attribute's argument. It is closely related to `counted_by`; the difference is
8143that `counted_by` counts the number of *elements* of the pointee type, whereas
8144`sized_by` counts the number of *bytes*. This makes `sized_by` the natural
8145choice for `void *` and other byte buffers.
8146
8147This attribute is used by {doc}`-fbounds-safety <BoundsSafety>` to propagate
8148bounds information on API surfaces without any ABI changes. This attribute is
8149also used to improve the results of the array bound sanitizer and the
8150`__builtin_dynamic_object_size` builtin.
8151
8152The argument is an expression of integer type, following the same rules as the
8153argument of `counted_by`. Unlike `counted_by`, `sized_by` cannot be
8154applied to a C99 flexible array member; it applies to pointers only. For
8155example:
8156
8157```c
8158struct object {
8159 unsigned long size;
8160 void *data __attribute__((sized_by(size)));
8161};
8162```
8163
8164A pointer annotated with `sized_by` must have a size of zero when it is null.
8165This requirement is currently only enforced when compiling with
8166{doc}`-fbounds-safety <BoundsSafety>` (see {ref}`Current status of
8167-fbounds-safety support in upstream Clang <bounds-safety-current-upstream-status>`). Use
8168`sized_by_or_null` for a pointer that may be null while carrying a nonzero
8169size.
8170
8171#### Keeping pointer and size in sync
8172
8173The `sized_by` attribute establishes a relationship between the annotated
8174pointer and its size: the pointer must point to at least `size` bytes.
8175Assigning to only one of them can break this relationship.
8176Without {doc}`-fbounds-safety <BoundsSafety>`, it is the programmer's
8177responsibility to ensure the pointer and size remain in sync. With
8178`-fbounds-safety` it is automatically enforced. For example:
8179
8180```c
8181struct buffer {
8182 uint8_t *buf __attribute__((sized_by(size)));
8183 size_t size;
8184};
8185
8186void grow(struct buffer *b, size_t new_size) {
8187 // b->buf isn't updated. The underlying memory pointed to by b->buf might be
8188 // smaller than new_size which would contradict the sized_by attribute.
8189 // Compile error with -fbounds-safety but allowed without -fbounds-safety.
8190 b->size = new_size;
8191}
8192```
8193
8194Updating both together - so that `buf` points to `size` bytes - keeps
8195the attribute true. For example:
8196
8197```c
8198void grow(struct buffer *b, size_t new_size) {
8199 // Allowed by -fbounds-safety
8200 uint8_t *new_buf = malloc(new_size);
8201 // -fbounds-safety enforces that the `new_buf` points to at least `new_size`
8202 // bytes at runtime. Without -fbounds-safety nothing enforces this.
8203 b->buf = new_buf;
8204 b->size = new_size;
8205}
8206```
8207
8208#### Incomplete and variable-length pointees
8209
8210`sized_by` is typically applied to `void *` or a pointer to a byte-sized
8211type, but it may be used with any pointee type. Two situations call for this,
8212both of which rule out counting fixed-size elements:
8213
8214First, the pointee type may be incomplete, such as an opaque type. Its element
8215size is then unavailable, so `counted_by` cannot be used, whereas `sized_by`
8216bounds the memory in bytes and imposes no completeness requirement.
8217
8218Second, the buffer may hold variable-length elements, so there is no fixed
8219element size to count, even though the total byte size is well defined. For
8220example, a buffer might pack together several structures that each end in a
8221flexible array member of differing length:
8222
8223```c
8224struct var_len {
8225 int fam_size;
8226 char data[] __attribute__((counted_by(fam_size)));
8227};
8228
8229struct buffer_view {
8230 int byte_size;
8231 struct var_len *buf __attribute__((sized_by(byte_size)));
8232};
8233```
8234
8235Here `counted_by` cannot be applied to `buf` because its pointee is a
8236variable-length structure, but `sized_by` bounds the whole region in bytes;
8237the region is traversed by advancing a byte offset rather than by indexing
8238elements.)reST";
8239
8240static const char AttrDoc_SizedByOrNull[] = R"reST(The `sized_by_or_null` attribute is applied to a pointer to indicate that, if
8241the pointer is non-null, it points to memory containing at least the number of
8242*bytes* given by the attribute's argument. If the pointer is null, the value of
8243the argument is ignored and the pointer points to zero bytes.
8244
8245The `sized_by_or_null` attribute is identical to `sized_by` except in how
8246it treats null pointers. Whereas `sized_by` requires a null pointer to have a
8247size of zero, `sized_by_or_null` allows the pointer to be null regardless of
8248the value of the size. This supports the common idiom where a pointer is either
8249null or points to memory containing at least the given number of bytes.
8250
8251Currently only {doc}`-fbounds-safety <BoundsSafety>` makes use of the
8252distinction between `sized_by_or_null` and `sized_by` (see
8253{ref}`Current status of -fbounds-safety support in upstream Clang
8254<bounds-safety-current-upstream-status>`).)reST";
8255
8256static const char AttrDoc_SpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
8257that [Speculative Load Hardening][slh]
8258should be enabled for the function body. This can also be applied to a method
8259in Objective C. This attribute will take precedence over the command line flag
8260in the case where {option}`-mno-speculative-load-hardening` is specified.
8261
8262[slh]: https://llvm.org/docs/SpeculativeLoadHardening.html
8263
8264Speculative Load Hardening is a best-effort mitigation against
8265information leak attacks that make use of control flow
8266miss-speculation - specifically miss-speculation of whether a branch
8267is taken or not. Typically vulnerabilities enabling such attacks are
8268classified as "Spectre variant #1". Notably, this does not attempt to
8269mitigate against miss-speculation of branch target, classified as
8270"Spectre variant #2" vulnerabilities.
8271
8272When inlining, the attribute is sticky. Inlining a function that
8273carries this attribute will cause the caller to gain the
8274attribute. This is intended to provide a maximally conservative model
8275where the code in a function annotated with this attribute will always
8276(even after inlining) end up hardened.)reST";
8277
8278static const char AttrDoc_StackProtectorIgnore[] = R"reST(The `stack_protector_ignore` attribute skips analysis of the given local
8279variable when determining if a function should use a stack protector.
8280
8281The `-fstack-protector` option uses a heuristic to only add stack protectors
8282to functions which contain variables or buffers over some size threshold. This
8283attribute overrides that heuristic for the attached variable, opting
8284them out. If this results in no variables or buffers remaining over the stack
8285protector threshold, then the function will no longer use a stack protector.)reST";
8286
8287static const char AttrDoc_StandaloneDebug[] = R"reST(The `standalone_debug` attribute causes debug info to be emitted for a record
8288type regardless of the debug info optimizations that are enabled with
8289-fno-standalone-debug. This attribute only has an effect when debug info
8290optimizations are enabled (e.g. with -fno-standalone-debug), and is C++-only.)reST";
8291
8292static const char AttrDoc_StdCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
8293function to clear parameters off of the stack on return. This convention does
8294not support variadic calls or unprototyped functions in C, and has no effect on
8295x86_64 targets. This calling convention is used widely by the Windows API and
8296COM applications. See the documentation for [\_\_stdcall][__stdcall] on MSDN.
8297
8298[__stdcall]: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx)reST";
8299
8300static const char AttrDoc_StrictFP[] = R"reST()reST";
8301
8302static const char AttrDoc_StrictGuardStackCheck[] = R"reST(Clang supports the Microsoft style `__declspec((strict_gs_check))` attribute
8303which upgrades the stack protector check from `-fstack-protector` to
8304`-fstack-protector-strong`.
8305
8306For example, it upgrades the stack protector for the function `foo` to
8307`-fstack-protector-strong` but function `bar` will still be built with the
8308stack protector with the `-fstack-protector` option.
8309
8310```c
8311__declspec((strict_gs_check))
8312int foo(int x); // stack protection will be upgraded for foo.
8313
8314int bar(int y); // bar can be built with the standard stack protector checks.
8315```)reST";
8316
8317static const char AttrDoc_Suppress[] = R"reST(The `suppress` attribute suppresses unwanted warnings coming from static
8318analysis tools such as the Clang Static Analyzer. The tool will not report
8319any issues in source code annotated with the attribute.
8320
8321The attribute cannot be used to suppress traditional Clang warnings, because
8322many such warnings are emitted before the attribute is fully parsed.
8323Consider using `#pragma clang diagnostic` to control such diagnostics,
8324as described in
8325{ref}`Controlling Diagnostics via Pragmas <pragma-gcc-diagnostic>`.
8326
8327The `suppress` attribute can be placed on an individual statement in order to
8328suppress warnings about undesirable behavior occurring at that statement:
8329
8330```c++
8331int foo() {
8332 int *x = nullptr;
8333 ...
8334 [[clang::suppress]]
8335 return *x; // null pointer dereference warning suppressed here
8336}
8337```
8338
8339Putting the attribute on a compound statement suppresses all warnings in scope:
8340
8341```c++
8342int foo() {
8343 [[clang::suppress]] {
8344 int *x = nullptr;
8345 ...
8346 return *x; // warnings suppressed in the entire scope
8347 }
8348}
8349```
8350
8351The attribute can also be placed on entire declarations of functions, classes,
8352variables, member variables, and so on, to suppress warnings related
8353to the declarations themselves. When used this way, the attribute additionally
8354suppresses all warnings in the lexical scope of the declaration:
8355
8356```c++
8357class [[clang::suppress]] C {
8358 int foo() {
8359 int *x = nullptr;
8360 ...
8361 return *x; // warnings suppressed in the entire class scope
8362 }
8363
8364 int bar();
8365};
8366
8367int C::bar() {
8368 int *x = nullptr;
8369 ...
8370 return *x; // warning NOT suppressed! - not lexically nested in 'class C{}'
8371}
8372```
8373
8374Some static analysis warnings are accompanied by one or more notes, and the
8375line of code against which the warning is emitted isn't necessarily the best
8376for suppression purposes. In such cases the tools are allowed to implement
8377additional ways to suppress specific warnings based on the attribute attached
8378to a note location.
8379
8380For example, the Clang Static Analyzer suppresses memory leak warnings when
8381the suppression attribute is placed at the allocation site (highlited by
8382a "note: memory is allocated"), which may be different from the line of code
8383at which the program "loses track" of the pointer (where the warning
8384is ultimately emitted):
8385
8386```c
8387int bar1(bool coin_flip) {
8388 __attribute__((suppress))
8389 int *result = (int *)malloc(sizeof(int));
8390 if (coin_flip)
8391 return 1; // warning about this leak path is suppressed
8392
8393 return *result; // warning about this leak path is also suppressed
8394}
8395
8396int bar2(bool coin_flip) {
8397 int *result = (int *)malloc(sizeof(int));
8398 if (coin_flip)
8399 return 1; // leak warning on this path NOT suppressed
8400
8401 __attribute__((suppress))
8402 return *result; // leak warning is suppressed only on this path
8403}
8404```
8405
8406When written as `[[gsl::suppress]]`, this attribute suppresses specific
8407clang-tidy diagnostics for rules of the [C++ Core Guidelines][c++ core guidelines] in a portable
8408way. The attribute can be attached to declarations, statements, and at
8409namespace scope.
8410
8411```c++
8412[[gsl::suppress("Rh-public")]]
8413void f_() {
8414 int *p;
8415 [[gsl::suppress("type")]] {
8416 p = reinterpret_cast<int*>(7);
8417 }
8418}
8419namespace N {
8420 [[clang::suppress("type", "bounds")]];
8421 ...
8422}
8423```
8424
8425[c++ core guidelines]: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement)reST";
8426
8427static const char AttrDoc_SwiftAsync[] = R"reST(The `swift_async` attribute specifies if and how a particular function or
8428Objective-C method is imported into a swift async method. For instance:
8429
8430```objc
8431@interface MyClass : NSObject
8432-(void)notActuallyAsync:(int)p1 withCompletionHandler:(void (^)())handler
8433 __attribute__((swift_async(none)));
8434
8435-(void)actuallyAsync:(int)p1 callThisAsync:(void (^)())fun
8436 __attribute__((swift_async(swift_private, 1)));
8437@end
8438```
8439
8440Here, `notActuallyAsync:withCompletionHandler` would have been imported as
8441`async` (because it's last parameter's selector piece is
8442`withCompletionHandler`) if not for the `swift_async(none)` attribute.
8443Conversely, `actuallyAsync:callThisAsync` wouldn't have been imported as
8444`async` if not for the `swift_async` attribute because it doesn't match the
8445naming convention.
8446
8447When using `swift_async` to enable importing, the first argument to the
8448attribute is either `swift_private` or `not_swift_private` to indicate
8449whether the function/method is private to the current framework, and the second
8450argument is the index of the completion handler parameter.)reST";
8451
8452static const char AttrDoc_SwiftAsyncCall[] = R"reST(The `swiftasynccall` attribute indicates that a function is
8453compatible with the low-level conventions of Swift async functions,
8454provided it declares the right formal arguments.
8455
8456In most respects, this is similar to the `swiftcall` attribute, except for
8457the following:
8458
8459- A parameter may be marked `swift_async_context`, `swift_context`
8460 or `swift_indirect_result` (with the same restrictions on parameter
8461 ordering as `swiftcall`) but the parameter attribute
8462 `swift_error_result` is not permitted.
8463- A `swiftasynccall` function must have return type `void`.
8464- Within a `swiftasynccall` function, a call to a `swiftasynccall`
8465 function that is the immediate operand of a `return` statement is
8466 guaranteed to be performed as a tail call. This syntax is allowed even
8467 in C as an extension (a call to a void-returning function cannot be a
8468 return operand in standard C). If something in the calling function would
8469 semantically be performed after a guaranteed tail call, such as the
8470 non-trivial destruction of a local variable or temporary,
8471 then the program is ill-formed.
8472
8473Query for this attribute with `__has_attribute(swiftasynccall)`. Query if
8474the target supports the calling convention with
8475`__has_extension(swiftasynccc)`.
8476
8477Since this attribute follows the Swift async calling convention, it is
8478considered ABI-unstable except on targets where the Swift project
8479has declared ABI stability. Users are responsible for ensuring that
8480calls and definitions of functions with this attribute are compiled
8481with compatible compilers. Note that different operating systems
8482on the same architecture may use different ABIs and therefore may
8483have different standards for ABI stability.)reST";
8484
8485static const char AttrDoc_SwiftAsyncContext[] = R"reST(The `swift_async_context` attribute marks a parameter of a `swiftasynccall`
8486function as having the special asynchronous context-parameter ABI treatment.
8487
8488If the function is not `swiftasynccall`, this attribute only generates
8489extended frame information.
8490
8491A context parameter must have pointer or reference type.)reST";
8492
8493static const char AttrDoc_SwiftAsyncError[] = R"reST(The `swift_async_error` attribute specifies how an error state will be
8494represented in a swift async method. It's a bit analogous to the `swift_error`
8495attribute for the generated async method. The `swift_async_error` attribute
8496can indicate a variety of different ways of representing an error.
8497
8498- `__attribute__((swift_async_error(zero_argument, N)))`, specifies that the
8499 async method is considered to have failed if the Nth argument to the
8500 completion handler is zero.
8501- `__attribute__((swift_async_error(nonzero_argument, N)))`, specifies that
8502 the async method is considered to have failed if the Nth argument to the
8503 completion handler is non-zero.
8504- `__attribute__((swift_async_error(nonnull_error)))`, specifies that the
8505 async method is considered to have failed if the `NSError *` argument to the
8506 completion handler is non-null.
8507- `__attribute__((swift_async_error(none)))`, specifies that the async method
8508 cannot fail.
8509
8510For instance:
8511
8512```objc
8513@interface MyClass : NSObject
8514-(void)asyncMethod:(void (^)(char, int, float))handler
8515 __attribute__((swift_async(swift_private, 1)))
8516 __attribute__((swift_async_error(zero_argument, 2)));
8517@end
8518```
8519
8520Here, the `swift_async` attribute specifies that `handler` is the completion
8521handler for this method, and the `swift_async_error` attribute specifies that
8522the `int` parameter is the one that represents the error.)reST";
8523
8524static const char AttrDoc_SwiftAsyncName[] = R"reST(The `swift_async_name` attribute provides the name of the `async` overload for
8525the given declaration in Swift. If this attribute is absent, the name is
8526transformed according to the algorithm built into the Swift compiler.
8527
8528The argument is a string literal that contains the Swift name of the function or
8529method. The name may be a compound Swift name. The function or method with such
8530an attribute must have more than zero parameters, as its last parameter is
8531assumed to be a callback that's eliminated in the Swift `async` name.
8532
8533```objc
8534@interface URL
8535+ (void) loadContentsFrom:(URL *)url callback:(void (^)(NSData *))data __attribute__((__swift_async_name__("URL.loadContentsFrom(_:)")))
8536@end
8537```)reST";
8538
8539static const char AttrDoc_SwiftAttr[] = R"reST(The `swift_attr` provides a Swift-specific annotation for the declaration
8540or type to which the attribute appertains to. It can be used on any declaration
8541or type in Clang. This kind of annotation is ignored by Clang as it doesn't have any
8542semantic meaning in languages supported by Clang. The Swift compiler can
8543interpret these annotations according to its own rules when importing C or
8544Objective-C declarations.)reST";
8545
8546static const char AttrDoc_SwiftBridge[] = R"reST(The `swift_bridge` attribute indicates that the declaration to which the
8547attribute appertains is bridged to the named Swift type.
8548
8549```objc
8550__attribute__((__objc_root__))
8551@interface Base
8552- (instancetype)init;
8553@end
8554
8555__attribute__((__swift_bridge__("BridgedI")))
8556@interface I : Base
8557@end
8558```
8559
8560In this example, the Objective-C interface `I` will be made available to Swift
8561with the name `BridgedI`. It would be possible for the compiler to refer to
8562`I` still in order to bridge the type back to Objective-C.)reST";
8563
8564static const char AttrDoc_SwiftBridgedTypedef[] = R"reST(The `swift_bridged_typedef` attribute indicates that when the typedef to which
8565the attribute appertains is imported into Swift, it should refer to the bridged
8566Swift type (e.g. Swift's `String`) rather than the Objective-C type as written
8567(e.g. `NSString`).
8568
8569```objc
8570@interface NSString;
8571typedef NSString *AliasedString __attribute__((__swift_bridged_typedef__));
8572
8573extern void acceptsAliasedString(AliasedString _Nonnull parameter);
8574```
8575
8576In this case, the function `acceptsAliasedString` will be imported into Swift
8577as a function which accepts a `String` type parameter.)reST";
8578
8579static const char AttrDoc_SwiftCall[] = R"reST(The `swiftcall` attribute indicates that a function should be called
8580using the Swift calling convention for a function or function pointer.
8581
8582The lowering for the Swift calling convention, as described by the Swift
8583ABI documentation, occurs in multiple phases. The first, "high-level"
8584phase breaks down the formal parameters and results into innately direct
8585and indirect components, adds implicit parameters for the generic
8586signature, and assigns the context and error ABI treatments to parameters
8587where applicable. The second phase breaks down the direct parameters
8588and results from the first phase and assigns them to registers or the
8589stack. The `swiftcall` convention only handles this second phase of
8590lowering; the C function type must accurately reflect the results
8591of the first phase, as follows:
8592
8593- Results classified as indirect by high-level lowering should be
8594 represented as parameters with the `swift_indirect_result` attribute.
8595
8596- Results classified as direct by high-level lowering should be represented
8597 as follows:
8598
8599 - First, remove any empty direct results.
8600 - If there are no direct results, the C result type should be `void`.
8601 - If there is one direct result, the C result type should be a type with
8602 the exact layout of that result type.
8603 - If there are a multiple direct results, the C result type should be
8604 a struct type with the exact layout of a tuple of those results.
8605
8606- Parameters classified as indirect by high-level lowering should be
8607 represented as parameters of pointer type.
8608
8609- Parameters classified as direct by high-level lowering should be
8610 omitted if they are empty types; otherwise, they should be represented
8611 as a parameter type with a layout exactly matching the layout of the
8612 Swift parameter type.
8613
8614- The context parameter, if present, should be represented as a trailing
8615 parameter with the `swift_context` attribute.
8616
8617- The error result parameter, if present, should be represented as a
8618 trailing parameter (always following a context parameter) with the
8619 `swift_error_result` attribute.
8620
8621`swiftcall` does not support variadic arguments or unprototyped functions.
8622
8623The parameter ABI treatment attributes are aspects of the function type.
8624A function type which applies an ABI treatment attribute to a
8625parameter is a different type from an otherwise-identical function type
8626that does not. A single parameter may not have multiple ABI treatment
8627attributes.
8628
8629Support for this feature is target-dependent, although it should be
8630supported on every target that Swift supports. Query for this attribute
8631with `__has_attribute(swiftcall)`. Query if the target supports the
8632calling convention with `__has_extension(swiftcc)`. This implies
8633support for the `swift_context`, `swift_error_result`, and
8634`swift_indirect_result` attributes.
8635
8636Since this attribute follows the Swift calling convention, it is
8637considered ABI-unstable except on targets where the Swift project
8638has declared ABI stability. Users are responsible for ensuring that
8639calls and definitions of functions with this attribute are compiled
8640with compatible compilers. Note that different operating systems
8641on the same architecture may use different ABIs and therefore may
8642have different standards for ABI stability.)reST";
8643
8644static const char AttrDoc_SwiftContext[] = R"reST(The `swift_context` attribute marks a parameter of a `swiftcall`
8645or `swiftasynccall` function as having the special context-parameter
8646ABI treatment.
8647
8648This treatment generally passes the context value in a special register
8649which is normally callee-preserved.
8650
8651A `swift_context` parameter must either be the last parameter or must be
8652followed by a `swift_error_result` parameter (which itself must always be
8653the last parameter).
8654
8655A context parameter must have pointer or reference type.)reST";
8656
8657static const char AttrDoc_SwiftError[] = R"reST(The `swift_error` attribute controls whether a particular function (or
8658Objective-C method) is imported into Swift as a throwing function, and if so,
8659which dynamic convention it uses.
8660
8661All of these conventions except `none` require the function to have an error
8662parameter. Currently, the error parameter is always the last parameter of type
8663`NSError**` or `CFErrorRef*`. Swift will remove the error parameter from
8664the imported API. When calling the API, Swift will always pass a valid address
8665initialized to a null pointer.
8666
8667- `swift_error(none)` means that the function should not be imported as
8668 throwing. The error parameter and result type will be imported normally.
8669- `swift_error(null_result)` means that calls to the function should be
8670 considered to have thrown if they return a null value. The return type must be
8671 a pointer type, and it will be imported into Swift with a non-optional type.
8672 This is the default error convention for Objective-C methods that return
8673 pointers.
8674- `swift_error(zero_result)` means that calls to the function should be
8675 considered to have thrown if they return a zero result. The return type must be
8676 an integral type. If the return type would have been imported as `Bool`, it
8677 is instead imported as `Void`. This is the default error convention for
8678 Objective-C methods that return a type that would be imported as `Bool`.
8679- `swift_error(nonzero_result)` means that calls to the function should be
8680 considered to have thrown if they return a non-zero result. The return type must
8681 be an integral type. If the return type would have been imported as `Bool`,
8682 it is instead imported as `Void`.
8683- `swift_error(nonnull_error)` means that calls to the function should be
8684 considered to have thrown if they leave a non-null error in the error parameter.
8685 The return type is left unmodified.)reST";
8686
8687static const char AttrDoc_SwiftErrorResult[] = R"reST(The `swift_error_result` attribute marks a parameter of a `swiftcall`
8688function as having the special error-result ABI treatment.
8689
8690This treatment generally passes the underlying error value in and out of
8691the function through a special register which is normally callee-preserved.
8692This is modeled in C by pretending that the register is addressable memory:
8693
8694- The caller appears to pass the address of a variable of pointer type.
8695 The current value of this variable is copied into the register before
8696 the call; if the call returns normally, the value is copied back into the
8697 variable.
8698- The callee appears to receive the address of a variable. This address
8699 is actually a hidden location in its own stack, initialized with the
8700 value of the register upon entry. When the function returns normally,
8701 the value in that hidden location is written back to the register.
8702
8703A `swift_error_result` parameter must be the last parameter, and it must be
8704preceded by a `swift_context` parameter.
8705
8706A `swift_error_result` parameter must have type `T**` or `T*&` for some
8707type T. Note that no qualifiers are permitted on the intermediate level.
8708
8709It is undefined behavior if the caller does not pass a pointer or
8710reference to a valid object.
8711
8712The standard convention is that the error value itself (that is, the
8713value stored in the apparent argument) will be null upon function entry,
8714but this is not enforced by the ABI.)reST";
8715
8716static const char AttrDoc_SwiftImportAsNonGeneric[] = R"reST()reST";
8717
8718static const char AttrDoc_SwiftImportPropertyAsAccessors[] = R"reST()reST";
8719
8720static const char AttrDoc_SwiftIndirectResult[] = R"reST(The `swift_indirect_result` attribute marks a parameter of a `swiftcall`
8721or `swiftasynccall` function as having the special indirect-result ABI
8722treatment.
8723
8724This treatment gives the parameter the target's normal indirect-result
8725ABI treatment, which may involve passing it differently from an ordinary
8726parameter. However, only the first indirect result will receive this
8727treatment. Furthermore, low-level lowering may decide that a direct result
8728must be returned indirectly; if so, this will take priority over the
8729`swift_indirect_result` parameters.
8730
8731A `swift_indirect_result` parameter must either be the first parameter or
8732follow another `swift_indirect_result` parameter.
8733
8734A `swift_indirect_result` parameter must have type `T*` or `T&` for
8735some object type `T`. If `T` is a complete type at the point of
8736definition of a function, it is undefined behavior if the argument
8737value does not point to storage of adequate size and alignment for a
8738value of type `T`.
8739
8740Making indirect results explicit in the signature allows C functions to
8741directly construct objects into them without relying on language
8742optimizations like C++'s named return value optimization (NRVO).)reST";
8743
8744static const char AttrDoc_SwiftName[] = R"reST(The `swift_name` attribute provides the name of the declaration in Swift. If
8745this attribute is absent, the name is transformed according to the algorithm
8746built into the Swift compiler.
8747
8748The argument is a string literal that contains the Swift name of the function,
8749variable, or type. When renaming a function, the name may be a compound Swift
8750name. For a type, enum constant, property, or variable declaration, the name
8751must be a simple or qualified identifier.
8752
8753```objc
8754@interface URL
8755- (void) initWithString:(NSString *)s __attribute__((__swift_name__("URL.init(_:)")))
8756@end
8757
8758void __attribute__((__swift_name__("squareRoot()"))) sqrt(double v) {
8759}
8760```)reST";
8761
8762static const char AttrDoc_SwiftNewType[] = R"reST(The `swift_newtype` attribute indicates that the typedef to which the
8763attribute appertains is imported as a new Swift type of the typedef's name.
8764Previously, the attribute was spelt `swift_wrapper`. While the behaviour of
8765the attribute is identical with either spelling, `swift_wrapper` is
8766deprecated, only exists for compatibility purposes, and should not be used in
8767new code.
8768
8769- `swift_newtype(struct)` means that a Swift struct will be created for this
8770 typedef.
8771
8772- `swift_newtype(enum)` means that a Swift enum will be created for this
8773 typedef.
8774
8775 ```c
8776 // Import UIFontTextStyle as an enum type, with enumerated values being
8777 // constants.
8778 typedef NSString * UIFontTextStyle __attribute__((__swift_newtype__(enum)));
8779
8780 // Import UIFontDescriptorFeatureKey as a structure type, with enumerated
8781 // values being members of the type structure.
8782 typedef NSString * UIFontDescriptorFeatureKey __attribute__((__swift_newtype__(struct)));
8783 ```)reST";
8784
8785static const char AttrDoc_SwiftNullability[] = R"reST()reST";
8786
8787static const char AttrDoc_SwiftObjCMembers[] = R"reST(This attribute indicates that Swift subclasses and members of Swift extensions
8788of this class will be implicitly marked with the `@objcMembers` Swift
8789attribute, exposing them back to Objective-C.)reST";
8790
8791static const char AttrDoc_SwiftPrivate[] = R"reST(Declarations marked with the `swift_private` attribute are hidden from the
8792framework client but are still made available for use within the framework or
8793Swift SDK overlay.
8794
8795The purpose of this attribute is to permit a more idomatic implementation of
8796declarations in Swift while hiding the non-idiomatic one.)reST";
8797
8798static const char AttrDoc_SwiftType[] = R"reST()reST";
8799
8800static const char AttrDoc_SwiftVersionedAddition[] = R"reST()reST";
8801
8802static const char AttrDoc_SwiftVersionedRemoval[] = R"reST()reST";
8803
8804static const char AttrDoc_SysVABI[] = R"reST(On Windows x86_64 targets, this attribute changes the calling convention of a
8805function to match the default convention used on Sys V targets such as Linux,
8806Mac, and BSD. This attribute has no effect on other targets.)reST";
8807
8808static const char AttrDoc_TLSModel[] = R"reST(The `tls_model` attribute allows you to specify which thread-local storage
8809model to use. It accepts the following strings:
8810
8811- global-dynamic
8812- local-dynamic
8813- initial-exec
8814- local-exec
8815
8816TLS models are mutually exclusive.)reST";
8817
8818static const char AttrDoc_Target[] = R"reST(Clang supports the GNU style `__attribute__((target("OPTIONS")))` attribute.
8819This attribute may be attached to a function definition and instructs
8820the backend to use different code generation options than were passed on the
8821command line.
8822
8823The current set of options correspond to the existing "subtarget features" for
8824the target with or without a "-mno-" in front corresponding to the absence
8825of the feature, as well as `arch="CPU"` which will change the default "CPU"
8826for the function.
8827
8828For X86, the attribute also allows `tune="CPU"` to optimize the generated
8829code for the given CPU without changing the available instructions.
8830
8831For AArch64, `arch="Arch"` will set the architecture, similar to the -march
8832command line options. `cpu="CPU"` can be used to select a specific cpu,
8833as per the `-mcpu` option, similarly for `tune=`. The attribute also allows the
8834"branch-protection=\<args>" option, where the permissible arguments and their
8835effect on code generation are the same as for the command-line option
8836`-mbranch-protection`.
8837
8838Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
8839"avx", "xop" and largely correspond to the machine specific options handled by
8840the front end.
8841
8842Note that this attribute does not apply transitively to nested functions such
8843as blocks or C++ lambdas.
8844
8845Additionally, this attribute supports function multiversioning for ELF based
8846x86/x86-64 targets, which can be used to create multiple implementations of the
8847same function that will be resolved at runtime based on the priority of their
8848`target` attribute strings. A function is considered a multiversioned function
8849if either two declarations of the function have different `target` attribute
8850strings, or if it has a `target` attribute string of `default`. For
8851example:
8852
8853```c++
8854__attribute__((target("arch=atom")))
8855void foo() {} // will be called on 'atom' processors.
8856__attribute__((target("default")))
8857void foo() {} // will be called on any other processors.
8858```
8859
8860All multiversioned functions must contain a `default` (fallback)
8861implementation, otherwise usages of the function are considered invalid.
8862Additionally, a function may not become multiversioned after its first use.)reST";
8863
8864static const char AttrDoc_TargetClones[] = R"reST(Clang supports the `target_clones("OPTIONS")` attribute. This attribute may be
8865attached to a function declaration and causes function multiversioning, where
8866multiple versions of the function will be emitted with different code
8867generation options. Additionally, these versions will be resolved at runtime
8868based on the priority of their attribute options. All `target_clone` functions
8869are considered multiversioned functions.
8870
8871For AArch64 target:
8872The attribute contains comma-separated strings of target features joined by "+"
8873sign. For example:
8874
8875```c++
8876__attribute__((target_clones("sha2+memtag", "fcma+sve2-pmull128")))
8877void foo() {}
8878```
8879
8880For every multiversioned function a `default` (fallback) implementation
8881always generated if not specified directly.
8882
8883For x86/x86-64 targets:
8884All multiversioned functions must contain a `default` (fallback)
8885implementation, otherwise usages of the function are considered invalid.
8886Additionally, a function may not become multiversioned after its first use.
8887
8888The options to `target_clones` can either be a target-specific architecture
8889(specified as `arch=CPU`), or one of a list of subtarget features.
8890
8891Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
8892"avx", "xop" and largely correspond to the machine specific options handled by
8893the front end.
8894
8895The versions can either be listed as a comma-separated sequence of string
8896literals or as a single string literal containing a comma-separated list of
8897versions. For compatibility with GCC, the two formats can be mixed. For
8898example, the following will emit 4 versions of the function:
8899
8900```c++
8901__attribute__((target_clones("arch=atom,avx2","arch=ivybridge","default")))
8902void foo() {}
8903```
8904
8905For targets that support the GNU indirect function (IFUNC) feature, dispatch
8906is performed by emitting an indirect function that is resolved to the appropriate
8907target clone at load time. The indirect function is given the name the
8908multiversioned function would have if it had been declared without the attribute.
8909For backward compatibility with earlier Clang releases, a function alias with an
8910`.ifunc` suffix is also emitted. The `.ifunc` suffixed symbol is a deprecated
8911feature and support for it may be removed in the future.
8912
8913For PowerPC targets, `target_clones` is supported on AIX only. Only CPU
8914(specified as `cpu=CPU`) and `default` options are allowed. IFUNC is supported
8915on AIX in Clang, so dispatch is implemented similar to other targets using IFUNC.
8916An FMV function that is only declared in a translation unit is treated as a
8917non-FMV. The resolver and the function clones are given internal linkage.)reST";
8918
8919static const char AttrDoc_TargetVersion[] = R"reST(For AArch64 target clang supports function multiversioning by
8920`__attribute__((target_version("OPTIONS")))` attribute. When applied to a
8921function it instructs compiler to emit multiple function versions based on
8922`target_version` attribute strings, which resolved at runtime depend on their
8923priority and target features availability. One of the versions is always
8924( implicitly or explicitly ) the `default` (fallback). Attribute strings can
8925contain dependent features names joined by the "+" sign.
8926
8927For targets that support the GNU indirect function (IFUNC) feature, dispatch
8928is performed by emitting an indirect function that is resolved to the appropriate
8929target clone at load time. The indirect function is given the name the
8930multiversioned function would have if it had been declared without the attribute.
8931For backward compatibility with earlier Clang releases, a function alias with an
8932`.ifunc` suffix is also emitted. The `.ifunc` suffixed symbol is a deprecated
8933feature and support for it may be removed in the future.)reST";
8934
8935static const char AttrDoc_TestTypestate[] = R"reST(Use `__attribute__((test_typestate(tested_state)))` to indicate that a method
8936returns true if the object is in the specified state..)reST";
8937
8938static const char AttrDoc_ThisCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
8939function to use ECX for the first parameter (typically the implicit `this`
8940parameter of C++ methods) and clear parameters off of the stack on return. This
8941convention does not support variadic calls or unprototyped functions in C, and
8942has no effect on x86_64 targets. See the documentation for [\_\_thiscall][__thiscall] on
8943MSDN.
8944
8945[__thiscall]: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx)reST";
8946
8947static const char AttrDoc_Thread[] = R"reST(The `__declspec(thread)` attribute declares a variable with thread local
8948storage. It is available under the `-fms-extensions` flag for MSVC
8949compatibility. See the documentation for [\_\_declspec(thread)][__declspec(thread)] on MSDN.
8950
8951In Clang, `__declspec(thread)` is generally equivalent in functionality to the
8952GNU `__thread` keyword. The variable must not have a destructor and must have
8953a constant initializer, if any. The attribute only applies to variables
8954declared with static storage duration, such as globals, class static data
8955members, and static locals.
8956
8957[__declspec(thread)]: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx)reST";
8958
8959static const char AttrDoc_TransparentUnion[] = R"reST(This attribute can be applied to a union to change the behavior of calls to
8960functions that have an argument with a transparent union type. The compiler
8961behavior is changed in the following manner:
8962
8963- A value whose type is any member of the transparent union can be passed as an
8964 argument without the need to cast that value.
8965- The argument is passed to the function using the calling convention of the
8966 first member of the transparent union. Consequently, all the members of the
8967 transparent union should have the same calling convention as its first member.
8968
8969Transparent unions are not supported in C++.)reST";
8970
8971static const char AttrDoc_TrivialABI[] = R"reST(The `trivial_abi` attribute can be applied to a C++ class, struct, or union.
8972It instructs the compiler to pass and return the type using the C ABI for the
8973underlying type when the type would otherwise be considered non-trivial for the
8974purpose of calls.
8975A class annotated with `trivial_abi` can have non-trivial destructors or
8976copy/move constructors without automatically becoming non-trivial for the
8977purposes of calls. For example:
8978
8979```c++
8980// A is trivial for the purposes of calls because `trivial_abi` makes the
8981// user-provided special functions trivial.
8982struct __attribute__((trivial_abi)) A {
8983 ~A();
8984 A(const A &);
8985 A(A &&);
8986 int x;
8987};
8988
8989// B's destructor and copy/move constructor are considered trivial for the
8990// purpose of calls because A is trivial.
8991struct B {
8992 A a;
8993};
8994```
8995
8996If a type is trivial for the purposes of calls, has a non-trivial destructor,
8997and is passed as an argument by value, the convention is that the callee will
8998destroy the object before returning. The lifetime of the copy of the parameter
8999in the caller ends without a destructor call when the call begins.
9000
9001If a type is trivial for the purpose of calls, it is assumed to be trivially
9002relocatable for the purpose of `__is_trivially_relocatable` and
9003`__builtin_is_cpp_trivially_relocatable`.
9004When a type marked with `[[trivial_abi]]` is used as a function argument,
9005the compiler may omit the call to the copy constructor.
9006Thus, side effects of the copy constructor are potentially not performed.
9007For example, objects that contain pointers to themselves or otherwise depend
9008on their address (or the address or their subobjects) should not be declared
9009`[[trivial_abi]]`.
9010
9011Attribute `trivial_abi` has no effect in the following cases:
9012
9013- The class directly declares a virtual base or virtual methods.
9014
9015- Copy constructors and move constructors of the class are all deleted.
9016
9017- The class has a base class that is non-trivial for the purposes of calls.
9018
9019- The class has a non-static data member whose type is non-trivial for the
9020 purposes of calls, which includes:
9021
9022 - classes that are non-trivial for the purposes of calls
9023 - \_\_weak-qualified types in Objective-C++
9024 - arrays of any of the above)reST";
9025
9026static const char AttrDoc_TryAcquireCapability[] = R"reST(Marks a function that attempts to acquire a capability. This function may fail to
9027actually acquire the capability; they accept a Boolean value determining
9028whether acquiring the capability means success (true), or failing to acquire
9029the capability means success (false).)reST";
9030
9031static const char AttrDoc_TypeNonNull[] = R"reST(The `_Nonnull` nullability qualifier indicates that null is not a meaningful
9032value for a value of the `_Nonnull` pointer type. For example, given a
9033declaration such as:
9034
9035```c
9036int fetch(int * _Nonnull ptr);
9037```
9038
9039a caller of `fetch` should not provide a null value, and the compiler will
9040produce a warning if it sees a literal null value passed to `fetch`. Note
9041that, unlike the declaration attribute `nonnull`, the presence of
9042`_Nonnull` does not imply that passing null is undefined behavior: `fetch`
9043is free to consider null undefined behavior or (perhaps for
9044backward-compatibility reasons) defensively handle null.)reST";
9045
9046static const char AttrDoc_TypeNullUnspecified[] = R"reST(The `_Null_unspecified` nullability qualifier indicates that neither the
9047`_Nonnull` nor `_Nullable` qualifiers make sense for a particular pointer
9048type. It is used primarily to indicate that the role of null with specific
9049pointers in a nullability-annotated header is unclear, e.g., due to
9050overly-complex implementations or historical factors with a long-lived API.)reST";
9051
9052static const char AttrDoc_TypeNullable[] = R"reST(The `_Nullable` nullability qualifier indicates that a value of the
9053`_Nullable` pointer type can be null. For example, given:
9054
9055```c
9056int fetch_or_zero(int * _Nullable ptr);
9057```
9058
9059a caller of `fetch_or_zero` can provide null.
9060
9061The `_Nullable` attribute on classes indicates that the given class can
9062represent null values, and so the `_Nullable`, `_Nonnull` etc qualifiers
9063make sense for this type. For example:
9064
9065```c
9066class _Nullable ArenaPointer { ... };
9067
9068ArenaPointer _Nonnull x = ...;
9069ArenaPointer _Nullable y = nullptr;
9070```)reST";
9071
9072static const char AttrDoc_TypeNullableResult[] = R"reST(The `_Nullable_result` nullability qualifier means that a value of the
9073`_Nullable_result` pointer can be `nil`, just like `_Nullable`. Where this
9074attribute differs from `_Nullable` is when it's used on a parameter to a
9075completion handler in a Swift async method. For instance, here:
9076
9077```objc
9078-(void)fetchSomeDataWithID:(int)identifier
9079 completionHandler:(void (^)(Data *_Nullable_result result, NSError *error))completionHandler;
9080```
9081
9082This method asynchronously calls `completionHandler` when the data is
9083available, or calls it with an error. `_Nullable_result` indicates to the
9084Swift importer that this is the uncommon case where `result` can get `nil`
9085even if no error has occurred, and will therefore import it as a Swift optional
9086type. Otherwise, if `result` was annotated with `_Nullable`, the Swift
9087importer will assume that `result` will always be non-nil unless an error
9088occurred.)reST";
9089
9090static const char AttrDoc_TypeTagForDatatype[] = R"reST(When declaring a variable, use
9091`__attribute__((type_tag_for_datatype(kind, type)))` to create a type tag that
9092is tied to the `type` argument given to the attribute.
9093
9094In the attribute prototype above:
9095: - `kind` is an identifier that should be used when annotating all applicable
9096 type tags.
9097 - `type` indicates the name of the type.
9098
9099Clang supports annotating type tags of two forms.
9100
9101- **Type tag that is a reference to a declared identifier.**
9102 Use `__attribute__((type_tag_for_datatype(kind, type)))` when declaring that
9103 identifier:
9104
9105 ```c++
9106 typedef int MPI_Datatype;
9107 extern struct mpi_datatype mpi_datatype_int
9108 __attribute__(( type_tag_for_datatype(mpi,int) ));
9109 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
9110 // &mpi_datatype_int is a type tag. It is tied to type "int".
9111 ```
9112
9113- **Type tag that is an integral literal.**
9114 Declare a `static const` variable with an initializer value and attach
9115 `__attribute__((type_tag_for_datatype(kind, type)))` on that declaration:
9116
9117 ```c++
9118 typedef int MPI_Datatype;
9119 static const MPI_Datatype mpi_datatype_int
9120 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42;
9121 #define MPI_INT ((MPI_Datatype) 42)
9122 // The number 42 is a type tag. It is tied to type "int".
9123 ```
9124
9125The `type_tag_for_datatype` attribute also accepts an optional third argument
9126that determines how the type of the function argument specified by either
9127`arg_idx` or `ptr_idx` is compared against the type associated with the type
9128tag. (Recall that for the `argument_with_type_tag` attribute, the type of the
9129function argument specified by `arg_idx` is compared against the type
9130associated with the type tag. Also recall that for the `pointer_with_type_tag`
9131attribute, the pointee type of the function argument specified by `ptr_idx` is
9132compared against the type associated with the type tag.) There are two supported
9133values for this optional third argument:
9134
9135- `layout_compatible` will cause types to be compared according to
9136 layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the
9137 layout-compatibility rules for two standard-layout struct types and for two
9138 standard-layout union types). This is useful when creating a type tag
9139 associated with a struct or union type. For example:
9140
9141 ```c++
9142 /* In mpi.h */
9143 typedef int MPI_Datatype;
9144 struct internal_mpi_double_int { double d; int i; };
9145 extern struct mpi_datatype mpi_datatype_double_int
9146 __attribute__(( type_tag_for_datatype(mpi,
9147 struct internal_mpi_double_int, layout_compatible) ));
9148
9149 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
9150
9151 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
9152 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
9153
9154 /* In user code */
9155 struct my_pair { double a; int b; };
9156 struct my_pair *buffer;
9157 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the
9158 // layout of my_pair is
9159 // compatible with that of
9160 // internal_mpi_double_int
9161
9162 struct my_int_pair { int a; int b; }
9163 struct my_int_pair *buffer2;
9164 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the
9165 // layout of my_int_pair
9166 // does not match that of
9167 // internal_mpi_double_int
9168 ```
9169
9170- `must_be_null` specifies that the function argument specified by either
9171 `arg_idx` (for the `argument_with_type_tag` attribute) or `ptr_idx` (for
9172 the `pointer_with_type_tag` attribute) should be a null pointer constant.
9173 The second argument to the `type_tag_for_datatype` attribute is ignored. For
9174 example:
9175
9176 ```c++
9177 /* In mpi.h */
9178 typedef int MPI_Datatype;
9179 extern struct mpi_datatype mpi_datatype_null
9180 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
9181
9182 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
9183 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
9184 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
9185
9186 /* In user code */
9187 struct my_pair { double a; int b; };
9188 struct my_pair *buffer;
9189 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
9190 // was specified but buffer
9191 // is not a null pointer
9192 ```)reST";
9193
9194static const char AttrDoc_TypeVisibility[] = R"reST(The `type_visibility` attribute allows the visibility of a type and its vague
9195linkage objects (vtable, typeinfo, typeinfo name) to be controlled separately from
9196the visibility of functions and data members of the type.
9197
9198For example, this can be used to give default visibility to the typeinfo and the vtable
9199of a type while still keeping hidden visibility on its member functions and static data
9200members.
9201
9202This attribute can only be applied to types and namespaces.
9203
9204If both `visibility` and `type_visibility` are applied to a type or a namespace, the
9205visibility specified with the `type_visibility` attribute overrides the visibility
9206provided with the regular `visibility` attribute.)reST";
9207
9208static const char AttrDoc_UPtr[] = R"reST(The `__uptr` qualifier specifies that a 32-bit pointer should be zero
9209extended when converted to a 64-bit pointer.)reST";
9210
9211static const char AttrDoc_Unavailable[] = R"reST(No documentation.)reST";
9212
9213static const char AttrDoc_Uninitialized[] = R"reST(The command-line parameter `-ftrivial-auto-var-init=*` can be used to
9214initialize trivial automatic stack variables. By default, trivial automatic
9215stack variables are uninitialized. This attribute is used to override the
9216command-line parameter, forcing variables to remain uninitialized. It has no
9217semantic meaning in that using uninitialized values is undefined behavior,
9218it rather documents the programmer's intent.)reST";
9219
9220static const char AttrDoc_Unlikely[] = R"reST(The `likely` and `unlikely` attributes are used as compiler hints.
9221The attributes are used to aid the compiler to determine which branch is
9222likely or unlikely to be taken. This is done by marking the branch substatement
9223with one of the two attributes.
9224
9225It isn't allowed to annotate a single statement with both `likely` and
9226`unlikely`. Annotating the `true` and `false` branch of an `if`
9227statement with the same likelihood attribute will result in a diagnostic and
9228the attributes are ignored on both branches.
9229
9230In a `switch` statement it's allowed to annotate multiple `case` labels
9231or the `default` label with the same likelihood attribute. This makes
9232\* all labels without an attribute have a neutral likelihood,
9233\* all labels marked `[[likely]]` have an equally positive likelihood, and
9234\* all labels marked `[[unlikely]]` have an equally negative likelihood.
9235The neutral likelihood is the more likely of path execution than the negative
9236likelihood. The positive likelihood is the more likely of path of execution
9237than the neutral likelihood.
9238
9239These attributes have no effect on the generated code when using
9240PGO (Profile-Guided Optimization) or at optimization level 0.
9241
9242In Clang, the attributes will be ignored if they're not placed on
9243\* the `case` or `default` label of a `switch` statement,
9244\* or on the substatement of an `if` or `else` statement,
9245\* or on the substatement of an `for` or `while` statement.
9246The C++ Standard recommends to honor them on every statement in the
9247path of execution, but that can be confusing:
9248
9249```c++
9250if (b) {
9251 [[unlikely]] --b; // Per the standard this is in the path of
9252 // execution, so this branch should be considered
9253 // unlikely. However, Clang ignores the attribute
9254 // here since it is not on the substatement.
9255}
9256
9257if (b) {
9258 --b;
9259 if(b)
9260 return;
9261 [[unlikely]] --b; // Not in the path of execution,
9262} // the branch has no likelihood information.
9263
9264if (b) {
9265 --b;
9266 foo(b);
9267 // Whether or not the next statement is in the path of execution depends
9268 // on the declaration of foo():
9269 // In the path of execution: void foo(int);
9270 // Not in the path of execution: [[noreturn]] void foo(int);
9271 // This means the likelihood of the branch depends on the declaration
9272 // of foo().
9273 [[unlikely]] --b;
9274}
9275```
9276
9277Below are some example usages of the likelihood attributes and their effects:
9278
9279```c++
9280if (b) [[likely]] { // Placement on the first statement in the branch.
9281 // The compiler will optimize to execute the code here.
9282} else {
9283}
9284
9285if (b)
9286 [[unlikely]] b++; // Placement on the first statement in the branch.
9287else {
9288 // The compiler will optimize to execute the code here.
9289}
9290
9291if (b) {
9292 [[unlikely]] b++; // Placement on the second statement in the branch.
9293} // The attribute will be ignored.
9294
9295if (b) [[likely]] {
9296 [[unlikely]] b++; // No contradiction since the second attribute
9297} // is ignored.
9298
9299if (b)
9300 ;
9301else [[likely]] {
9302 // The compiler will optimize to execute the code here.
9303}
9304
9305if (b)
9306 ;
9307else
9308 // The compiler will optimize to execute the next statement.
9309 [[likely]] b = f();
9310
9311if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
9312else [[likely]]; // and the attributes are ignored.
9313
9314if (b)
9315 [[likely]] int i = 5; // Issues a diagnostic since the attribute
9316 // isn't allowed on a declaration.
9317
9318switch (i) {
9319 [[likely]] case 1: // This value is likely
9320 ...
9321 break;
9322
9323 [[unlikely]] case 2: // This value is unlikely
9324 ...
9325 [[fallthrough]];
9326
9327 case 3: // No likelihood attribute
9328 ...
9329 [[likely]] break; // No effect
9330
9331 case 4: [[likely]] { // attribute on substatement has no effect
9332 ...
9333 break;
9334 }
9335
9336 [[unlikely]] default: // All other values are unlikely
9337 ...
9338 break;
9339}
9340
9341switch (i) {
9342 [[likely]] case 0: // This value and code path is likely
9343 ...
9344 [[fallthrough]];
9345
9346 case 1: // No likelihood attribute, code path is neutral
9347 break; // falling through has no effect on the likelihood
9348
9349 case 2: // No likelihood attribute, code path is neutral
9350 [[fallthrough]];
9351
9352 [[unlikely]] default: // This value and code path are both unlikely
9353 break;
9354}
9355
9356for(int i = 0; i != size; ++i) [[likely]] {
9357 ... // The loop is the likely path of execution
9358}
9359
9360for(const auto &E : Elements) [[likely]] {
9361 ... // The loop is the likely path of execution
9362}
9363
9364while(i != size) [[unlikely]] {
9365 ... // The loop is the unlikely path of execution
9366} // The generated code will optimize to skip the loop body
9367
9368while(true) [[unlikely]] {
9369 ... // The attribute has no effect
9370} // Clang elides the comparison and generates an infinite
9371 // loop
9372```)reST";
9373
9374static const char AttrDoc_UnsafeBufferUsage[] = R"reST(The attribute `[[clang::unsafe_buffer_usage]]` should be placed on functions
9375that need to be avoided as they are prone to buffer overflows or unsafe buffer
9376struct fields. It is designed to work together with the off-by-default compiler
9377warning `-Wunsafe-buffer-usage` to help codebases transition away from raw pointer
9378based buffer management, in favor of safer abstractions such as C++20 `std::span`.
9379The attribute causes `-Wunsafe-buffer-usage` to warn on every use of the function or
9380the field it is attached to, and it may also lead to emission of automatic fix-it
9381hints which would help the user replace the use of unsafe functions(/fields) with safe
9382alternatives, though the attribute can be used even when the fix can't be automated.
9383
9384- Attribute attached to functions: The attribute suppresses all
9385 `-Wunsafe-buffer-usage` warnings within the function it is attached to, as the
9386 function is now classified as unsafe. The attribute should be used carefully, as it
9387 will silence all unsafe operation warnings inside the function; including any new
9388 unsafe operations introduced in the future.
9389
9390 The attribute is warranted even if the only way a function can overflow
9391 the buffer is by violating the function's preconditions. For example, it
9392 would make sense to put the attribute on function `foo()` below because
9393 passing an incorrect size parameter would cause a buffer overflow:
9394
9395 ```c++
9396 [[clang::unsafe_buffer_usage]]
9397 void foo(int *buf, size_t size) {
9398 for (size_t i = 0; i < size; ++i) {
9399 buf[i] = i;
9400 }
9401 }
9402 ```
9403
9404 The attribute is NOT warranted when the function uses safe abstractions,
9405 assuming that these abstractions weren't misused outside the function.
9406 For example, function `bar()` below doesn't need the attribute,
9407 because assuming that the container `buf` is well-formed (has size that
9408 fits the original buffer it refers to), overflow cannot occur:
9409
9410 ```c++
9411 void bar(std::span<int> buf) {
9412 for (size_t i = 0; i < buf.size(); ++i) {
9413 buf[i] = i;
9414 }
9415 }
9416 ```
9417
9418 In this case function `bar()` enables the user to keep the buffer
9419 "containerized" in a span for as long as possible. On the other hand,
9420 Function `foo()` in the previous example may have internal
9421 consistency, but by accepting a raw buffer it requires the user to unwrap
9422 their span, which is undesirable according to the programming model
9423 behind `-Wunsafe-buffer-usage`.
9424
9425 The attribute is warranted when a function accepts a raw buffer only to
9426 immediately put it into a span:
9427
9428 ```c++
9429 [[clang::unsafe_buffer_usage]]
9430 void baz(int *buf, size_t size) {
9431 std::span<int> sp{ buf, size };
9432 for (size_t i = 0; i < sp.size(); ++i) {
9433 sp[i] = i;
9434 }
9435 }
9436 ```
9437
9438 In this case `baz()` does not contain any unsafe operations, but the awkward
9439 parameter type causes the caller to unwrap the span unnecessarily.
9440 Note that regardless of the attribute, code inside `baz()` isn't flagged
9441 by `-Wunsafe-buffer-usage` as unsafe. It is definitely undesirable,
9442 but if `baz()` is on an API surface, there is no way to improve it
9443 to make it as safe as `bar()` without breaking the source and binary
9444 compatibility with existing users of the function. In such cases
9445 the proper solution would be to create a different function (possibly
9446 an overload of `baz()`) that accepts a safe container like `bar()`,
9447 and then use the attribute on the original `baz()` to help the users
9448 update their code to use the new function.
9449
9450- Attribute attached to fields: The attribute should only be attached to
9451 struct fields, if the fields can not be updated to a safe type with bounds
9452 check, such as std::span. In other words, the buffers prone to unsafe accesses
9453 should always be updated to use safe containers/views and attaching the attribute
9454 must be last resort when such an update is infeasible.
9455
9456 The attribute can be placed on individual fields or a set of them as shown below.
9457
9458 ```c++
9459 struct A {
9460 [[clang::unsafe_buffer_usage]]
9461 int *ptr1;
9462
9463 [[clang::unsafe_buffer_usage]]
9464 int *ptr2, buf[10];
9465
9466 [[clang::unsafe_buffer_usage]]
9467 size_t sz;
9468 };
9469 ```
9470
9471 Here, every read/write to the fields ptr1, ptr2, buf and sz will trigger a warning
9472 that the field has been explcitly marked as unsafe due to unsafe-buffer operations.)reST";
9473
9474static const char AttrDoc_Unused[] = R"reST(When passing the `-Wunused` flag to Clang, entities that are unused by the
9475program may be diagnosed. The `[[maybe_unused]]` (or
9476`__attribute__((unused))`) attribute can be used to silence such diagnostics
9477when the entity cannot be removed. For instance, a local variable may exist
9478solely for use in an `assert()` statement, which makes the local variable
9479unused when `NDEBUG` is defined.
9480
9481The attribute may be applied to the declaration of a class, a typedef, a
9482variable, a function or method, a function parameter, an enumeration, an
9483enumerator, a non-static data member, or a label.
9484
9485```c++
9486#include <cassert>
9487
9488[[maybe_unused]] void f([[maybe_unused]] bool thing1,
9489 [[maybe_unused]] bool thing2) {
9490 [[maybe_unused]] bool b = thing1 && thing2;
9491 assert(b);
9492}
9493```)reST";
9494
9495static const char AttrDoc_UseHandle[] = R"reST(A function taking a handle by value might close the handle. If a function
9496parameter is annotated with `use_handle(tag)` it is assumed to not to change
9497the state of the handle. It is also assumed to require an open handle to work with.
9498The attribute requires a string literal argument to identify the handle being used.
9499
9500```c++
9501zx_status_t zx_port_wait(zx_handle_t handle [[clang::use_handle("zircon")]],
9502 zx_time_t deadline,
9503 zx_port_packet_t* packet);
9504```)reST";
9505
9506static const char AttrDoc_Used[] = R"reST(This attribute, when attached to a function or variable definition, indicates
9507that there may be references to the entity which are not apparent in the source
9508code. For example, it may be referenced from inline `asm`, or it may be
9509found through a dynamic symbol or section lookup.
9510
9511The compiler must emit the definition even if it appears to be unused, and it
9512must not apply optimizations which depend on fully understanding how the entity
9513is used.
9514
9515Whether this attribute has any effect on the linker depends on the target and
9516the linker. Most linkers support the feature of section garbage collection
9517(`--gc-sections`), also known as "dead stripping" (`ld64 -dead_strip`) or
9518discarding unreferenced sections (`link.exe /OPT:REF`). On COFF and Mach-O
9519targets (Windows and Apple platforms), the `used` attribute prevents symbols
9520from being removed by linker section GC. On ELF targets, it has no effect on its
9521own, and the linker may remove the definition if it is not otherwise referenced.
9522This linker GC can be avoided by also adding the `retain` attribute. Note
9523that `retain` requires special support from the linker; see that attribute's
9524documentation for further information.)reST";
9525
9526static const char AttrDoc_UsingIfExists[] = R"reST(The `using_if_exists` attribute applies to a using-declaration. It allows
9527programmers to import a declaration that potentially does not exist, instead
9528deferring any errors to the point of use. For instance:
9529
9530```c++
9531namespace empty_namespace {};
9532__attribute__((using_if_exists))
9533using empty_namespace::does_not_exist; // no error!
9534
9535does_not_exist x; // error: use of unresolved 'using_if_exists'
9536```
9537
9538The C++ spelling of the attribute (`[[clang::using_if_exists]]`) is also
9539supported as a clang extension, since ISO C++ doesn't support attributes in this
9540position. If the entity referred to by the using-declaration is found by name
9541lookup, the attribute has no effect. This attribute is useful for libraries
9542(primarily, libc++) that wish to redeclare a set of declarations in another
9543namespace, when the availability of those declarations is difficult or
9544impossible to detect at compile time with the preprocessor.)reST";
9545
9546static const char AttrDoc_Uuid[] = R"reST(No documentation.)reST";
9547
9548static const char AttrDoc_VTablePointerAuthentication[] = R"reST(No documentation.)reST";
9549
9550static const char AttrDoc_VecReturn[] = R"reST(No documentation.)reST";
9551
9552static const char AttrDoc_VecTypeHint[] = R"reST(No documentation.)reST";
9553
9554static const char AttrDoc_VectorCall[] = R"reST(On 32-bit x86 *and* x86_64 targets, this attribute changes the calling
9555convention of a function to pass vector parameters in SSE registers.
9556
9557On 32-bit x86 targets, this calling convention is similar to `__fastcall`.
9558The first two integer parameters are passed in ECX and EDX. Subsequent integer
9559parameters are passed in memory, and callee clears the stack. On x86_64
9560targets, the callee does *not* clear the stack, and integer parameters are
9561passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling
9562convention.
9563
9564On both 32-bit x86 and x86_64 targets, vector and floating point arguments are
9565passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are
9566passed in sequential SSE registers if enough are available. If AVX is enabled,
9567256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that
9568cannot be passed in registers for any reason is passed by reference, which
9569allows the caller to align the parameter memory.
9570
9571See the documentation for [\_\_vectorcall][__vectorcall] on MSDN for more details.
9572
9573[__vectorcall]: http://msdn.microsoft.com/en-us/library/dn375768.aspx)reST";
9574
9575static const char AttrDoc_Visibility[] = R"reST(No documentation.)reST";
9576
9577static const char AttrDoc_WarnUnused[] = R"reST(The `warn_unused` attribute can be placed on the declaration of a structure or union type.
9578When the `-Wunused-variable` diagnostic is enabled, local variables of types which have a non-trivial constructor or destructor are considered "used" by virtue of the constructor or destructor invocations involved.
9579Those constructor or destructor invocations are not considered a use if the type is declared with the `warn_unused` attribute.
9580The variable is considered used if it is named outside of its declaration.
9581
9582This attribute is available in both C and C++ language modes but is primarily useful in C++ for classes which have a non-trivial constructor or destructor but act as a value type rather than an RAII type.
9583
9584```c++
9585struct [[gnu::warn_unused]] S {
9586 S();
9587 ~S();
9588};
9589
9590struct T {
9591 T();
9592 ~T();
9593 };
9594
9595 int func() {
9596 S s1; // -Wunused-variable warning
9597 S s2; // No -Wunused-variable warning because of the member access expression below
9598 S s3; // No -Wunused-variable warning because of the sizeof operand below
9599 T t; // No -Wunused-variable warning
9600
9601 s2.~S();
9602 return sizeof(s3);
9603 }
9604```)reST";
9605
9606static const char AttrDoc_WarnUnusedResult[] = R"reST(Clang supports the ability to diagnose when the results of a function call
9607expression are discarded under suspicious circumstances. A diagnostic is
9608generated when a function or its return type is marked with `[[nodiscard]]`
9609(or `__attribute__((warn_unused_result))`) and the function call appears as a
9610potentially-evaluated discarded-value expression that is not explicitly cast to
9611`void`.
9612
9613A string literal may optionally be provided to the attribute, which will be
9614reproduced in any resulting diagnostics. Redeclarations using different forms
9615of the attribute (with or without the string literal or with different string
9616literal contents) are allowed. If there are redeclarations of the entity with
9617differing string literals, it is unspecified which one will be used by Clang
9618in any resulting diagnostics.
9619
9620```c++
9621struct [[nodiscard]] error_info { /*...*/ };
9622error_info enable_missile_safety_mode();
9623
9624void launch_missiles();
9625void test_missiles() {
9626 enable_missile_safety_mode(); // diagnoses
9627 launch_missiles();
9628}
9629error_info &foo();
9630void f() { foo(); } // Does not diagnose, error_info is a reference.
9631```
9632
9633Additionally, discarded temporaries resulting from a call to a constructor
9634marked with `[[nodiscard]]` or a constructor of a type marked
9635`[[nodiscard]]` will also diagnose. This also applies to type conversions that
9636use the annotated `[[nodiscard]]` constructor or result in an annotated type.
9637
9638```c++
9639struct [[nodiscard]] marked_type {/*..*/ };
9640struct marked_ctor {
9641 [[nodiscard]] marked_ctor();
9642 marked_ctor(int);
9643};
9644
9645struct S {
9646 operator marked_type() const;
9647 [[nodiscard]] operator int() const;
9648};
9649
9650void usages() {
9651 marked_type(); // diagnoses.
9652 marked_ctor(); // diagnoses.
9653 marked_ctor(3); // Does not diagnose, int constructor isn't marked nodiscard.
9654
9655 S s;
9656 static_cast<marked_type>(s); // diagnoses
9657 (int)s; // diagnoses
9658}
9659```)reST";
9660
9661static const char AttrDoc_Weak[] = R"reST(In supported output formats the `weak` attribute can be used to
9662specify that a variable or function should be emitted as a symbol with
9663`weak` (if a definition) or `extern_weak` (if a declaration of an
9664external symbol) [linkage](https://llvm.org/docs/LangRef.html#linkage-types).
9665
9666If there is a non-weak definition of the symbol the linker will select
9667that over the weak. They must have same type and alignment (variables
9668must also have the same size), but may have a different value.
9669
9670If there are multiple weak definitions of same symbol, but no non-weak
9671definition, they should have same type, size, alignment and value, the
9672linker will select one of them (see also [selectany] attribute).
9673
9674If the `weak` attribute is applied to a `const` qualified variable
9675definition that variable is no longer consider a compiletime constant
9676as its value can change during linking (or dynamic linking). This
9677means that it can e.g no longer be part of an initializer expression.
9678
9679```c
9680const int ANSWER __attribute__ ((weak)) = 42;
9681
9682/* This function may be replaced link-time */
9683__attribute__ ((weak)) void debug_log(const char *msg)
9684{
9685 fprintf(stderr, "DEBUG: %s\n", msg);
9686}
9687
9688int main(int argc, const char **argv)
9689{
9690 debug_log ("Starting up...");
9691
9692 /* This may print something else than "6 * 7 = 42",
9693 if there is a non-weak definition of "ANSWER" in
9694 an object linked in */
9695 printf("6 * 7 = %d\n", ANSWER);
9696
9697 return 0;
9698 }
9699```
9700
9701If an external declaration is marked weak and that symbol does not
9702exist during linking (possibly dynamic) the address of the symbol will
9703evaluate to NULL.
9704
9705```c
9706void may_not_exist(void) __attribute__ ((weak));
9707
9708int main(int argc, const char **argv)
9709{
9710 if (may_not_exist) {
9711 may_not_exist();
9712 } else {
9713 printf("Function did not exist\n");
9714 }
9715 return 0;
9716}
9717```)reST";
9718
9719static const char AttrDoc_WeakImport[] = R"reST(No documentation.)reST";
9720
9721static const char AttrDoc_WeakRef[] = R"reST(No documentation.)reST";
9722
9723static const char AttrDoc_WebAssemblyExportName[] = R"reST(Clang supports the `__attribute__((export_name(<name>)))`
9724attribute for the WebAssembly target. This attribute may be attached to a
9725function declaration, where it modifies how the symbol is to be exported
9726from the linked WebAssembly.
9727
9728WebAssembly functions are exported via string name. By default when a symbol
9729is exported, the export name for C/C++ symbols are the same as their C/C++
9730symbol names. This attribute can be used to override the default behavior, and
9731request a specific string name be used instead.)reST";
9732
9733static const char AttrDoc_WebAssemblyFuncref[] = R"reST(Clang supports the `__attribute__((export_name(<name>)))`
9734attribute for the WebAssembly target. This attribute may be attached to a
9735function declaration, where it modifies how the symbol is to be exported
9736from the linked WebAssembly.
9737
9738WebAssembly functions are exported via string name. By default when a symbol
9739is exported, the export name for C/C++ symbols are the same as their C/C++
9740symbol names. This attribute can be used to override the default behavior, and
9741request a specific string name be used instead.)reST";
9742
9743static const char AttrDoc_WebAssemblyImportModule[] = R"reST(Clang supports the `__attribute__((import_module(<module_name>)))`
9744attribute for the WebAssembly target. This attribute may be attached to a
9745function declaration, where it modifies how the symbol is to be imported
9746within the WebAssembly linking environment.
9747
9748WebAssembly imports use a two-level namespace scheme, consisting of a module
9749name, which typically identifies a module from which to import, and a field
9750name, which typically identifies a field from that module to import. By
9751default, module names for C/C++ symbols are assigned automatically by the
9752linker. This attribute can be used to override the default behavior, and
9753request a specific module name be used instead.)reST";
9754
9755static const char AttrDoc_WebAssemblyImportName[] = R"reST(Clang supports the `__attribute__((import_name(<name>)))`
9756attribute for the WebAssembly target. This attribute may be attached to a
9757function declaration, where it modifies how the symbol is to be imported
9758within the WebAssembly linking environment.
9759
9760WebAssembly imports use a two-level namespace scheme, consisting of a module
9761name, which typically identifies a module from which to import, and a field
9762name, which typically identifies a field from that module to import. By
9763default, field names for C/C++ symbols are the same as their C/C++ symbol
9764names. This attribute can be used to override the default behavior, and
9765request a specific field name be used instead.)reST";
9766
9767static const char AttrDoc_WorkGroupSizeHint[] = R"reST(No documentation.)reST";
9768
9769static const char AttrDoc_X86ForceAlignArgPointer[] = R"reST(Use this attribute to force stack alignment.
9770
9771Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions
9772(like 'movaps') that work with the stack require operands to be 16-byte aligned.
9773This attribute realigns the stack in the function prologue to make sure the
9774stack can be used with SSE instructions.
9775
9776Note that the x86_64 ABI forces 16-byte stack alignment at the call site.
9777Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in
9778rare cases where the caller does not align the stack properly (e.g. flow
9779jumps from i386 arch code).
9780
9781```c
9782__attribute__ ((force_align_arg_pointer))
9783void f () {
9784 ...
9785}
9786```)reST";
9787
9788static const char AttrDoc_XRayInstrument[] = R"reST(`__attribute__((xray_always_instrument))` or
9789`[[clang::xray_always_instrument]]` is used to mark member functions (in C++),
9790methods (in Objective C), and free functions (in C, C++, and Objective C) to be
9791instrumented with XRay. This will cause the function to always have space at
9792the beginning and exit points to allow for runtime patching.
9793
9794Conversely, `__attribute__((xray_never_instrument))` or
9795`[[clang::xray_never_instrument]]` will inhibit the insertion of these
9796instrumentation points.
9797
9798If a function has neither of these attributes, they become subject to the XRay
9799heuristics used to determine whether a function should be instrumented or
9800otherwise.
9801
9802`__attribute__((xray_log_args(N)))` or `[[clang::xray_log_args(N)]]` is
9803used to preserve N function arguments for the logging function. Currently,
9804only N==1 is supported.)reST";
9805
9806static const char AttrDoc_XRayLogArgs[] = R"reST(`__attribute__((xray_always_instrument))` or
9807`[[clang::xray_always_instrument]]` is used to mark member functions (in C++),
9808methods (in Objective C), and free functions (in C, C++, and Objective C) to be
9809instrumented with XRay. This will cause the function to always have space at
9810the beginning and exit points to allow for runtime patching.
9811
9812Conversely, `__attribute__((xray_never_instrument))` or
9813`[[clang::xray_never_instrument]]` will inhibit the insertion of these
9814instrumentation points.
9815
9816If a function has neither of these attributes, they become subject to the XRay
9817heuristics used to determine whether a function should be instrumented or
9818otherwise.
9819
9820`__attribute__((xray_log_args(N)))` or `[[clang::xray_log_args(N)]]` is
9821used to preserve N function arguments for the logging function. Currently,
9822only N==1 is supported.)reST";
9823
9824static const char AttrDoc_ZeroCallUsedRegs[] = R"reST(This attribute, when attached to a function, causes the compiler to zero a
9825subset of all call-used registers before the function returns. It's used to
9826increase program security by either mitigating [Return-Oriented Programming][return-oriented programming]
9827(ROP) attacks or preventing information leakage through registers.
9828
9829The term "call-used" means registers which are not guaranteed to be preserved
9830unchanged for the caller by the current calling convention. This could also be
9831described as "caller-saved" or "not callee-saved".
9832
9833The `choice` parameters gives the programmer flexibility to choose the subset
9834of the call-used registers to be zeroed:
9835
9836- `skip` doesn't zero any call-used registers. This choice overrides any
9837 command-line arguments.
9838- `used` only zeros call-used registers used in the function. By `used`, we
9839 mean a register whose contents have been set or referenced in the function.
9840- `used-gpr` only zeros call-used GPR registers used in the function.
9841- `used-arg` only zeros call-used registers used to pass arguments to the
9842 function.
9843- `used-gpr-arg` only zeros call-used GPR registers used to pass arguments to
9844 the function.
9845- `all` zeros all call-used registers.
9846- `all-gpr` zeros all call-used GPR registers.
9847- `all-arg` zeros all call-used registers used to pass arguments to the
9848 function.
9849- `all-gpr-arg` zeros all call-used GPR registers used to pass arguments to
9850 the function.
9851
9852The default for the attribute is controlled by the `-fzero-call-used-regs`
9853flag.
9854
9855[return-oriented programming]: https://en.wikipedia.org/wiki/Return-oriented_programming)reST";
9856