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](#opencl-address-spaces), `__global__`, `__local__`,
323or something else.
324:::
325
326The `address_space` attribute functions as a type qualifier that allows the
327programmer to specify the address space for a pointer or reference type.
328Qualified pointer types are considered distinct types for the purposes of
329overload resolution. The attribute takes a single, non-negative integer
330constant expression identifying the address space. For example:
331
332```c
333int * __attribute__((address_space(1))) ptr;
334
335void foo(__attribute__((address_space(2))) float *buf);
336```
337
338Only one address space qualifier may be applied to a given pointer or reference
339type. Where address spaces are allowed (e.g., variables, parameters, return
340types) and what values are valid depends on the target and language mode.
341
342The meaning of each value is defined by the target; multiple address spaces are
343used in environments such as OpenCL, CUDA, HIP, and other GPU programming
344models to distinguish global, local, constant, and private memory. See for
345example the address spaces defined in the [NVPTX User Guide][nvptx user guide] and the
346[AMDGPU User Guide][amdgpu user guide].
347
348Address spaces may partially overlap or be entirely distinct. The compiler may
349reject attempts to convert between distinct, incompatible address spaces.
350Pointer width may vary between different address spaces, so some explicit casts
351may truncate.
352
353For more information, refer to [ISO TR18037][iso tr18037], which covers embedded C language
354extensions. Section 5 covers named address spaces.
355
356[amdgpu user guide]: https://llvm.org/docs/AMDGPUUsage.html#address-spaces
357[iso tr18037]: https://standards.iso.org/ittf/PubliclyAvailableStandards/c051126_ISO_IEC_TR_18037_2008.zip
358[nvptx user guide]: https://llvm.org/docs/NVPTXUsage.html#address-spaces)reST";
359
360static const char AttrDoc_Alias[] = R"reST(No documentation.)reST";
361
362static const char AttrDoc_AlignMac68k[] = R"reST()reST";
363
364static const char AttrDoc_AlignNatural[] = R"reST()reST";
365
366static const char AttrDoc_AlignValue[] = R"reST(The align_value attribute can be added to the typedef of a pointer type or the
367declaration of a variable of pointer or reference type. It specifies that the
368pointer will point to, or the reference will bind to, only objects with at
369least the provided alignment. This alignment value must be some positive power
370of 2.
371
372```c
373typedef double * aligned_double_ptr __attribute__((align_value(64)));
374void foo(double & x __attribute__((align_value(128))),
375 aligned_double_ptr y) { ... }
376```
377
378If the pointer value does not have the specified alignment at runtime, the
379behavior of the program is undefined.)reST";
380
381static const char AttrDoc_Aligned[] = R"reST(No documentation.)reST";
382
383static const char AttrDoc_AllocAlign[] = R"reST(Use `__attribute__((alloc_align(<parameter-index>)))` on a declaration with a
384function prototype to specify that the prototype's return value (which must be a
385pointer type) is at least as aligned as the value of the indicated parameter.
386This includes functions, Objective-C methods, blocks, and declarations of
387function pointer, member function pointer, function reference, and block pointer
388types. The attribute can also be applied to typedef or type alias declarations
389whose underlying type has a function prototype.
390
391The parameter is given by its index in the list of formal parameters; the first
392parameter has index 1 unless the function is a C++ non-static member function,
393in which case the first parameter has index 2 to account for the implicit `this`
394parameter.
395
396```c++
397// The returned pointer has the alignment specified by the first parameter.
398void *a(size_t align) __attribute__((alloc_align(1)));
399
400// The function pointer's returned pointer has the alignment specified by
401// the first parameter of the pointed-to function.
402void *(*allocator)(size_t align) __attribute__((alloc_align(1)));
403
404// The returned pointer has the alignment specified by the second parameter.
405void *b(void *v, size_t align) __attribute__((alloc_align(2)));
406
407// The returned pointer has the alignment specified by the second visible
408// parameter, however it must be adjusted for the implicit 'this' parameter.
409void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3)));
410```
411
412Note that this attribute merely informs the compiler that a function always
413returns a sufficiently aligned pointer. It does not cause the compiler to
414emit code to enforce that alignment. The behavior is undefined if the returned
415pointer is not sufficiently aligned.)reST";
416
417static const char AttrDoc_AllocSize[] = R"reST(The `alloc_size` attribute can be placed on functions that return pointers in
418order to hint to the compiler how many bytes of memory will be available at the
419returned pointer. `alloc_size` takes one or two arguments.
420
421- `alloc_size(N)` implies that argument number N equals the number of
422 available bytes at the returned pointer.
423- `alloc_size(N, M)` implies that the product of argument number N and
424 argument number M equals the number of available bytes at the returned
425 pointer.
426
427Argument numbers are 1-based.
428
429An example of how to use `alloc_size`
430
431```c
432void *my_malloc(int a) __attribute__((alloc_size(1)));
433void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2)));
434
435int main() {
436 void *const p = my_malloc(100);
437 assert(__builtin_object_size(p, 0) == 100);
438 void *const a = my_calloc(20, 5);
439 assert(__builtin_object_size(a, 0) == 100);
440}
441```
442
443When `-Walloc-size` is enabled, this attribute allows the compiler to
444diagnose cases when the allocated memory is insufficient for the size of the
445type the returned pointer is cast to.
446
447```c
448void *my_malloc(int a) __attribute__((alloc_size(1)));
449void consumer_func(int *);
450
451int main() {
452 int *ptr = my_malloc(sizeof(int)); // no warning
453 int *w = my_malloc(1); // warning: allocation of insufficient size '1' for type 'int' with size '4'
454 consumer_func(my_malloc(1)); // warning: allocation of insufficient size '1' for type 'int' with size '4'
455}
456```
457
458:::{Note}
459This attribute works differently in clang than it does in GCC.
460Specifically, clang will only trace `const` pointers (as above); we give up
461on pointers that are not marked as `const`. In the vast majority of cases,
462this is unimportant, because LLVM has support for the `alloc_size`
463attribute. However, this may cause mildly unintuitive behavior when used with
464other attributes, such as `enable_if`.
465:::)reST";
466
467static const char AttrDoc_Allocating[] = R"reST(Declares that a function potentially allocates heap memory, and prevents any potential inference
468of `nonallocating` by the compiler.)reST";
469
470static const char AttrDoc_AlwaysDestroy[] = R"reST(The `always_destroy` attribute specifies that a variable with static or thread
471storage duration should have its exit-time destructor run. This attribute is the
472default unless clang was invoked with `-fno-c++-static-destructors`.
473
474If a variable is explicitly declared with this attribute, Clang will silence
475otherwise applicable `-Wexit-time-destructors` warnings.)reST";
476
477static const char AttrDoc_AlwaysInline[] = R"reST(Inlining heuristics are disabled and inlining is always attempted regardless of
478optimization level.
479
480`[[clang::always_inline]]` spelling can be used as a statement attribute; other
481spellings of the attribute are not supported on statements. If a statement is
482marked `[[clang::always_inline]]` and contains calls, the compiler attempts
483to inline those calls.
484
485```c
486int example(void) {
487 int i;
488 [[clang::always_inline]] foo(); // attempts to inline foo
489 [[clang::always_inline]] i = bar(); // attempts to inline bar
490 [[clang::always_inline]] return f(42, baz(bar())); // attempts to inline everything
491}
492```
493
494A declaration statement, which is a statement, is not a statement that can have an
495attribute associated with it (the attribute applies to the declaration, not the
496statement in that case). So this use case will not work:
497
498```c
499int example(void) {
500 [[clang::always_inline]] int i = bar();
501 return i;
502}
503```
504
505This attribute does not guarantee that inline substitution actually occurs.
506
507:::{Note}
508Note: applying this attribute to a coroutine at the `-O0` optimization level
509has no effect; other optimization levels may only partially inline and result in a
510diagnostic.
511:::
512
513See also [the Microsoft Docs on Inline Functions][the microsoft docs on inline functions], [the GCC Common Function
514Attribute docs][the gcc common function attribute docs], and [the GCC Inline docs][the gcc inline docs].
515
516[the gcc common function attribute docs]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html
517[the gcc inline docs]: https://gcc.gnu.org/onlinedocs/gcc/Inline.html
518[the microsoft docs on inline functions]: https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp)reST";
519
520static const char AttrDoc_AnalyzerNoReturn[] = R"reST(No documentation.)reST";
521
522static const char AttrDoc_Annotate[] = R"reST(The `annotate` attribute is used to add annotations to declarations or statements,
523typically for use by static analysis tools that are not integrated into the
524core Clang compiler (e.g., Clang-Tidy checks or out-of-tree Clang-based tools).
525It is a counterpart to the `annotate_type` attribute, which serves the same
526purpose, but for types.
527
528The attribute takes a mandatory string literal argument specifying the
529annotation category and an arbitrary number of optional arguments that provide
530additional information specific to the annotation category. The optional
531arguments must be constant expressions of arbitrary type.
532
533For example:
534
535```c++
536[[clang::annotate("category1", "foo", 1)]] void func(int val [[clang::annotate("category2")]]) {
537 [[clang::annotate("category3")]] if (val) {
538
539 }
540}
541```)reST";
542
543static const char AttrDoc_AnnotateType[] = R"reST(This attribute is used to add annotations to types, typically for use by static
544analysis tools that are not integrated into the core Clang compiler (e.g.,
545Clang-Tidy checks or out-of-tree Clang-based tools). It is a counterpart to the
546`annotate` attribute, which serves the same purpose, but for declarations.
547
548The attribute takes a mandatory string literal argument specifying the
549annotation category and an arbitrary number of optional arguments that provide
550additional information specific to the annotation category. The optional
551arguments must be constant expressions of arbitrary type.
552
553For example:
554
555```c++
556int* [[clang::annotate_type("category1", "foo", 1)]] f(int[[clang::annotate_type("category2")]] *);
557```
558
559The attribute does not have any effect on the semantics of the type system,
560neither type checking rules, nor runtime semantics. In particular:
561
562- `std::is_same<T, T [[clang::annotate_type("foo")]]>` is true for all types
563 `T`.
564- It is not permissible for overloaded functions or template specializations
565 to differ merely by an `annotate_type` attribute.
566- The presence of an `annotate_type` attribute will not affect name
567 mangling.)reST";
568
569static const char AttrDoc_AnyX86Interrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt))` attribute on X86
570targets. This attribute may be attached to a function definition and instructs
571the backend to generate appropriate function entry/exit code so that it can be
572used directly as an interrupt service routine.
573
574Interrupt handlers have access to the stack frame pushed onto the stack by the processor,
575and return using the `IRET` instruction. All registers in an interrupt handler are callee-saved.
576Exception handlers also have access to the error code pushed onto the stack by the processor,
577when applicable.
578
579An interrupt handler must take the following arguments:
580
581```c
582__attribute__ ((interrupt))
583void f (struct stack_frame *frame) {
584 ...
585}
586```
587
588Where `struct stack_frame` is a suitable struct matching the stack frame pushed
589by the processor.
590
591An exception handler must take the following arguments:
592
593```c
594__attribute__ ((interrupt))
595void g (struct stack_frame *frame, unsigned long code) {
596 ...
597}
598```
599
600On 32-bit targets, the `code` argument should be of type `unsigned int`.
601
602Exception handlers should only be used when an error code is pushed by the processor.
603Using the incorrect handler type will crash the system.
604
605Interrupt and exception handlers cannot be called by other functions and must have return type `void`.
606
607Interrupt and exception handlers should only call functions with the `no_caller_saved_registers`
608attribute, or should be compiled with the `-mgeneral-regs-only` flag to avoid saving unused
609non-GPR registers.)reST";
610
611static const char AttrDoc_AnyX86NoCallerSavedRegisters[] = R"reST(Use this attribute to indicate that the specified function has no
612caller-saved registers. That is, all registers are callee-saved except for
613registers used for passing parameters to the function or returning parameters
614from the function.
615The compiler saves and restores any modified registers that were not used for
616passing or returning arguments to the function.
617
618The user can call functions specified with the `no_caller_saved_registers`
619attribute from an interrupt handler without saving and restoring all
620call-clobbered registers.
621
622Functions specified with the `no_caller_saved_registers` attribute should only
623call other functions with the `no_caller_saved_registers` attribute, or should be
624compiled with the `-mgeneral-regs-only` flag to avoid saving unused non-GPR registers.
625
626Note that `no_caller_saved_registers` attribute is not a calling convention.
627In fact, it only overrides the decision of which registers should be saved by
628the caller, but not how the parameters are passed from the caller to the callee.
629
630For example:
631
632```c
633__attribute__ ((no_caller_saved_registers, fastcall))
634void f (int arg1, int arg2) {
635 ...
636}
637```
638
639In this case parameters `arg1` and `arg2` will be passed in registers.
640In this case, on 32-bit x86 targets, the function `f` will use ECX and EDX as
641register parameters. However, it will not assume any scratch registers and
642should save and restore any modified registers except for ECX and EDX.)reST";
643
644static const char AttrDoc_AnyX86NoCfCheck[] = R"reST(Jump Oriented Programming attacks rely on tampering with addresses used by
645indirect call / jmp, e.g. redirect control-flow to non-programmer
646intended bytes in the binary.
647X86 Supports Indirect Branch Tracking (IBT) as part of Control-Flow
648Enforcement Technology (CET). IBT instruments ENDBR instructions used to
649specify valid targets of indirect call / jmp.
650The `nocf_check` attribute has two roles:
6511\. Appertains to a function - do not add ENDBR instruction at the beginning of
652the function.
6532\. Appertains to a function pointer - do not track the target function of this
654pointer (by adding nocf_check prefix to the indirect-call instruction).)reST";
655
656static const char AttrDoc_ArcWeakrefUnavailable[] = R"reST(No documentation.)reST";
657
658static const char AttrDoc_ArgumentWithTypeTag[] = R"reST(Use `__attribute__((argument_with_type_tag(arg_kind, arg_idx,
659type_tag_idx)))` on a function declaration to specify that the function
660accepts a type tag that determines the type of some other argument.
661
662This attribute is primarily useful for checking arguments of variadic functions
663(`pointer_with_type_tag` can be used in most non-variadic cases).
664
665In the attribute prototype above:
666: - `arg_kind` is an identifier that should be used when annotating all
667 applicable type tags.
668 - `arg_idx` provides the position of a function argument. The expected type of
669 this function argument will be determined by the function argument specified
670 by `type_tag_idx`. In the code example below, "3" means that the type of the
671 function's third argument will be determined by `type_tag_idx`.
672 - `type_tag_idx` provides the position of a function argument. This function
673 argument will be a type tag. The type tag will determine the expected type of
674 the argument specified by `arg_idx`. In the code example below, "2" means
675 that the type tag associated with the function's second argument should agree
676 with the type of the argument specified by `arg_idx`.
677
678For example:
679
680```c++
681int fcntl(int fd, int cmd, ...)
682 __attribute__(( argument_with_type_tag(fcntl,3,2) ));
683// The function's second argument will be a type tag; this type tag will
684// determine the expected type of the function's third argument.
685```)reST";
686
687static const char AttrDoc_ArmAgnostic[] = R"reST(The `__arm_agnostic` keyword applies to prototyped function types and
688affects the function's calling convention for a given state S. This
689attribute allows the user to describe a function that preserves S, without
690requiring the function to share S with its callers and without making
691the assumption that S exists.
692
693If a function has the `__arm_agnostic(S)` attribute and calls a function
694without this attribute, then the function's object code will contain code
695to preserve state S. Otherwise, the function's object code will be the same
696as if it did not have the attribute.
697
698The attribute takes string arguments to describe state S. The supported
699states are:
700
701- `"sme_za_state"` for state enabled by PSTATE.ZA, such as ZA and ZT0.
702
703The attribute `__arm_agnostic("sme_za_state")` cannot be used in conjunction
704with `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` or
705`__arm_preserves(S)` where state S describes state enabled by PSTATE.ZA,
706such as "za" or "zt0".)reST";
707
708static const char AttrDoc_ArmBuiltinAlias[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics.
709It allows the intrinsic functions to
710be declared using the names defined in ACLE, and still be recognized
711as clang builtins equivalent to the underlying name. For example,
712`arm_mve.h` declares the function `vaddq_u32` with
713`__attribute__((__clang_arm_mve_alias(__builtin_arm_mve_vaddq_u32)))`,
714and similarly, one of the type-overloaded declarations of `vaddq`
715will have the same attribute. This ensures that both functions are
716recognized as that clang builtin, and in the latter case, the choice
717of which builtin to identify the function as can be deferred until
718after overload resolution.
719
720This attribute can only be used to set up the aliases for certain Arm
721intrinsic functions; it is intended for use only inside `arm_*.h`
722and is not a general mechanism for declaring arbitrary aliases for
723clang builtin functions.
724
725In order to avoid duplicating the attribute definitions for similar
726purpose for other architecture, there is a general form for the
727attribute `clang_builtin_alias`.)reST";
728
729static const char AttrDoc_ArmIn[] = R"reST(The `__arm_in` keyword applies to prototyped function types and specifies
730that the function shares a given state S with its caller. For `__arm_in`, the
731function takes the state S as input and returns with the state S unchanged.
732
733The attribute takes string arguments to instruct the compiler which state
734is shared. The supported states for S are:
735
736- `"za"` for Matrix Storage (requires SME)
737
738The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and
739`__arm_preserves(S)` are all mutually exclusive for the same state S.)reST";
740
741static const char AttrDoc_ArmInOut[] = R"reST(The `__arm_inout` keyword applies to prototyped function types and specifies
742that the function shares a given state S with its caller. For `__arm_inout`,
743the function takes the state S as input and returns new state for S.
744
745The attribute takes string arguments to instruct the compiler which state
746is shared. The supported states for S are:
747
748- `"za"` for Matrix Storage (requires SME)
749
750The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and
751`__arm_preserves(S)` are all mutually exclusive for the same state S.)reST";
752
753static const char AttrDoc_ArmLocallyStreaming[] = R"reST(The `__arm_locally_streaming` keyword applies to function declarations
754and specifies that all the statements in the function are executed in
755streaming mode. This means that:
756
757- the function requires that the target processor implements the Scalable Matrix
758 Extension (SME).
759- the program automatically puts the machine into streaming mode before
760 executing the statements and automatically restores the previous mode
761 afterwards.
762
763Clang manages PSTATE.SM automatically; it is not the source code's
764responsibility to do this. For example, Clang will emit code to enable
765streaming mode at the start of the function, and disable streaming mode
766at the end of the function.)reST";
767
768static const char AttrDoc_ArmMveStrictPolymorphism[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics for the Arm
769MVE instruction set. It is used to define the vector types used by the MVE
770intrinsics.
771
772Its effect is to modify the behavior of a vector type with respect to function
773overloading. If a candidate function for overload resolution has a parameter
774type with this attribute, then the selection of that candidate function will be
775disallowed if the actual argument can only be converted via a lax vector
776conversion. The aim is to prevent spurious ambiguity in ARM MVE polymorphic
777intrinsics.
778
779```c++
780void overloaded(uint16x8_t vector, uint16_t scalar);
781void overloaded(int32x4_t vector, int32_t scalar);
782uint16x8_t myVector;
783uint16_t myScalar;
784
785// myScalar is promoted to int32_t as a side effect of the addition,
786// so if lax vector conversions are considered for myVector, then
787// the two overloads are equally good (one argument conversion
788// each). But if the vector has the __clang_arm_mve_strict_polymorphism
789// attribute, only the uint16x8_t,uint16_t overload will match.
790overloaded(myVector, myScalar + 1);
791```
792
793However, this attribute does not prohibit lax vector conversions in contexts
794other than overloading.
795
796```c++
797uint16x8_t function();
798
799// This is still permitted with lax vector conversion enabled, even
800// if the vector types have __clang_arm_mve_strict_polymorphism
801int32x4_t result = function();
802```)reST";
803
804static const char AttrDoc_ArmNew[] = R"reST(The `__arm_new` keyword applies to function declarations and specifies
805that the function will create a new scope for state S.
806
807The attribute takes string arguments to instruct the compiler for which state
808to create new scope. The supported states for S are:
809
810- `"za"` for Matrix Storage (requires SME)
811
812For state `"za"`, this means that:
813
814- the function requires that the target processor implements the Scalable Matrix
815 Extension (SME).
816- the function will commit any lazily saved ZA data.
817- the function will create a new ZA context and enable PSTATE.ZA.
818- the function will disable PSTATE.ZA (by setting it to 0) before returning.
819
820For `__arm_new("za")` functions Clang will set up the ZA context automatically
821on entry to the function and disable it before returning. For example, if ZA is
822in a dormant state Clang will generate the code to commit a lazy-save and set up
823a new ZA state before executing user code.)reST";
824
825static const char AttrDoc_ArmOut[] = R"reST(The `__arm_out` keyword applies to prototyped function types and specifies
826that the function shares a given state S with its caller. For `__arm_out`,
827the function ignores the incoming state for S and returns new state for S.
828
829The attribute takes string arguments to instruct the compiler which state
830is shared. The supported states for S are:
831
832- `"za"` for Matrix Storage (requires SME)
833
834The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and
835`__arm_preserves(S)` are all mutually exclusive for the same state S.)reST";
836
837static const char AttrDoc_ArmPreserves[] = R"reST(The `__arm_preserves` keyword applies to prototyped function types and
838specifies that the function does not read a given state S and returns
839with state S unchanged.
840
841The attribute takes string arguments to instruct the compiler which state
842is shared. The supported states for S are:
843
844- `"za"` for Matrix Storage (requires SME)
845
846The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and
847`__arm_preserves(S)` are all mutually exclusive for the same state S.)reST";
848
849static const char AttrDoc_ArmStreaming[] = R"reST(The `__arm_streaming` keyword applies to prototyped function types and specifies
850that the function has a "streaming interface". This means that:
851
852- the function requires that the processor implements the Scalable Matrix
853 Extension (SME).
854- the function must be entered in streaming mode (that is, with PSTATE.SM
855 set to 1)
856- the function must return in streaming mode
857
858Clang manages PSTATE.SM automatically; it is not the source code's
859responsibility to do this. For example, if a non-streaming
860function calls an `__arm_streaming` function, Clang generates code
861that switches into streaming mode before calling the function and
862switches back to non-streaming mode on return.)reST";
863
864static const char AttrDoc_ArmStreamingCompatible[] = R"reST(The `__arm_streaming_compatible` keyword applies to prototyped function types and
865specifies that the function has a "streaming compatible interface". This
866means that:
867
868- the function may be entered in either non-streaming mode (PSTATE.SM=0) or
869 in streaming mode (PSTATE.SM=1).
870- the function must return in the same mode as it was entered.
871- the code executed in the function is compatible with either mode.
872
873Clang manages PSTATE.SM automatically; it is not the source code's
874responsibility to do this. Clang will ensure that the generated code in
875streaming-compatible functions is valid in either mode (PSTATE.SM=0 or
876PSTATE.SM=1). For example, if an `__arm_streaming_compatible` function calls a
877non-streaming function, Clang generates code to temporarily switch out of streaming
878mode before calling the function and switch back to streaming-mode on return if
879`PSTATE.SM` is `1` on entry of the caller. If `PSTATE.SM` is `0` on
880entry to the `__arm_streaming_compatible` function, the call will be executed
881without changing modes.)reST";
882
883static const char AttrDoc_Artificial[] = R"reST(The `artificial` attribute can be applied to an inline function. If such a
884function is inlined, the attribute indicates that debuggers should associate
885the resulting instructions with the call site, rather than with the
886corresponding line within the inlined callee.)reST";
887
888static const char AttrDoc_AsmLabel[] = R"reST(This attribute can be used on a function or variable to specify its symbol name.
889
890On some targets, all C symbols are prefixed by default with a single character,
891typically `_`. This was done historically to distinguish them from symbols
892used by other languages. (This prefix is also added to the standard Itanium
893C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true
894symbol name for a C++ variable declared as `int cppvar;` would be
895`__Z6cppvar`; note the two underscores.) This prefix is *not* added to the
896symbol names specified by the `__asm` attribute; programmers wishing to match
897a C symbol name must compensate for this.
898
899For example, consider the following C code:
900
901```c
902int var1 __asm("altvar") = 1; // "altvar" in symbol table.
903int var2 = 1; // "_var2" in symbol table.
904
905void func1(void) __asm("altfunc");
906void func1(void) {} // "altfunc" in symbol table.
907void func2(void) {} // "_func2" in symbol table.
908```
909
910Clang's implementation of this attribute is compatible with GCC's, [documented here](https://gcc.gnu.org/onlinedocs/gcc/Asm-Labels.html).
911
912While it is possible to use this attribute to name a special symbol used
913internally by the compiler, such as an LLVM intrinsic, this is neither
914recommended nor supported and may cause the compiler to crash or miscompile.
915Users who wish to gain access to intrinsic behavior are strongly encouraged to
916request new builtin functions.)reST";
917
918static const char AttrDoc_AssertCapability[] = R"reST(Marks a function that dynamically tests whether a capability is held, and halts
919the program if it is not held.)reST";
920
921static const char AttrDoc_AssumeAligned[] = R"reST(Use `__attribute__((assume_aligned(<alignment>[,<offset>]))` on a function
922declaration to specify that the return value of the function (which must be a
923pointer type) has the specified offset, in bytes, from an address with the
924specified alignment. The offset is taken to be zero if omitted.
925
926```c++
927// The returned pointer value has 32-byte alignment.
928void *a() __attribute__((assume_aligned (32)));
929
930// The returned pointer value is 4 bytes greater than an address having
931// 32-byte alignment.
932void *b() __attribute__((assume_aligned (32, 4)));
933```
934
935Note that this attribute provides information to the compiler regarding a
936condition that the code already ensures is true. It does not cause the compiler
937to enforce the provided alignment assumption.)reST";
938
939static const char AttrDoc_Atomic[] = R"reST(The `atomic` attribute can be applied to *compound statements* to override or
940further specify the default atomic code-generation behavior, especially on
941targets such as AMDGPU. You can annotate compound statements with options
942to modify how atomic instructions inside that statement are emitted at the IR
943level.
944
945For details, see the documentation for
946{ref}`@atomic <langext-atomic-code-generation>`)reST";
947
948static const char AttrDoc_Availability[] = R"reST(The `availability` attribute can be placed on declarations to describe the
949lifecycle of that declaration relative to operating system versions. Consider
950the function declaration for a hypothetical function `f`:
951
952```c++
953void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
954```
955
956The availability attribute states that `f` was introduced in macOS 10.4,
957deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information
958is used by Clang to determine when it is safe to use `f`: for example, if
959Clang is instructed to compile code for macOS 10.5, a call to `f()`
960succeeds. If Clang is instructed to compile code for macOS 10.6, the call
961succeeds but Clang emits a warning specifying that the function is deprecated.
962Finally, if Clang is instructed to compile code for macOS 10.7, the call
963fails because `f()` is no longer available.
964
965Clang is instructed to compile code for a minimum deployment version using
966the `-target` or `-mtargetos` command line arguments. For example,
967macOS 10.7 would be specified as `-target x86_64-apple-macos10.7` or
968`-mtargetos=macos10.7`. Variants like Mac Catalyst are specified as
969`-target arm64-apple-ios15.0-macabi` or `-mtargetos=ios15.0-macabi`
970
971The availability attribute is a comma-separated list starting with the
972platform name and then including clauses specifying important milestones in the
973declaration's lifetime (in any order) along with additional information. Those
974clauses can be:
975
976introduced=*version*
977
978: The first version in which this declaration was introduced.
979
980deprecated=*version*
981
982: The first version in which this declaration was deprecated, meaning that
983 users should migrate away from this API.
984
985obsoleted=*version*
986
987: The first version in which this declaration was obsoleted, meaning that it
988 was removed completely and can no longer be used.
989
990unavailable
991
992: This declaration is never available on this platform.
993
994message=*string-literal*
995
996: Additional message text that Clang will provide when emitting a warning or
997 error about use of a deprecated or obsoleted declaration. Useful to direct
998 users to replacement APIs.
999
1000replacement=*string-literal*
1001
1002: Additional message text that Clang will use to provide Fix-It when emitting
1003 a warning about use of a deprecated declaration. The Fix-It will replace
1004 the deprecated declaration with the new declaration specified.
1005
1006environment=*identifier*
1007
1008: Target environment in which this declaration is available. If present,
1009 the availability attribute applies only to targets with the same platform
1010 and environment. The parameter is currently supported only in HLSL.
1011
1012Multiple availability attributes can be placed on a declaration, which may
1013correspond to different platforms. For most platforms, the availability
1014attribute with the platform corresponding to the target platform will be used;
1015any others will be ignored. However, the availability for `watchOS` and
1016`tvOS` can be implicitly inferred from an `iOS` availability attribute.
1017Any explicit availability attributes for those platforms are still preferred over
1018the implicitly inferred availability attributes. If no availability attribute
1019specifies availability for the current target platform, the availability
1020attributes are ignored. Supported platforms are:
1021
1022`iOS`
1023`macOS`
1024`tvOS`
1025`watchOS`
1026`iOSApplicationExtension`
1027`macOSApplicationExtension`
1028`tvOSApplicationExtension`
1029`watchOSApplicationExtension`
1030`macCatalyst`
1031`macCatalystApplicationExtension`
1032`visionOS`
1033`visionOSApplicationExtension`
1034`driverkit`
1035`anyAppleOS`
1036`swift`
1037`android`
1038`fuchsia`
1039`ohos`
1040`zos`
1041`ShaderModel`
1042
1043Some platforms have alias names:
1044
1045`ios`
1046`macos`
1047`macosx (deprecated)`
1048`tvos`
1049`watchos`
1050`ios_app_extension`
1051`macos_app_extension`
1052`macosx_app_extension (deprecated)`
1053`tvos_app_extension`
1054`watchos_app_extension`
1055`maccatalyst`
1056`maccatalyst_app_extension`
1057`visionos`
1058`visionos_app_extension`
1059`anyappleos`
1060`shadermodel`
1061
1062Supported environment names for the ShaderModel platform:
1063
1064`pixel`
1065`vertex`
1066`geometry`
1067`hull`
1068`domain`
1069`compute`
1070`raygeneration`
1071`intersection`
1072`anyhit`
1073`closesthit`
1074`miss`
1075`callable`
1076`mesh`
1077`amplification`
1078`library`
1079
1080The special platform `anyAppleOS` (alias: `anyappleos`) is a shorthand that
1081applies the availability attribute to all Apple Darwin platforms. An explicit
1082platform-specific availability attribute takes precedence over an `anyAppleOS`
1083attribute for that platform. Versions specified with `anyAppleOS` must be at
1084least 26.0, which is the first OS release where all supported Apple platforms
1085share a unified version number.
1086
1087A declaration can typically be used even when deploying back to a platform
1088version prior to when the declaration was introduced. When this happens, the
1089declaration is [weakly linked](https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html),
1090as if the `weak_import` attribute were added to the declaration. A
1091weakly-linked declaration may or may not be present a run-time, and a program
1092can determine whether the declaration is present by checking whether the
1093address of that declaration is non-NULL.
1094
1095The flag `strict` disallows using API when deploying back to a
1096platform version prior to when the declaration was introduced. An
1097attempt to use such API before its introduction causes a hard error.
1098Weakly-linking is almost always a better API choice, since it allows
1099users to query availability at runtime.
1100
1101If there are multiple declarations of the same entity, the availability
1102attributes must either match on a per-platform basis or later
1103declarations must not have availability attributes for that
1104platform. For example:
1105
1106```c
1107void g(void) __attribute__((availability(macos,introduced=10.4)));
1108void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches
1109void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
1110void g(void); // okay, inherits both macos and ios availability from above.
1111void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch
1112```
1113
1114When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
1115
1116```objc
1117@interface A
1118- (id)method __attribute__((availability(macos,introduced=10.4)));
1119- (id)method2 __attribute__((availability(macos,introduced=10.4)));
1120@end
1121
1122@interface B : A
1123- (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later
1124- (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4
1125@end
1126```
1127
1128Starting with the macOS 10.12 SDK, the `API_AVAILABLE` macro from
1129`<os/availability.h>` can simplify the spelling:
1130
1131```objc
1132@interface A
1133- (id)method API_AVAILABLE(macos(10.11)));
1134- (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0));
1135@end
1136```
1137
1138Availability attributes can also be applied using a `#pragma clang attribute`.
1139Any explicit availability attribute whose platform corresponds to the target
1140platform is applied to a declaration regardless of the availability attributes
1141specified in the pragma. For example, in the code below,
1142`hasExplicitAvailabilityAttribute` will use the `macOS` availability
1143attribute that is specified with the declaration, whereas
1144`getsThePragmaAvailabilityAttribute` will use the `macOS` availability
1145attribute that is applied by the pragma.
1146
1147```c
1148#pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function)
1149void getsThePragmaAvailabilityAttribute(void);
1150void hasExplicitAvailabilityAttribute(void) __attribute__((availability(macos,introduced=10.4)));
1151#pragma clang attribute pop
1152```
1153
1154For platforms like `watchOS` and `tvOS`, whose availability attributes can
1155be implicitly inferred from an `iOS` availability attribute, the logic is
1156slightly more complex. The explicit and the pragma-applied availability
1157attributes whose platform corresponds to the target platform are applied as
1158described in the previous paragraph. However, the implicitly inferred attributes
1159are applied to a declaration only when there is no explicit or pragma-applied
1160availability attribute whose platform corresponds to the target platform. For
1161example, the function below will receive the `tvOS` availability from the
1162pragma rather than using the inferred `iOS` availability from the declaration:
1163
1164```c
1165#pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function)
1166void getsThePragmaTVOSAvailabilityAttribute(void) __attribute__((availability(iOS,introduced=11.0)));
1167#pragma clang attribute pop
1168```
1169
1170The compiler is also able to apply implicitly inferred attributes from a pragma
1171as well. For example, when targeting `tvOS`, the function below will receive
1172a `tvOS` availability attribute that is implicitly inferred from the `iOS`
1173availability attribute applied by the pragma:
1174
1175```c
1176#pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function)
1177void infersTVOSAvailabilityFromPragma(void);
1178#pragma clang attribute pop
1179```
1180
1181The implicit attributes that are inferred from explicitly specified attributes
1182whose platform corresponds to the target platform are applied to the declaration
1183even if there is an availability attribute that can be inferred from a pragma.
1184For example, the function below will receive the `tvOS, introduced=11.0`
1185availability that is inferred from the attribute on the declaration rather than
1186inferring availability from the pragma:
1187
1188```c
1189#pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function)
1190void infersTVOSAvailabilityFromAttributeNextToDeclaration(void)
1191 __attribute__((availability(iOS,introduced=11.0)));
1192#pragma clang attribute pop
1193```
1194
1195Also see the documentation for
1196{ref}`@available <langext-objective-c-available>`)reST";
1197
1198static const char AttrDoc_AvailableOnlyInDefaultEvalMethod[] = R"reST(No documentation.)reST";
1199
1200static const char AttrDoc_BPFFastCall[] = R"reST(Functions annotated with this attribute are likely to be inlined by BPF JIT.
1201It is assumed that inlined implementation uses less caller saved registers,
1202than a regular function.
1203Specifically, the following registers are likely to be preserved:
1204- `R0` if function return value is `void`;
1205- `R2-R5` if function takes 1 argument;
1206- `R3-R5` if function takes 2 arguments;
1207- `R4-R5` if function takes 3 arguments;
1208- `R5` if function takes 4 arguments;
1209
1210For such functions Clang generates code pattern that allows BPF JIT
1211to recognize and remove unnecessary spills and fills of the preserved
1212registers.)reST";
1213
1214static const char AttrDoc_BPFPreserveAccessIndex[] = R"reST(Clang supports the `__attribute__((preserve_access_index))`
1215attribute for the BPF target. This attribute may be attached to a
1216struct or union declaration, where if -g is specified, it enables
1217preserving struct or union member access debuginfo indices of this
1218struct or union, similar to clang `__builtin_preserve_access_index()`.
1219
1220The attribute may also be attached to a named enum, or an anonymous enum with
1221a typedef name. A use of its enumerator is then treated like
1222`__builtin_preserve_enum_value(*(enum_type *)enumerator, BPF_ENUMVAL_VALUE)`,
1223so it is not a constant expression, and if -g is specified, its value is
1224relocated. An enum defined in a struct or union with the attribute does not
1225get the attribute.
1226
1227Where a constant is required, e.g., in an array bound, a case label, an array
1228designator, the initializer of a global, static local or constexpr variable or
1229an `"i"` operand of inline asm, the enumerator is not relocated and its value in
1230the local enum is used. This is diagnosed by `-Wbpf-enum-not-relocated`, an
1231error by default; `-Wno-error=` or `#pragma clang diagnostic` allows such a use.
1232
1233The macro `__BPF_FEATURE_ENUM_PRESERVE_ACCESS_INDEX` is defined if the
1234attribute is supported on enum declarations.)reST";
1235
1236static const char AttrDoc_BPFPreserveStaticOffset[] = R"reST(Clang supports the `__attribute__((preserve_static_offset))`
1237attribute for the BPF target. This attribute may be attached to a
1238struct or union declaration. Reading or writing fields of types having
1239such annotation is guaranteed to generate LDX/ST/STX instruction with
1240offset corresponding to the field.
1241
1242For example:
1243
1244```c
1245struct foo {
1246 int a;
1247 int b;
1248};
1249
1250struct bar {
1251 int a;
1252 struct foo b;
1253} __attribute__((preserve_static_offset));
1254
1255void buz(struct bar *g) {
1256 g->b.a = 42;
1257}
1258```
1259
1260The assignment to `g`'s field would produce an ST instruction with
1261offset 8: `*(u32)(r1 + 8) = 42;`.
1262
1263Without this attribute generated instructions might be different,
1264depending on optimizations behavior. E.g. the example above could be
1265rewritten as `r1 += 8; *(u32)(r1 + 0) = 42;`.)reST";
1266
1267static const char AttrDoc_BTFDeclTag[] = R"reST(Clang supports the `__attribute__((btf_decl_tag("ARGUMENT")))` attribute for
1268all targets. This attribute may be attached to a struct/union, struct/union
1269field, function, function parameter, variable or typedef declaration. If -g is
1270specified, the `ARGUMENT` info will be preserved in IR and be emitted to
1271dwarf. For BPF targets, the `ARGUMENT` info will be emitted to .BTF ELF
1272section too.)reST";
1273
1274static const char AttrDoc_BTFTypeTag[] = R"reST(Clang supports the `__attribute__((btf_type_tag("ARGUMENT")))` attribute for
1275all targets. It only has effect when `-g` is specified on the command line.
1276
1277The attribute can be applied to a pointer type, in which case the tag is
1278associated with the pointee type, e.g.:
1279
1280```c
1281int __attribute__((btf_type_tag("tag"))) *p;
1282```
1283
1284It can also be applied to the underlying type of a typedef, in which case the
1285tag follows the typedef down to its base type, e.g.:
1286
1287```c
1288typedef struct foo __attribute__((btf_type_tag("tag"))) foo_t;
1289```
1290
1291The following is the corresponding btf:
1292
1293```
1294...
1295[2] TYPE_TAG 'tag' type_id=4
1296[3] TYPEDEF 'foo_t' type_id=2
1297[4] STRUCT 'foo' size=4 vlen=1
1298 'c' type_id=5 bits_offset=0
1299[5] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
1300...
1301```
1302
1303The attribute is currently silently ignored in any other position (note: this
1304scenario may be diagnosed in the future).
1305
1306The `ARGUMENT` string will be preserved in IR and emitted to DWARF for the
1307types used in variable declarations, function declarations, or typedef
1308declarations.
1309
1310For BPF targets, the `ARGUMENT` string will also be emitted to .BTF ELF
1311section.)reST";
1312
1313static const char AttrDoc_Blocking[] = R"reST(Declares that a function potentially blocks, and prevents any potential inference of `nonblocking`
1314by the compiler.)reST";
1315
1316static const char AttrDoc_Blocks[] = R"reST(No documentation.)reST";
1317
1318static const char AttrDoc_Builtin[] = R"reST()reST";
1319
1320static const char AttrDoc_BuiltinAlias[] = R"reST(This attribute is used in the implementation of the C intrinsics.
1321It allows the C intrinsic functions to be declared using the names defined
1322in target builtins, and still be recognized as clang builtins equivalent to the
1323underlying name. For example, `riscv_vector.h` declares the function `vadd`
1324with `__attribute__((clang_builtin_alias(__builtin_rvv_vadd_vv_i8m1)))`.
1325This ensures that both functions are recognized as that clang builtin,
1326and in the latter case, the choice of which builtin to identify the
1327function as can be deferred until after overload resolution.
1328
1329This attribute can only be used to set up the aliases for certain ARM/RISC-V
1330C intrinsic functions; it is intended for use only inside `arm_*.h` and
1331`riscv_*.h` and is not a general mechanism for declaring arbitrary aliases
1332for clang builtin functions.)reST";
1333
1334static const char AttrDoc_C11NoReturn[] = R"reST(A function declared as `_Noreturn` shall not return to its caller. The
1335compiler will generate a diagnostic for a function declared as `_Noreturn`
1336that appears to be capable of returning to its caller. Despite being a type
1337specifier, the `_Noreturn` attribute cannot be specified on a function
1338pointer type.)reST";
1339
1340static const char AttrDoc_CDecl[] = R"reST(No documentation.)reST";
1341
1342static const char AttrDoc_CFAuditedTransfer[] = R"reST(No documentation.)reST";
1343
1344static const char AttrDoc_CFConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1345(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1346convention (e.g. functions starting with "get" are assumed to return at
1347`+0`).
1348
1349It can be overridden using a family of the following attributes. In
1350Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
1351a function communicates that the object is returned at `+1`, and the caller
1352is responsible for freeing it.
1353Similarly, the annotation `__attribute__((ns_returns_not_retained))`
1354specifies that the object is returned at `+0` and the ownership remains with
1355the callee.
1356The annotation `__attribute__((ns_consumes_self))` specifies that
1357the Objective-C method call consumes the reference to `self`, e.g. by
1358attaching it to a supplied parameter.
1359Additionally, parameters can have an annotation
1360`__attribute__((ns_consumed))`, which specifies that passing an owned object
1361as that parameter effectively transfers the ownership, and the caller is no
1362longer responsible for it.
1363These attributes affect code generation when interacting with ARC code, and
1364they are used by the Clang Static Analyzer.
1365
1366In C programs using CoreFoundation, a similar set of attributes:
1367`__attribute__((cf_returns_not_retained))`,
1368`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
1369have the same respective semantics when applied to CoreFoundation objects.
1370These attributes affect code generation when interacting with ARC code, and
1371they are used by the Clang Static Analyzer.
1372
1373(os-retained-attr-family)=
1374
1375Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1376the same attribute family is present:
1377`__attribute__((os_returns_not_retained))`,
1378`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
1379with the same respective semantics.
1380Similar to `__attribute__((ns_consumes_self))`,
1381`__attribute__((os_consumes_this))` specifies that the method call consumes
1382the reference to "this" (e.g., when attaching it to a different object supplied
1383as a parameter).
1384Out parameters (parameters the function is meant to write into,
1385either via pointers-to-pointers or references-to-pointers)
1386may be annotated with `__attribute__((os_returns_retained))`
1387or `__attribute__((os_returns_not_retained))` which specifies that the object
1388written into the out parameter should (or respectively should not) be released
1389after use.
1390Since often out parameters may or may not be written depending on the exit
1391code of the function,
1392annotations `__attribute__((os_returns_retained_on_zero))`
1393and `__attribute__((os_returns_retained_on_non_zero))` specify that
1394an out parameter at `+1` is written if and only if the function returns a zero
1395(respectively non-zero) error code.
1396Observe that return-code-dependent out parameter annotations are only
1397available for retained out parameters, as non-retained object do not have to be
1398released by the callee.
1399These attributes are only used by the Clang Static Analyzer.
1400
1401The family of attributes `X_returns_X_retained` can be added to functions,
1402C++ methods, and Objective-C methods and properties.
1403Attributes `X_consumed` can be added to parameters of methods, functions,
1404and Objective-C methods.)reST";
1405
1406static const char AttrDoc_CFGuard[] = R"reST(Code can indicate CFG checks are not wanted with the `__declspec(guard(nocf))`
1407attribute. This directs the compiler to not insert any CFG checks for the entire
1408function. This approach is typically used only sparingly in specific situations
1409where the programmer has manually inserted "CFG-equivalent" protection. The
1410programmer knows that they are calling through some read-only function table
1411whose address is obtained through read-only memory references and for which the
1412index is masked to the function table limit. This approach may also be applied
1413to small wrapper functions that are not inlined and that do nothing more than
1414make a call through a function pointer. Since incorrect usage of this directive
1415can compromise the security of CFG, the programmer must be very careful using
1416the directive. Typically, this usage is limited to very small functions that
1417only call one function.
1418
1419Control Flow Guard documentation is available here:
1420<https://docs.microsoft.com/en-us/windows/win32/secbp/pe-metadata>)reST";
1421
1422static const char AttrDoc_CFICanonicalJumpTable[] = R"reST(Use `__attribute__((cfi_canonical_jump_table))` on a function declaration to
1423make the function's CFI jump table canonical. See {ref}`the CFI documentation
1424<cfi-canonical-jump-tables>` for more details.)reST";
1425
1426static const char AttrDoc_CFISalt[] = R"reST(The `cfi_salt` attribute specifies a string literal that is used as a salt
1427for Control-Flow Integrity (CFI) checks to distinguish between functions with
1428the same type signature. This attribute can be applied to function declarations,
1429function definitions, and function pointer typedefs.
1430
1431The attribute prevents function pointers from being replaced with pointers to
1432functions that have a compatible type, which can be a CFI bypass vector.
1433
1434**Syntax:**
1435
1436- GNU-style: `__attribute__((cfi_salt("<salt_string>")))`
1437- C++11-style: `[[clang::cfi_salt("<salt_string>")]]`
1438
1439**Usage:**
1440
1441The attribute takes a single string literal argument that serves as the salt.
1442Functions or function types with different salt values will have different CFI
1443hashes, even if they have identical type signatures.
1444
1445**Motivation:**
1446
1447In large codebases like the Linux kernel, there are often hundreds of functions
1448with identical type signatures that are called indirectly:
1449
1450```
14511662 functions with void (*)(void)
14521179 functions with int (*)(void)
1453 ...
1454```
1455
1456By salting the CFI hashes, you can make CFI more robust by ensuring that
1457functions intended for different purposes have distinct CFI identities.
1458
1459**Type Compatibility:**
1460
1461- Functions with different salt values are considered to have incompatible types
1462- Function pointers with different salt values cannot be assigned to each other
1463- All declarations of the same function must use the same salt value
1464
1465**Example:**
1466
1467```c
1468// Header file - define convenience macros
1469#define __cfi_salt(s) __attribute__((cfi_salt(s)))
1470
1471// Typedef for regular function pointers
1472typedef int (*fptr_t)(void);
1473
1474// Typedef for salted function pointers
1475typedef int (*fptr_salted_t)(void) __cfi_salt("pepper");
1476
1477struct widget_ops {
1478 fptr_t init; // Regular CFI
1479 fptr_salted_t exec; // Salted CFI
1480 fptr_t cleanup; // Regular CFI
1481};
1482
1483// Function implementations
1484static int widget_init(void) { return 0; }
1485static int widget_exec(void) __cfi_salt("pepper") { return 1; }
1486static int widget_cleanup(void) { return 0; }
1487
1488static struct widget_ops ops = {
1489 .init = widget_init, // OK - compatible types
1490 .exec = widget_exec, // OK - both use "pepper" salt
1491 .cleanup = widget_cleanup // OK - compatible types
1492};
1493
1494// Using C++11 attribute syntax
1495void secure_callback(void) [[clang::cfi_salt("secure")]];
1496
1497// This would cause a compilation error:
1498// fptr_t bad_ptr = widget_exec; // Error: incompatible types
1499```
1500
1501**Notes:**
1502
1503- The salt string can contain non-NULL ASCII characters, including spaces and
1504 quotes
1505- This attribute only applies to function types; using it on non-function
1506 types will generate a warning
1507- All declarations and definitions of the same function must use identical
1508 salt values
1509- The attribute affects type compatibility during compilation and CFI hash
1510 generation during code generation)reST";
1511
1512static const char AttrDoc_CFIUncheckedCallee[] = R"reST(`cfi_unchecked_callee` is a function type attribute which prevents the
1513compiler from instrumenting
1514{doc}`Control Flow Integrity <ControlFlowIntegrity>` checks on indirect
1515function calls. This also includes control flow checks added by
1516`-fsanitize=function`; see {ref}`Available checks <ubsan-checks>`.
1517Specifically, the attribute has the following semantics:
1518
15191. Indirect calls to a function type with this attribute will not be instrumented with CFI. That is,
1520 the indirect call will not be checked. Note that this only changes the behavior for indirect calls
1521 on pointers to function types having this attribute. It does not prevent all indirect function calls
1522 for a given type from being checked.
15232. All direct references to a function whose type has this attribute will always reference the
1524 function definition rather than an entry in the CFI jump table.
15253. When a pointer to a function with this attribute is implicitly cast to a pointer to a function
1526 without this attribute, the compiler will give a warning saying this attribute is discarded. This
1527 warning can be silenced with an explicit cast. Note an explicit cast just disables the warning, so
1528 direct references to a function with a `cfi_unchecked_callee` attribute will still reference the
1529 function definition rather than the CFI jump table.
1530
1531```c
1532#define CFI_UNCHECKED_CALLEE __attribute__((cfi_unchecked_callee))
1533
1534void no_cfi() CFI_UNCHECKED_CALLEE {}
1535
1536void (*with_cfi)() = no_cfi; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1537 // `with_cfi` also points to the actual definition of `no_cfi` rather than
1538 // its jump table entry.
1539
1540void invoke(void (CFI_UNCHECKED_CALLEE *func)()) {
1541 func(); // CFI will not instrument this indirect call.
1542
1543 void (*func2)() = func; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1544
1545 func2(); // CFI will instrument this indirect call. Users should be careful however because if this
1546 // references a function with type `cfi_unchecked_callee`, then the CFI check may incorrectly
1547 // fail because the reference will be to the function definition rather than the CFI jump
1548 // table entry.
1549}
1550```
1551
1552This attribute can only be applied on functions or member functions. This attribute can be a good
1553alternative to `no_sanitize("cfi")` if you only want to disable innstrumentation for specific indirect
1554calls rather than applying `no_sanitize("cfi")` on the whole function containing indirect call. Note
1555that `cfi_unchecked_attribute` is a type attribute doesn't disable CFI instrumentation on a function
1556body.)reST";
1557
1558static const char AttrDoc_CFReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1559(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1560convention (e.g. functions starting with "get" are assumed to return at
1561`+0`).
1562
1563It can be overridden using a family of the following attributes. In
1564Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
1565a function communicates that the object is returned at `+1`, and the caller
1566is responsible for freeing it.
1567Similarly, the annotation `__attribute__((ns_returns_not_retained))`
1568specifies that the object is returned at `+0` and the ownership remains with
1569the callee.
1570The annotation `__attribute__((ns_consumes_self))` specifies that
1571the Objective-C method call consumes the reference to `self`, e.g. by
1572attaching it to a supplied parameter.
1573Additionally, parameters can have an annotation
1574`__attribute__((ns_consumed))`, which specifies that passing an owned object
1575as that parameter effectively transfers the ownership, and the caller is no
1576longer responsible for it.
1577These attributes affect code generation when interacting with ARC code, and
1578they are used by the Clang Static Analyzer.
1579
1580In C programs using CoreFoundation, a similar set of attributes:
1581`__attribute__((cf_returns_not_retained))`,
1582`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
1583have the same respective semantics when applied to CoreFoundation objects.
1584These attributes affect code generation when interacting with ARC code, and
1585they are used by the Clang Static Analyzer.
1586
1587(os-retained-attr-family)=
1588
1589Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1590the same attribute family is present:
1591`__attribute__((os_returns_not_retained))`,
1592`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
1593with the same respective semantics.
1594Similar to `__attribute__((ns_consumes_self))`,
1595`__attribute__((os_consumes_this))` specifies that the method call consumes
1596the reference to "this" (e.g., when attaching it to a different object supplied
1597as a parameter).
1598Out parameters (parameters the function is meant to write into,
1599either via pointers-to-pointers or references-to-pointers)
1600may be annotated with `__attribute__((os_returns_retained))`
1601or `__attribute__((os_returns_not_retained))` which specifies that the object
1602written into the out parameter should (or respectively should not) be released
1603after use.
1604Since often out parameters may or may not be written depending on the exit
1605code of the function,
1606annotations `__attribute__((os_returns_retained_on_zero))`
1607and `__attribute__((os_returns_retained_on_non_zero))` specify that
1608an out parameter at `+1` is written if and only if the function returns a zero
1609(respectively non-zero) error code.
1610Observe that return-code-dependent out parameter annotations are only
1611available for retained out parameters, as non-retained object do not have to be
1612released by the callee.
1613These attributes are only used by the Clang Static Analyzer.
1614
1615The family of attributes `X_returns_X_retained` can be added to functions,
1616C++ methods, and Objective-C methods and properties.
1617Attributes `X_consumed` can be added to parameters of methods, functions,
1618and Objective-C methods.)reST";
1619
1620static const char AttrDoc_CFReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1621(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1622convention (e.g. functions starting with "get" are assumed to return at
1623`+0`).
1624
1625It can be overridden using a family of the following attributes. In
1626Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
1627a function communicates that the object is returned at `+1`, and the caller
1628is responsible for freeing it.
1629Similarly, the annotation `__attribute__((ns_returns_not_retained))`
1630specifies that the object is returned at `+0` and the ownership remains with
1631the callee.
1632The annotation `__attribute__((ns_consumes_self))` specifies that
1633the Objective-C method call consumes the reference to `self`, e.g. by
1634attaching it to a supplied parameter.
1635Additionally, parameters can have an annotation
1636`__attribute__((ns_consumed))`, which specifies that passing an owned object
1637as that parameter effectively transfers the ownership, and the caller is no
1638longer responsible for it.
1639These attributes affect code generation when interacting with ARC code, and
1640they are used by the Clang Static Analyzer.
1641
1642In C programs using CoreFoundation, a similar set of attributes:
1643`__attribute__((cf_returns_not_retained))`,
1644`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
1645have the same respective semantics when applied to CoreFoundation objects.
1646These attributes affect code generation when interacting with ARC code, and
1647they are used by the Clang Static Analyzer.
1648
1649(os-retained-attr-family)=
1650
1651Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1652the same attribute family is present:
1653`__attribute__((os_returns_not_retained))`,
1654`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
1655with the same respective semantics.
1656Similar to `__attribute__((ns_consumes_self))`,
1657`__attribute__((os_consumes_this))` specifies that the method call consumes
1658the reference to "this" (e.g., when attaching it to a different object supplied
1659as a parameter).
1660Out parameters (parameters the function is meant to write into,
1661either via pointers-to-pointers or references-to-pointers)
1662may be annotated with `__attribute__((os_returns_retained))`
1663or `__attribute__((os_returns_not_retained))` which specifies that the object
1664written into the out parameter should (or respectively should not) be released
1665after use.
1666Since often out parameters may or may not be written depending on the exit
1667code of the function,
1668annotations `__attribute__((os_returns_retained_on_zero))`
1669and `__attribute__((os_returns_retained_on_non_zero))` specify that
1670an out parameter at `+1` is written if and only if the function returns a zero
1671(respectively non-zero) error code.
1672Observe that return-code-dependent out parameter annotations are only
1673available for retained out parameters, as non-retained object do not have to be
1674released by the callee.
1675These attributes are only used by the Clang Static Analyzer.
1676
1677The family of attributes `X_returns_X_retained` can be added to functions,
1678C++ methods, and Objective-C methods and properties.
1679Attributes `X_consumed` can be added to parameters of methods, functions,
1680and Objective-C methods.)reST";
1681
1682static const char AttrDoc_CFUnknownTransfer[] = R"reST(No documentation.)reST";
1683
1684static const char AttrDoc_CPUDispatch[] = R"reST(The `cpu_specific` and `cpu_dispatch` attributes are used to define and
1685resolve multiversioned functions. This form of multiversioning provides a
1686mechanism for declaring versions across translation units and manually
1687specifying the resolved function list. A specified CPU defines a set of minimum
1688features that are required for the function to be called. The result of this is
1689that future processors execute the most restrictive version of the function the
1690new processor can execute.
1691
1692In addition, unlike the ICC implementation of this feature, the selection of the
1693version does not consider the manufacturer or microarchitecture of the processor.
1694It tests solely the list of features that are both supported by the specified
1695processor and present in the compiler-rt library. This can be surprising at times,
1696as the runtime processor may be from a completely different manufacturer, as long
1697as it supports the same feature set.
1698
1699This can additionally be surprising, as some processors are indistringuishable from
1700others based on the list of testable features. When this happens, the variant
1701is selected in an unspecified manner.
1702
1703Function versions are defined with `cpu_specific`, which takes one or more CPU
1704names as a parameter. For example:
1705
1706```c
1707// Declares and defines the ivybridge version of single_cpu.
1708__attribute__((cpu_specific(ivybridge)))
1709void single_cpu(void){}
1710
1711// Declares and defines the atom version of single_cpu.
1712__attribute__((cpu_specific(atom)))
1713void single_cpu(void){}
1714
1715// Declares and defines both the ivybridge and atom version of multi_cpu.
1716__attribute__((cpu_specific(ivybridge, atom)))
1717void multi_cpu(void){}
1718```
1719
1720A dispatching (or resolving) function can be declared anywhere in a project's
1721source code with `cpu_dispatch`. This attribute takes one or more CPU names
1722as a parameter (like `cpu_specific`). Functions marked with `cpu_dispatch`
1723are not expected to be defined, only declared. If such a marked function has a
1724definition, any side effects of the function are ignored; trivial function
1725bodies are permissible for ICC compatibility.
1726
1727```c
1728// Creates a resolver for single_cpu above.
1729__attribute__((cpu_dispatch(ivybridge, atom)))
1730void single_cpu(void){}
1731
1732// Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1733// translation unit.
1734__attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1735void multi_cpu(void){}
1736```
1737
1738Note that it is possible to have a resolving function that dispatches based on
1739more or fewer options than are present in the program. Specifying fewer will
1740result in the omitted options not being considered during resolution. Specifying
1741a version for resolution that isn't defined in the program will result in a
1742linking failure.
1743
1744It is also possible to specify a CPU name of `generic` which will be resolved
1745if the executing processor doesn't satisfy the features required in the CPU
1746name. The behavior of a program executing on a processor that doesn't satisfy
1747any option of a multiversioned function is undefined.)reST";
1748
1749static const char AttrDoc_CPUSpecific[] = R"reST(The `cpu_specific` and `cpu_dispatch` attributes are used to define and
1750resolve multiversioned functions. This form of multiversioning provides a
1751mechanism for declaring versions across translation units and manually
1752specifying the resolved function list. A specified CPU defines a set of minimum
1753features that are required for the function to be called. The result of this is
1754that future processors execute the most restrictive version of the function the
1755new processor can execute.
1756
1757In addition, unlike the ICC implementation of this feature, the selection of the
1758version does not consider the manufacturer or microarchitecture of the processor.
1759It tests solely the list of features that are both supported by the specified
1760processor and present in the compiler-rt library. This can be surprising at times,
1761as the runtime processor may be from a completely different manufacturer, as long
1762as it supports the same feature set.
1763
1764This can additionally be surprising, as some processors are indistringuishable from
1765others based on the list of testable features. When this happens, the variant
1766is selected in an unspecified manner.
1767
1768Function versions are defined with `cpu_specific`, which takes one or more CPU
1769names as a parameter. For example:
1770
1771```c
1772// Declares and defines the ivybridge version of single_cpu.
1773__attribute__((cpu_specific(ivybridge)))
1774void single_cpu(void){}
1775
1776// Declares and defines the atom version of single_cpu.
1777__attribute__((cpu_specific(atom)))
1778void single_cpu(void){}
1779
1780// Declares and defines both the ivybridge and atom version of multi_cpu.
1781__attribute__((cpu_specific(ivybridge, atom)))
1782void multi_cpu(void){}
1783```
1784
1785A dispatching (or resolving) function can be declared anywhere in a project's
1786source code with `cpu_dispatch`. This attribute takes one or more CPU names
1787as a parameter (like `cpu_specific`). Functions marked with `cpu_dispatch`
1788are not expected to be defined, only declared. If such a marked function has a
1789definition, any side effects of the function are ignored; trivial function
1790bodies are permissible for ICC compatibility.
1791
1792```c
1793// Creates a resolver for single_cpu above.
1794__attribute__((cpu_dispatch(ivybridge, atom)))
1795void single_cpu(void){}
1796
1797// Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1798// translation unit.
1799__attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1800void multi_cpu(void){}
1801```
1802
1803Note that it is possible to have a resolving function that dispatches based on
1804more or fewer options than are present in the program. Specifying fewer will
1805result in the omitted options not being considered during resolution. Specifying
1806a version for resolution that isn't defined in the program will result in a
1807linking failure.
1808
1809It is also possible to specify a CPU name of `generic` which will be resolved
1810if the executing processor doesn't satisfy the features required in the CPU
1811name. The behavior of a program executing on a processor that doesn't satisfy
1812any option of a multiversioned function is undefined.)reST";
1813
1814static const char AttrDoc_CUDAClusterDims[] = R"reST(In CUDA/HIP programming, the `cluster_dims` attribute, conventionally exposed as the
1815`__cluster_dims__` macro, can be applied to a kernel function to set the dimensions of a
1816thread block cluster, which is an optional level of hierarchy and made up of thread blocks.
1817`__cluster_dims__` defines the cluster size as `(X, Y, Z)`, where each value is the number
1818of thread blocks in that dimension. The `cluster_dims` and `no_cluster` attributes are
1819mutually exclusive.
1820
1821```
1822__global__ __cluster_dims__(2, 1, 1) void kernel(...) {
1823 ...
1824}
1825```)reST";
1826
1827static const char AttrDoc_CUDAConstant[] = R"reST(No documentation.)reST";
1828
1829static const char AttrDoc_CUDADevice[] = R"reST(No documentation.)reST";
1830
1831static const char AttrDoc_CUDADeviceBuiltinSurfaceType[] = R"reST(The `device_builtin_surface_type` attribute can be applied to a class
1832template when declaring the surface reference. A surface reference variable
1833could be accessed on the host side and, on the device side, might be translated
1834into an internal surface object, which is established through surface bind and
1835unbind runtime APIs.)reST";
1836
1837static const char AttrDoc_CUDADeviceBuiltinTextureType[] = R"reST(The `device_builtin_texture_type` attribute can be applied to a class
1838template when declaring the texture reference. A texture reference variable
1839could be accessed on the host side and, on the device side, might be translated
1840into an internal texture object, which is established through texture bind and
1841unbind runtime APIs.)reST";
1842
1843static const char AttrDoc_CUDAGlobal[] = R"reST(No documentation.)reST";
1844
1845static const char AttrDoc_CUDAGridConstant[] = R"reST(The `__grid_constant__` attribute can be applied to a `const`-qualified kernel
1846function argument and allows compiler to take the address of that argument without
1847making a copy. The argument applies to sm_70 or newer GPUs, during compilation
1848with CUDA-11.7(PTX 7.7) or newer, and is ignored otherwise.)reST";
1849
1850static const char AttrDoc_CUDAHost[] = R"reST(No documentation.)reST";
1851
1852static const char AttrDoc_CUDAInvalidTarget[] = R"reST()reST";
1853
1854static const char AttrDoc_CUDALaunchBounds[] = R"reST(The `__launch_bounds__` attribute (also spelled `launch_bounds`) originates
1855in CUDA. It informs the compiler of the launch configuration a kernel will be
1856dispatched with, allowing it to optimize the kernel accordingly. It takes the
1857form `__launch_bounds__(<max-threads-per-block>[,
1858<min-blocks-per-multiprocessor>[, <max-blocks-per-cluster>]])`. All arguments
1859are constant expressions.
1860
1861The attribute only takes effect on `__global__` (kernel) functions; like
1862NVCC, Clang ignores it on any other function.
1863
1864`<max-threads-per-block>` specifies the maximum number of threads per block
1865the kernel will be launched with. `<min-blocks-per-multiprocessor>` specifies
1866the desired minimum number of blocks resident per multiprocessor, and
1867`<max-blocks-per-cluster>` the maximum number of blocks per cluster.
1868
1869For the NVPTX target, `<max-threads-per-block>` and
1870`<min-blocks-per-multiprocessor>` map to the `.maxntid` and `.minnctapersm`
1871PTX directives, respectively, and `<max-blocks-per-cluster>` (which requires
1872`sm_90` or newer) maps to `.maxclusterrank`.
1873
1874For the AMDGPU target, the attribute is translated into the equivalent AMDGPU
1875kernel attributes:
1876
1877 - `<max-threads-per-block>` sets the maximum
1878 `amdgpu_flat_work_group_size` (as `1, <max-threads-per-block>`).
1879 - `<min-blocks-per-multiprocessor>` sets the minimum
1880 `amdgpu_waves_per_eu`. Note that HIP reinterprets this CUDA argument as a
1881 minimum number of waves per execution unit, so its meaning differs from the
1882 NVPTX interpretation.
1883 - `<max-blocks-per-cluster>` is currently ignored.
1884
1885An explicit `amdgpu_flat_work_group_size` or `amdgpu_waves_per_eu` attribute
1886takes precedence over the value derived from `__launch_bounds__`.
1887
1888When the same kernel is declared multiple times, the launch bounds from the most
1889recent declaration that specifies them are used; a definition without
1890`__launch_bounds__` inherits the bounds from an earlier declaration.)reST";
1891
1892static const char AttrDoc_CUDANoCluster[] = R"reST(In CUDA/HIP programming, a kernel function can still be launched with the cluster feature enabled
1893at runtime, even without being annotated with `__cluster_dims__`. The LLVM/Clang-exclusive
1894`no_cluster` attribute, conventionally exposed as the `__no_cluster__` macro, can be applied to
1895a kernel function to explicitly indicate that the cluster feature will not be enabled either at
1896compile time or at kernel launch time. This allows the compiler to apply certain optimizations
1897without assuming that clustering could be enabled at runtime. It is undefined behavior to launch a
1898kernel annotated with `__no_cluster__` if the cluster feature is enabled at runtime.
1899The `cluster_dims` and `no_cluster` attributes are mutually exclusive.
1900
1901```
1902__global__ __no_cluster__ void kernel(...) {
1903 ...
1904}
1905```)reST";
1906
1907static const char AttrDoc_CUDAShared[] = R"reST(No documentation.)reST";
1908
1909static const char AttrDoc_CXX11NoReturn[] = R"reST(A function declared as `[[noreturn]]` shall not return to its caller. The
1910compiler will generate a diagnostic for a function declared as `[[noreturn]]`
1911that appears to be capable of returning to its caller.
1912
1913The `[[_Noreturn]]` spelling is deprecated and only exists to ease code
1914migration for code using `[[noreturn]]` after including `<stdnoreturn.h>`.)reST";
1915
1916static const char AttrDoc_CXXAssume[] = R"reST(The `assume` attribute is used to indicate to the optimizer that a
1917certain condition is assumed to be true at a certain point in the
1918program. If this condition is violated at runtime, the behavior is
1919undefined. `assume` can only be applied to a null statement.
1920
1921Different optimisers are likely to react differently to the presence of
1922this attribute; in some cases, adding `assume` may affect performance
1923negatively. It should be used with parsimony and care.
1924
1925Example:
1926
1927```c++
1928int f(int x, int y) {
1929 [[assume(x == 27)]];
1930 [[assume(x == y)]];
1931 return y + 1; // May be optimised to `return 28`.
1932}
1933```)reST";
1934
1935static const char AttrDoc_CallableWhen[] = R"reST(Use `__attribute__((callable_when(...)))` to indicate what states a method
1936may be called in. Valid states are unconsumed, consumed, or unknown. Each
1937argument to this attribute must be a quoted string. E.g.:
1938
1939`__attribute__((callable_when("unconsumed", "unknown")))`)reST";
1940
1941static const char AttrDoc_Callback[] = R"reST(The `callback` attribute specifies that the annotated function may invoke the
1942specified callback zero or more times. The callback, as well as the passed
1943arguments, are identified by their parameter name or position (starting with
19441!) in the annotated function. The first position in the attribute identifies
1945the callback callee, the following positions declare describe its arguments.
1946The callback callee is required to be callable with the number, and order, of
1947the specified arguments. The index `0`, or the identifier `this`, is used to
1948represent an implicit "this" pointer in class methods. If there is no implicit
1949"this" pointer it shall not be referenced. The index `-1`, or the name `__`,
1950represents an unknown callback callee argument. This can be a value which is
1951not present in the declared parameter list, or one that is, but is potentially
1952inspected, captured, or modified. Parameter names and indices can be mixed in
1953the callback attribute.
1954
1955The `callback` attribute, which is directly translated to `callback`
1956metadata (<http://llvm.org/docs/LangRef.html#callback-metadata>), make the
1957connection between the call to the annotated function and the callback callee.
1958This can enable interprocedural optimizations which were otherwise impossible.
1959If a function parameter is mentioned in the `callback` attribute, through its
1960position, it is undefined if that parameter is used for anything other than the
1961actual callback. Inspected, captured, or modified parameters shall not be
1962listed in the `callback` metadata.
1963
1964Example encodings for the callback performed by `pthread_create` are shown
1965below. The explicit attribute annotation indicates that the third parameter
1966(`start_routine`) is called zero or more times by the `pthread_create` function,
1967and that the fourth parameter (`arg`) is passed along. Note that the callback
1968behavior of `pthread_create` is automatically recognized by Clang. In addition,
1969the declarations of `__kmpc_fork_teams` and `__kmpc_fork_call`, generated for
1970`#pragma omp target teams` and `#pragma omp parallel`, respectively, are also
1971automatically recognized as broker functions. Further functions might be added
1972in the future.
1973
1974```c
1975__attribute__((callback (start_routine, arg)))
1976int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1977 void *(*start_routine) (void *), void *arg);
1978
1979__attribute__((callback (3, 4)))
1980int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1981 void *(*start_routine) (void *), void *arg);
1982```)reST";
1983
1984static const char AttrDoc_CalledOnce[] = R"reST(The `called_once` attribute specifies that the annotated function or method
1985parameter is invoked exactly once on all execution paths. It only applies
1986to parameters with function-like types, i.e. function pointers or blocks. This
1987concept is particularly useful for asynchronous programs.
1988
1989Clang implements a check for `called_once` parameters,
1990`-Wcalled-once-parameter`. It is on by default and finds the following
1991violations:
1992
1993- Parameter is not called at all.
1994- Parameter is called more than once.
1995- Parameter is not called on one of the execution paths.
1996
1997In the latter case, Clang pinpoints the path where parameter is not invoked
1998by showing the control-flow statement where the path diverges.
1999
2000```objc
2001void fooWithCallback(void (^callback)(void) __attribute__((called_once))) {
2002 if (somePredicate()) {
2003 ...
2004 callback();
2005 } else {
2006 callback(); // OK: callback is called on every path
2007 }
2008}
2009
2010void barWithCallback(void (^callback)(void) __attribute__((called_once))) {
2011 if (somePredicate()) {
2012 ...
2013 callback(); // note: previous call is here
2014 }
2015 callback(); // warning: callback is called twice
2016}
2017
2018void foobarWithCallback(void (^callback)(void) __attribute__((called_once))) {
2019 if (somePredicate()) { // warning: callback is not called when condition is false
2020 ...
2021 callback();
2022 }
2023}
2024```
2025
2026This attribute is useful for API developers who want to double-check if they
2027implemented their method correctly.)reST";
2028
2029static const char AttrDoc_Capability[] = R"reST(No documentation.)reST";
2030
2031static const char AttrDoc_CapturedRecord[] = R"reST()reST";
2032
2033static const char AttrDoc_Cleanup[] = R"reST(This attribute allows a function to be run when a local variable goes out of
2034scope. The attribute takes the identifier of a function with a parameter type
2035that is a pointer to the type with the attribute.
2036
2037```c
2038static void foo (int *) { ... }
2039static void bar (int *) { ... }
2040void baz (void) {
2041 int x __attribute__((cleanup(foo)));
2042 {
2043 int y __attribute__((cleanup(bar)));
2044 }
2045}
2046```
2047
2048The above example will result in a call to `bar` being passed the address of
2049`y` when `y` goes out of scope, then a call to `foo` being passed the
2050address of `x` when `x` goes out of scope. If two or more variables share
2051the same scope, their `cleanup` callbacks are invoked in the reverse order
2052the variables were declared in. It is not possible to check the return value
2053(if any) of these `cleanup` callback functions.)reST";
2054
2055static 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).
2056
2057```c
2058void __attribute__((clspv_libclc_builtin)) libclc_builtin() {}
2059```
2060
2061[clspv]: https://github.com/google/clspv
2062[libclc]: https://libclc.llvm.org)reST";
2063
2064static const char AttrDoc_CmseNSCall[] = R"reST(This attribute declares a non-secure function type. When compiling for secure
2065state, a call to such a function would switch from secure to non-secure state.
2066All non-secure function calls must happen only through a function pointer, and
2067a non-secure function type should only be used as a base type of a pointer.
2068See [ARMv8-M Security Extensions: Requirements on Development
2069Tools - Engineering Specification Documentation](https://developer.arm.com/docs/ecm0359818/latest/) for more information.)reST";
2070
2071static const char AttrDoc_CmseNSEntry[] = R"reST(This attribute declares a function that can be called from non-secure state, or
2072from secure state. Entering from and returning to non-secure state would switch
2073to and from secure state, respectively, and prevent flow of information
2074to non-secure state, except via return values. See [ARMv8-M Security Extensions:
2075Requirements on Development Tools - Engineering Specification Documentation](https://developer.arm.com/docs/ecm0359818/latest/) for more information.)reST";
2076
2077static const char AttrDoc_CodeAlign[] = R"reST(The `clang::code_align(N)` attribute applies to a loop and specifies the byte
2078alignment for a loop. The attribute accepts a positive integer constant
2079initialization expression indicating the number of bytes for the minimum
2080alignment boundary. Its value must be a power of 2, between 1 and 4096
2081(inclusive).
2082
2083```c++
2084void foo() {
2085 int var = 0;
2086 [[clang::code_align(16)]] for (int i = 0; i < 10; ++i) var++;
2087}
2088
2089void Array(int *array, size_t n) {
2090 [[clang::code_align(64)]] for (int i = 0; i < n; ++i) array[i] = 0;
2091}
2092
2093void count () {
2094 int a1[10], int i = 0;
2095 [[clang::code_align(32)]] while (i < 10) { a1[i] += 3; }
2096}
2097
2098void check() {
2099 int a = 10;
2100 [[clang::code_align(8)]] do {
2101 a = a + 1;
2102 } while (a < 20);
2103}
2104
2105template<int A>
2106void func() {
2107 [[clang::code_align(A)]] for(;;) { }
2108}
2109```)reST";
2110
2111static const char AttrDoc_CodeModel[] = R"reST(The `model` attribute allows overriding the translation unit's
2112code model (specified by `-mcmodel`) for a specific global variable.
2113
2114On LoongArch, allowed values are "normal", "medium", "extreme".
2115
2116On x86-64, allowed values are `"small"` and `"large"`. `"small"` is
2117roughly equivalent to `-mcmodel=small`, meaning the global is considered
2118"small" placed closer to the `.text` section relative to "large" globals, and
2119to prefer using 32-bit relocations to access the global. `"large"` is roughly
2120equivalent to `-mcmodel=large`, meaning the global is considered "large" and
2121placed further from the `.text` section relative to "small" globals, and
212264-bit relocations must be used to access the global.)reST";
2123
2124static const char AttrDoc_CodeSeg[] = R"reST(The `__declspec(code_seg)` attribute enables the placement of code into separate
2125named segments that can be paged or locked in memory individually. This attribute
2126is used to control the placement of instantiated templates and compiler-generated
2127code. See the documentation for [`__declspec(code_seg)`][__declspec(code_seg)] on MSDN.
2128
2129[__declspec(code_seg)]: http://msdn.microsoft.com/en-us/library/dn636922.aspx)reST";
2130
2131static const char AttrDoc_Cold[] = R"reST(`__attribute__((cold))` marks a function as cold, as a manual alternative to PGO hotness data.
2132If PGO data is available, the profile count based hotness overrides the `__attribute__((cold))` annotation (unlike `__attribute__((hot))`).)reST";
2133
2134static const char AttrDoc_Common[] = R"reST(No documentation.)reST";
2135
2136static const char AttrDoc_Const[] = R"reST(No documentation.)reST";
2137
2138static const char AttrDoc_ConstInit[] = R"reST(This attribute specifies that the variable to which it is attached is intended
2139to have a [*constant initializer*](http://en.cppreference.com/w/cpp/language/constant_initialization)
2140according to the rules of [basic.start.static]. The variable is required to
2141have static or thread storage duration. If the initialization of the variable
2142is not a constant initializer an error will be produced. This attribute may
2143only be used in C++; the `constinit` spelling is only accepted in C++20
2144onwards.
2145
2146Note that in C++03 strict constant expression checking is not done. Instead
2147the attribute reports if Clang can emit the variable as a constant, even if it's
2148not technically a *constant initializer*. This behavior is non-portable.
2149
2150Static storage duration variables with constant initializers avoid hard-to-find
2151bugs caused by the indeterminate order of dynamic initialization. They can also
2152be safely used during dynamic initialization across translation units.
2153
2154This attribute acts as a compile time assertion that the requirements
2155for constant initialization have been met. Since these requirements change
2156between dialects and have subtle pitfalls it's important to fail fast instead
2157of silently falling back on dynamic initialization.
2158
2159The first use of the attribute on a variable must be part of, or precede, the
2160initializing declaration of the variable. C++20 requires the `constinit`
2161spelling of the attribute to be present on the initializing declaration if it
2162is used anywhere. The other spellings can be specified on a forward declaration
2163and omitted on a later initializing declaration.
2164
2165```c++
2166// -std=c++14
2167#define SAFE_STATIC [[clang::require_constant_initialization]]
2168struct T {
2169 constexpr T(int) {}
2170 ~T(); // non-trivial
2171};
2172SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor.
2173SAFE_STATIC T y = 42; // error: variable does not have a constant initializer
2174// copy initialization is not a constant expression on a non-literal type.
2175```)reST";
2176
2177static const char AttrDoc_Constructor[] = R"reST(The `constructor` attribute causes the function to be called before entering
2178`main()`, and the `destructor` attribute causes the function to be called
2179after returning from `main()` or when the `exit()` function has been
2180called. Note, `quick_exit()`, `_Exit()`, and `abort()` prevent a function
2181marked `destructor` from being called.
2182
2183The constructor or destructor function should not accept any arguments and its
2184return type should be `void`.
2185
2186The attributes accept an optional argument used to specify the priority order
2187in which to execute constructor and destructor functions. The priority is
2188given as an integer constant expression between 101 and 65535 (inclusive).
2189Priorities outside of that range are reserved for use by the implementation. A
2190lower value indicates a higher priority of initialization. Note that only the
2191relative ordering of values is important. For example:
2192
2193```c++
2194__attribute__((constructor(200))) void foo(void);
2195__attribute__((constructor(101))) void bar(void);
2196```
2197
2198`bar()` will be called before `foo()`, and both will be called before
2199`main()`. If no argument is given to the `constructor` or `destructor`
2200attribute, they default to the value `65535`.)reST";
2201
2202static const char AttrDoc_Consumable[] = R"reST(Each `class` that uses any of the typestate annotations must first be marked
2203using the `consumable` attribute. Failure to do so will result in a warning.
2204
2205This attribute accepts a single parameter that must be one of the following:
2206`unknown`, `consumed`, or `unconsumed`.)reST";
2207
2208static const char AttrDoc_ConsumableAutoCast[] = R"reST(No documentation.)reST";
2209
2210static const char AttrDoc_ConsumableSetOnRead[] = R"reST(No documentation.)reST";
2211
2212static const char AttrDoc_Convergent[] = R"reST(The `convergent` attribute can be placed on a function declaration. It is
2213translated into the LLVM `convergent` attribute, which indicates that the call
2214instructions of a function with this attribute cannot be made control-dependent
2215on any additional values.
2216
2217This attribute is different from `noduplicate` because it allows duplicating
2218function calls if it can be proved that the duplicated function calls are
2219not made control-dependent on any additional values, e.g., unrolling a loop
2220executed by all work items.
2221
2222Sample usage:
2223
2224```c
2225void convfunc(void) __attribute__((convergent));
2226// Setting it as a C++11 attribute is also valid in a C++ program.
2227// void convfunc(void) [[clang::convergent]];
2228```)reST";
2229
2230static const char AttrDoc_CoroAwaitElidable[] = R"reST(The `[[clang::coro_await_elidable]]` is a class attribute which can be
2231applied to a coroutine return type. It provides a hint to the compiler to apply
2232Heap Allocation Elision more aggressively.
2233
2234When a coroutine function returns such a type, a direct call expression therein
2235that returns a prvalue of a type attributed `[[clang::coro_await_elidable]]`
2236is said to be under a safe elide context if one of the following is true:
2237
2238- it is the immediate right-hand side operand to a co_await expression.
2239- it is an argument to a `[[clang::coro_await_elidable_argument]]` parameter
2240 or parameter pack of another direct call expression under a safe elide context.
2241
2242Do note that the safe elide context applies only to the call expression itself,
2243and the context does not transitively include any of its subexpressions unless
2244exceptional rules of `[[clang::coro_await_elidable_argument]]` apply.
2245
2246The compiler performs heap allocation elision on call expressions under a safe
2247elide context, if the callee is a coroutine.
2248
2249Example:
2250
2251```c++
2252class [[clang::coro_await_elidable]] Task { ... };
2253
2254Task foo();
2255Task bar() {
2256 co_await foo(); // foo()'s coroutine frame on this line is elidable
2257 auto t = foo(); // foo()'s coroutine frame on this line is NOT elidable
2258 co_await t;
2259}
2260```
2261
2262Such elision replaces the heap allocated activation frame of the callee coroutine
2263with a local variable within the enclosing braces in the caller's stack frame.
2264The local variable, like other variables in coroutines, may be collected into the
2265coroutine frame, which may be allocated on the heap. The behavior is undefined
2266if the caller coroutine is destroyed earlier than the callee coroutine.)reST";
2267
2268static const char AttrDoc_CoroAwaitElidableArgument[] = R"reST(The `[[clang::coro_await_elidable_argument]]` is a function parameter attribute.
2269It works in conjunction with `[[clang::coro_await_elidable]]` to propagate a
2270safe elide context to a parameter or parameter pack if the function is called
2271under a safe elide context.
2272
2273This is sometimes necessary on utility functions used to compose or modify the
2274behavior of a callee coroutine.
2275
2276Example:
2277
2278```c++
2279template <typename T>
2280class [[clang::coro_await_elidable]] Task { ... };
2281
2282template <typename... T>
2283class [[clang::coro_await_elidable]] WhenAll { ... };
2284
2285// `when_all` is a utility function that composes coroutines. It does not
2286// need to be a coroutine to propagate.
2287template <typename... T>
2288WhenAll<T...> when_all([[clang::coro_await_elidable_argument]] Task<T> tasks...);
2289
2290Task<int> foo();
2291Task<int> bar();
2292Task<void> example1() {
2293 // `when_all`, `foo`, and `bar` are all elide safe because `when_all` is
2294 // under a safe elide context and, thanks to the [[clang::coro_await_elidable_argument]]
2295 // attribute, such context is propagated to foo and bar.
2296 co_await when_all(foo(), bar());
2297}
2298
2299Task<void> example2() {
2300 // `when_all` and `bar` are elide safe. `foo` is not elide safe.
2301 auto f = foo();
2302 co_await when_all(f, bar());
2303}
2304
2305
2306Task<void> example3() {
2307 // None of the calls are elide safe.
2308 auto t = when_all(foo(), bar());
2309 co_await t;
2310}
2311```)reST";
2312
2313static const char AttrDoc_CoroDisableLifetimeBound[] = R"reST(The `[[clang::coro_lifetimebound]]` is a class attribute which can be applied
2314to a coroutine return type ([coro_return_type, coro_wrapper]) (i.e.
2315it should also be annotated with `[[clang::coro_return_type]]`).
2316
2317All parameters of a function are considered to be lifetime bound if the function returns a
2318coroutine return type (CRT) annotated with `[[clang::coro_lifetimebound]]`.
2319This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2320with `[[clang::coro_disable_lifetimebound]]` function attribute .
2321See documentation of [lifetimebound] for details about lifetime bound analysis.
2322
2323Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2324
2325For example,
2326
2327```c++
2328task<int> coro(const int& a) { co_return a + 1; }
2329task<int> dangling_refs(int a) {
2330 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2331 auto foo = coro(1);
2332 // `coro` captures reference to local variable `a` which is destroyed after the return.
2333 return coro(a);
2334}
2335```
2336
2337Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2338which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2339`[[clang::coro_lifetimebound]]`, then lifetime bound analysis would detect capturing reference to
2340temporaries or return address of a local variable.
2341
2342Both coroutines and coroutine wrappers are part of this analysis.
2343
2344```c++
2345template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2346 using promise_type = some_promise_type;
2347};
2348
2349Task<int> coro(const int& a) { co_return a + 1; }
2350[[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2351 return a > b ? coro(a) : coro(b);
2352}
2353Task<int> temporary_reference() {
2354 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2355
2356 int a = 1;
2357 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2358
2359 co_return co_await coro(1); // fine.
2360}
2361[[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2362 return coro(a); // warning: returning address of stack variable `a`.
2363}
2364```
2365
2366This analysis can be disabled for all calls to a particular function by annotating the function
2367with function attribute `[[clang::coro_disable_lifetimebound]]`.
2368For example, this could be useful for coroutine wrappers which accept reference parameters
2369but do not pass them to the underlying coroutine or pass them by value.
2370
2371```c++
2372Task<int> coro(int a) { co_return a + 1; }
2373[[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2374 return coro(a + 1);
2375}
2376void use() {
2377 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2378}
2379```)reST";
2380
2381static const char AttrDoc_CoroLifetimeBound[] = R"reST(The `[[clang::coro_lifetimebound]]` is a class attribute which can be applied
2382to a coroutine return type ([coro_return_type, coro_wrapper]) (i.e.
2383it should also be annotated with `[[clang::coro_return_type]]`).
2384
2385All parameters of a function are considered to be lifetime bound if the function returns a
2386coroutine return type (CRT) annotated with `[[clang::coro_lifetimebound]]`.
2387This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2388with `[[clang::coro_disable_lifetimebound]]` function attribute .
2389See documentation of [lifetimebound] for details about lifetime bound analysis.
2390
2391Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2392
2393For example,
2394
2395```c++
2396task<int> coro(const int& a) { co_return a + 1; }
2397task<int> dangling_refs(int a) {
2398 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2399 auto foo = coro(1);
2400 // `coro` captures reference to local variable `a` which is destroyed after the return.
2401 return coro(a);
2402}
2403```
2404
2405Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2406which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2407`[[clang::coro_lifetimebound]]`, then lifetime bound analysis would detect capturing reference to
2408temporaries or return address of a local variable.
2409
2410Both coroutines and coroutine wrappers are part of this analysis.
2411
2412```c++
2413template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2414 using promise_type = some_promise_type;
2415};
2416
2417Task<int> coro(const int& a) { co_return a + 1; }
2418[[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2419 return a > b ? coro(a) : coro(b);
2420}
2421Task<int> temporary_reference() {
2422 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2423
2424 int a = 1;
2425 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2426
2427 co_return co_await coro(1); // fine.
2428}
2429[[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2430 return coro(a); // warning: returning address of stack variable `a`.
2431}
2432```
2433
2434This analysis can be disabled for all calls to a particular function by annotating the function
2435with function attribute `[[clang::coro_disable_lifetimebound]]`.
2436For example, this could be useful for coroutine wrappers which accept reference parameters
2437but do not pass them to the underlying coroutine or pass them by value.
2438
2439```c++
2440Task<int> coro(int a) { co_return a + 1; }
2441[[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2442 return coro(a + 1);
2443}
2444void use() {
2445 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2446}
2447```)reST";
2448
2449static const char AttrDoc_CoroOnlyDestroyWhenComplete[] = R"reST(The `coro_only_destroy_when_complete` attribute should be marked on a C++ class. The coroutines
2450whose return type is marked with the attribute are assumed to be destroyed only after the coroutine has
2451reached the final suspend point.
2452
2453This is helpful for the optimizers to reduce the size of the destroy function for the coroutines.
2454
2455For example,
2456
2457```c++
2458A foo() {
2459 dtor d;
2460 co_await something();
2461 dtor d1;
2462 co_await something();
2463 dtor d2;
2464 co_return 43;
2465}
2466```
2467
2468The compiler may generate the following pseudocode:
2469
2470```c++
2471void foo.destroy(foo.Frame *frame) {
2472 switch(frame->suspend_index()) {
2473 case 1:
2474 frame->d.~dtor();
2475 break;
2476 case 2:
2477 frame->d.~dtor();
2478 frame->d1.~dtor();
2479 break;
2480 case 3:
2481 frame->d.~dtor();
2482 frame->d1.~dtor();
2483 frame->d2.~dtor();
2484 break;
2485 default: // coroutine completed or haven't started
2486 break;
2487 }
2488
2489 frame->promise.~promise_type();
2490 delete frame;
2491}
2492```
2493
2494The `foo.destroy()` function's purpose is to release all of the resources
2495initialized for the coroutine when it is destroyed in a suspended state.
2496However, if the coroutine is only ever destroyed at the final suspend state,
2497the rest of the conditions are superfluous.
2498
2499The user can use the `coro_only_destroy_when_complete` attributo suppress
2500generation of the other destruction cases, optimizing the above `foo.destroy` to:
2501
2502```c++
2503void foo.destroy(foo.Frame *frame) {
2504 frame->promise.~promise_type();
2505 delete frame;
2506}
2507```)reST";
2508
2509static const char AttrDoc_CoroReturnType[] = R"reST(The `[[clang::coro_return_type]]` attribute is used to help static analyzers to recognize
2510coroutines from the function signatures.
2511
2512The `coro_return_type` attribute should be marked on a C++ class to mark it as
2513a **coroutine return type (CRT)**.
2514
2515A function `R func(P1, .., PN)` has a coroutine return type (CRT) `R` if `R`
2516is marked by `[[clang::coro_return_type]]` and `R` has a promise type associated to it
2517(i.e., `std::coroutine_traits<R, P1, .., PN>::promise_type` is a valid promise type).
2518
2519If the return type of a function is a `CRT` then the function must be a coroutine.
2520Otherwise the program is invalid. It is allowed for a non-coroutine to return a `CRT`
2521if the function is marked with `[[clang::coro_wrapper]]`.
2522
2523The `[[clang::coro_wrapper]]` attribute should be marked on a C++ function to mark it as
2524a **coroutine wrapper**. A coroutine wrapper is a function which returns a `CRT`,
2525is not a coroutine itself and is marked with `[[clang::coro_wrapper]]`.
2526
2527Clang will enforce that all functions that return a `CRT` are either coroutines or marked
2528with `[[clang::coro_wrapper]]`. Clang will enforce this with an error.
2529
2530From a language perspective, it is not possible to differentiate between a coroutine and a
2531function returning a CRT by merely looking at the function signature.
2532
2533Coroutine wrappers, in particular, are susceptible to capturing
2534references to temporaries and other lifetime issues. This allows to avoid such lifetime
2535issues with coroutine wrappers.
2536
2537For example,
2538
2539```c++
2540// This is a CRT.
2541template <typename T> struct [[clang::coro_return_type]] Task {
2542 using promise_type = some_promise_type;
2543};
2544
2545Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2546Task<int> foo() { return increment(1); } // Error. foo is not a coroutine.
2547
2548// Fine for a coroutine wrapper to return a CRT.
2549[[clang::coro_wrapper]] Task<int> foo() { return increment(1); }
2550
2551void bar() {
2552 // Invalid. This intantiates a function which returns a CRT but is not marked as
2553 // a coroutine wrapper.
2554 std::function<Task<int>(int)> f = increment;
2555}
2556```
2557
2558Note: `a_promise_type::get_return_object` is exempted from this analysis as it is a necessary
2559implementation detail of any coroutine library.)reST";
2560
2561static const char AttrDoc_CoroWrapper[] = R"reST(The `[[clang::coro_return_type]]` attribute is used to help static analyzers to recognize
2562coroutines from the function signatures.
2563
2564The `coro_return_type` attribute should be marked on a C++ class to mark it as
2565a **coroutine return type (CRT)**.
2566
2567A function `R func(P1, .., PN)` has a coroutine return type (CRT) `R` if `R`
2568is marked by `[[clang::coro_return_type]]` and `R` has a promise type associated to it
2569(i.e., `std::coroutine_traits<R, P1, .., PN>::promise_type` is a valid promise type).
2570
2571If the return type of a function is a `CRT` then the function must be a coroutine.
2572Otherwise the program is invalid. It is allowed for a non-coroutine to return a `CRT`
2573if the function is marked with `[[clang::coro_wrapper]]`.
2574
2575The `[[clang::coro_wrapper]]` attribute should be marked on a C++ function to mark it as
2576a **coroutine wrapper**. A coroutine wrapper is a function which returns a `CRT`,
2577is not a coroutine itself and is marked with `[[clang::coro_wrapper]]`.
2578
2579Clang will enforce that all functions that return a `CRT` are either coroutines or marked
2580with `[[clang::coro_wrapper]]`. Clang will enforce this with an error.
2581
2582From a language perspective, it is not possible to differentiate between a coroutine and a
2583function returning a CRT by merely looking at the function signature.
2584
2585Coroutine wrappers, in particular, are susceptible to capturing
2586references to temporaries and other lifetime issues. This allows to avoid such lifetime
2587issues with coroutine wrappers.
2588
2589For example,
2590
2591```c++
2592// This is a CRT.
2593template <typename T> struct [[clang::coro_return_type]] Task {
2594 using promise_type = some_promise_type;
2595};
2596
2597Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2598Task<int> foo() { return increment(1); } // Error. foo is not a coroutine.
2599
2600// Fine for a coroutine wrapper to return a CRT.
2601[[clang::coro_wrapper]] Task<int> foo() { return increment(1); }
2602
2603void bar() {
2604 // Invalid. This intantiates a function which returns a CRT but is not marked as
2605 // a coroutine wrapper.
2606 std::function<Task<int>(int)> f = increment;
2607}
2608```
2609
2610Note: `a_promise_type::get_return_object` is exempted from this analysis as it is a necessary
2611implementation detail of any coroutine library.)reST";
2612
2613static const char AttrDoc_CountedBy[] = R"reST(The `counted_by` attribute is applied to a pointer or flexible array member to
2614indicate that the pointer points to (or the flexible array member contains) at
2615least the number of *elements* given by the attribute's argument.
2616
2617This attribute is used by {doc}`-fbounds-safety <BoundsSafety>` to propagate
2618bounds information on API surfaces without any ABI changes. This attribute is
2619also used to improve the results of the array bound sanitizer and the
2620`__builtin_dynamic_object_size` builtin.
2621
2622Because the size of the pointee type must be known to compute the pointer's
2623bounds, such a pointer must not be used while its pointee type is incomplete; a
2624pointer to a forward-declared type is accepted on fields annotated with
2625`counted_by`, but the type must be completed before the pointer is used. If
2626the pointee type can never be completed, `counted_by` is rejected and
2627`sized_by` should be used instead. `void *` is a special case: as a GNU
2628extension (diagnosed by `-Wgnu-pointer-arith`), `counted_by` is accepted on
2629it, where it behaves like `sized_by` (the argument is treated as a byte count,
2630`void` having an assumed size of one byte).
2631
2632A pointer annotated with `counted_by` must have a count of zero when it is
2633null. This requirement is currently only enforced when compiling with
2634{doc}`-fbounds-safety <BoundsSafety>` (see {ref}`Current status of
2635-fbounds-safety support in upstream Clang <bounds-safety-current-upstream-status>`). Use
2636`counted_by_or_null` for a pointer that may be null while carrying a nonzero
2637count.
2638
2639#### Keeping pointer and count in sync
2640
2641The `counted_by` attribute establishes a relationship between the annotated
2642pointer and its count: the pointer must point to at least `count` elements.
2643Assigning to only one of them can break this relationship.
2644Without {doc}`-fbounds-safety <BoundsSafety>`, it is the programmer's
2645responsibility to ensure the pointer and count remain in sync. With
2646`-fbounds-safety` it is automatically enforced. For example:
2647
2648```c
2649struct buffer {
2650 int *buf __attribute__((counted_by(count)));
2651 size_t count;
2652};
2653
2654void grow(struct buffer *b, size_t new_count) {
2655 // b->buf isn't updated. The underlying memory pointed to by b->buf might be
2656 // smaller than new_count which would contradict the counted_by attribute.
2657 // Compile error with -fbounds-safety but allowed without -fbounds-safety.
2658 b->count = new_count;
2659}
2660```
2661
2662Updating both together - so that `buf` points to `count` elements - keeps
2663the attribute true. For example:
2664
2665```c
2666void grow(struct buffer *b, size_t new_count) {
2667 // Allowed by -fbounds-safety
2668 int *new_buf = malloc(new_count * sizeof(int));
2669 // -fbounds-safety enforces that the `new_buf` points to at least `new_count`
2670 // integers at runtime. Without -fbounds-safety nothing enforces this.
2671 b->buf = new_buf;
2672 b->count = new_count;
2673}
2674```
2675
2676#### Flexible array members
2677
2678The `counted_by` attribute may also be applied to the flexible array member of
2679a structure in C. In this case the argument names the field member holding the
2680count of elements in the flexible array; that field must be within the same
2681non-anonymous, enclosing struct as the flexible array member.
2682
2683This example specifies that the flexible array member `array` has the number
2684of elements allocated for it in `count`:
2685
2686```c
2687struct bar;
2688
2689struct foo {
2690 size_t count;
2691 char other;
2692 struct bar *array[] __attribute__((counted_by(count)));
2693};
2694```
2695
2696This establishes a relationship between `array` and `count`. Specifically,
2697`array` must have at least `count` number of elements available. It's the
2698user's responsibility to ensure that this relationship is maintained through
2699changes to the structure.
2700
2701In the following example, the allocated array erroneously has fewer elements
2702than what's specified by `p->count`. This would result in an out-of-bounds
2703access not being detected.
2704
2705```c
2706#define SIZE_INCR 42
2707
2708struct foo *p;
2709
2710void foo_alloc(size_t count) {
2711 p = malloc(MAX(sizeof(struct foo),
2712 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2713 p->count = count + SIZE_INCR;
2714}
2715```
2716
2717The next example updates `p->count`, but breaks the relationship requirement
2718that `p->array` must have at least `p->count` number of elements available:
2719
2720```c
2721#define SIZE_INCR 42
2722
2723struct foo *p;
2724
2725void foo_alloc(size_t count) {
2726 p = malloc(MAX(sizeof(struct foo),
2727 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2728 p->count = count;
2729}
2730
2731void use_foo(int index, int val) {
2732 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
2733 p->array[index] = val; /* The sanitizer can't properly check this access. */
2734}
2735```
2736
2737In this example, an update to `p->count` maintains the relationship
2738requirement:
2739
2740```c
2741void use_foo(int index, int val) {
2742 if (p->count == 0)
2743 return;
2744 --p->count;
2745 p->array[index] = val;
2746}
2747```)reST";
2748
2749static const char AttrDoc_CountedByOrNull[] = R"reST(The `counted_by_or_null` attribute is applied to a pointer to indicate that,
2750if the pointer is non-null, it points to memory containing at least the number
2751of *elements* given by the attribute's argument. If the pointer is null, the
2752value of the argument is ignored and the pointer points to zero elements.
2753
2754The `counted_by_or_null` attribute is identical to `counted_by` except that
2755it treats null pointers differently and cannot be applied to a flexible array
2756member. Whereas `counted_by` requires a null pointer to have a count of zero,
2757`counted_by_or_null` allows the pointer to be null regardless of the value of
2758the count. This supports the common idiom where a pointer is either null or
2759points to memory containing at least the given number of elements.
2760
2761Currently only {doc}`-fbounds-safety <BoundsSafety>` makes use of the
2762distinction between `counted_by_or_null` and `counted_by` (see
2763{ref}`Current status of -fbounds-safety support in upstream Clang
2764<bounds-safety-current-upstream-status>`).)reST";
2765
2766static const char AttrDoc_DLLExport[] = R"reST(The `__declspec(dllexport)` attribute declares a variable, function, or
2767Objective-C interface to be exported from the module. It is available under the
2768`-fdeclspec` flag for compatibility with various compilers. The primary use
2769is for COFF object files which explicitly specify what interfaces are available
2770for external use. See the [dllexport][dllexport] documentation on MSDN for more
2771information.
2772
2773[dllexport]: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2774
2775static const char AttrDoc_DLLExportOnDecl[] = R"reST()reST";
2776
2777static const char AttrDoc_DLLExportStaticLocal[] = R"reST()reST";
2778
2779static const char AttrDoc_DLLImport[] = R"reST(The `__declspec(dllimport)` attribute declares a variable, function, or
2780Objective-C interface to be imported from an external module. It is available
2781under the `-fdeclspec` flag for compatibility with various compilers. The
2782primary use is for COFF object files which explicitly specify what interfaces
2783are imported from external modules. See the [dllimport][dllimport] documentation on MSDN
2784for more information.
2785
2786Note that a dllimport function may still be inlined, if its definition is
2787available and it doesn't reference any non-dllimport functions or global
2788variables.
2789
2790[dllimport]: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2791
2792static const char AttrDoc_DLLImportStaticLocal[] = R"reST()reST";
2793
2794static const char AttrDoc_Deprecated[] = R"reST(The `deprecated` attribute can be applied to a function, a variable, or a
2795type. This is useful when identifying functions, variables, or types that are
2796expected to be removed in a future version of a program.
2797
2798Consider the function declaration for a hypothetical function `f`:
2799
2800```c++
2801void f(void) __attribute__((deprecated("message", "replacement")));
2802```
2803
2804When spelled as `__attribute__((deprecated))`, the deprecated attribute can have
2805two optional string arguments. The first one is the message to display when
2806emitting the warning; the second one enables the compiler to provide a Fix-It
2807to replace the deprecated name with a new name. Otherwise, when spelled as
2808`[[gnu::deprecated]]` or `[[deprecated]]`, the attribute can have one optional
2809string argument which is the message to display when emitting the warning.)reST";
2810
2811static const char AttrDoc_Destructor[] = R"reST(The `constructor` attribute causes the function to be called before entering
2812`main()`, and the `destructor` attribute causes the function to be called
2813after returning from `main()` or when the `exit()` function has been
2814called. Note, `quick_exit()`, `_Exit()`, and `abort()` prevent a function
2815marked `destructor` from being called.
2816
2817The constructor or destructor function should not accept any arguments and its
2818return type should be `void`.
2819
2820The attributes accept an optional argument used to specify the priority order
2821in which to execute constructor and destructor functions. The priority is
2822given as an integer constant expression between 101 and 65535 (inclusive).
2823Priorities outside of that range are reserved for use by the implementation. A
2824lower value indicates a higher priority of initialization. Note that only the
2825relative ordering of values is important. For example:
2826
2827```c++
2828__attribute__((constructor(200))) void foo(void);
2829__attribute__((constructor(101))) void bar(void);
2830```
2831
2832`bar()` will be called before `foo()`, and both will be called before
2833`main()`. If no argument is given to the `constructor` or `destructor`
2834attribute, they default to the value `65535`.)reST";
2835
2836static const char AttrDoc_DeviceKernel[] = R"reST(These attributes specify that the function represents a kernel for device offloading.
2837The specific semantics depend on the offloading language, target, and attribute spelling.
2838Here is a code example using the attribute to mark a function as a kernel:
2839
2840```c++
2841[[clang::device_kernel]] int foo(int x) { return ++x; }
2842```)reST";
2843
2844static const char AttrDoc_DiagnoseAsBuiltin[] = R"reST(The `diagnose_as_builtin` attribute indicates that Fortify diagnostics are to
2845be applied to the declared function as if it were the function specified by the
2846attribute. The builtin function whose diagnostics are to be mimicked should be
2847given. In addition, the order in which arguments should be applied must also
2848be given.
2849
2850For example, the attribute can be used as follows.
2851
2852```c
2853__attribute__((diagnose_as_builtin(__builtin_memset, 3, 2, 1)))
2854void *mymemset(int n, int c, void *s) {
2855 // ...
2856}
2857```
2858
2859This indicates that calls to `mymemset` should be diagnosed as if they were
2860calls to `__builtin_memset`. The arguments `3, 2, 1` indicate by index the
2861order in which arguments of `mymemset` should be applied to
2862`__builtin_memset`. The third argument should be applied first, then the
2863second, and then the first. Thus (when Fortify warnings are enabled) the call
2864`mymemset(n, c, s)` will diagnose overflows as if it were the call
2865`__builtin_memset(s, c, n)`.
2866
2867For variadic functions, the variadic arguments must come in the same order as
2868they would to the builtin function, after all normal arguments. For instance,
2869to diagnose a new function as if it were `sscanf`, we can use the attribute as
2870follows.
2871
2872```c
2873__attribute__((diagnose_as_builtin(sscanf, 1, 2)))
2874int mysscanf(const char *str, const char *format, ...) {
2875 // ...
2876}
2877```
2878
2879Then the call `mysscanf("abc def", "%4s %4s", buf1, buf2)` will be diagnosed as
2880if it were the call `sscanf("abc def", "%4s %4s", buf1, buf2)`.
2881
2882This attribute cannot be applied to non-static member functions.)reST";
2883
2884static const char AttrDoc_DiagnoseIf[] = R"reST(The `diagnose_if` attribute can be placed on function declarations to emit
2885warnings or errors at compile-time if calls to the attributed function meet
2886certain user-defined criteria. For example:
2887
2888```c
2889int abs(int a)
2890 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning")));
2891int must_abs(int a)
2892 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error")));
2893
2894int val = abs(1); // warning: Redundant abs call
2895int val2 = must_abs(1); // error: Redundant abs call
2896int val3 = abs(val);
2897int val4 = must_abs(val); // Because run-time checks are not emitted for
2898 // diagnose_if attributes, this executes without
2899 // issue.
2900```
2901
2902`diagnose_if` is closely related to `enable_if`, with a few key differences:
2903
2904- Overload resolution is not aware of `diagnose_if` attributes: they're
2905 considered only after we select the best candidate from a given candidate set.
2906- Function declarations that differ only in their `diagnose_if` attributes are
2907 considered to be redeclarations of the same function (not overloads).
2908- If the condition provided to `diagnose_if` cannot be evaluated, no
2909 diagnostic will be emitted.
2910
2911Otherwise, `diagnose_if` is essentially the logical negation of `enable_if`.
2912
2913As a result of bullet number two, `diagnose_if` attributes will stack on the
2914same function. For example:
2915
2916```c
2917int foo() __attribute__((diagnose_if(1, "diag1", "warning")));
2918int foo() __attribute__((diagnose_if(1, "diag2", "warning")));
2919
2920int bar = foo(); // warning: diag1
2921 // warning: diag2
2922int (*fooptr)(void) = foo; // warning: diag1
2923 // warning: diag2
2924
2925constexpr int supportsAPILevel(int N) { return N < 5; }
2926int baz(int a)
2927 __attribute__((diagnose_if(!supportsAPILevel(10),
2928 "Upgrade to API level 10 to use baz", "error")));
2929int baz(int a)
2930 __attribute__((diagnose_if(!a, "0 is not recommended.", "warning")));
2931
2932int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz
2933int v = baz(0); // error: Upgrade to API level 10 to use baz
2934```
2935
2936Query for this feature with `__has_attribute(diagnose_if)`.)reST";
2937
2938static const char AttrDoc_DisableSanitizerInstrumentation[] = R"reST(Use the `disable_sanitizer_instrumentation` attribute on a function,
2939Objective-C method, or global variable, to specify that no sanitizer
2940instrumentation should be applied.
2941
2942This is not the same as `__attribute__((no_sanitize(...)))`, which depending
2943on the tool may still insert instrumentation to prevent false positive reports.)reST";
2944
2945static const char AttrDoc_DisableTailCalls[] = R"reST(The `disable_tail_calls` attribute instructs the backend to not perform tail
2946call optimization inside the marked function.
2947
2948For example:
2949
2950```c
2951int callee(int);
2952
2953int foo(int a) __attribute__((disable_tail_calls)) {
2954 return callee(a); // This call is not tail-call optimized.
2955}
2956```
2957
2958Marking virtual functions as `disable_tail_calls` is legal.
2959
2960```c++
2961int callee(int);
2962
2963class Base {
2964public:
2965 [[clang::disable_tail_calls]] virtual int foo1() {
2966 return callee(); // This call is not tail-call optimized.
2967 }
2968};
2969
2970class Derived1 : public Base {
2971public:
2972 int foo1() override {
2973 return callee(); // This call is tail-call optimized.
2974 }
2975};
2976```)reST";
2977
2978static const char AttrDoc_EmptyBases[] = R"reST(The empty_bases attribute permits the compiler to utilize the
2979empty-base-optimization more frequently.
2980This attribute only applies to struct, class, and union types.
2981It is only supported when using the Microsoft C++ ABI.)reST";
2982
2983static const char AttrDoc_EnableIf[] = R"reST(:::{Note}
2984Some features of this attribute are experimental. The meaning of
2985multiple enable_if attributes on a single declaration is subject to change in
2986a future version of clang. Also, the ABI is not standardized and the name
2987mangling may change in future versions. To avoid that, use asm labels.
2988:::
2989
2990The `enable_if` attribute can be placed on function declarations to control
2991which overload is selected based on the values of the function's arguments.
2992When combined with the `overloadable` attribute, this feature is also
2993available in C.
2994
2995```c++
2996int isdigit(int c);
2997int isdigit(int c)
2998 __attribute__((enable_if(c <= -1 || c > 255, "chosen when 'c' is out of range")))
2999 __attribute__((unavailable("'c' must have the value of an unsigned char or EOF")));
3000
3001void foo(char c) {
3002 isdigit(c);
3003 isdigit(10);
3004 isdigit(-10); // results in a compile-time error.
3005}
3006```
3007
3008The enable_if attribute takes two arguments, the first is an expression written
3009in terms of the function parameters, the second is a string explaining why this
3010overload candidate could not be selected to be displayed in diagnostics. The
3011expression is part of the function signature for the purposes of determining
3012whether it is a redeclaration (following the rules used when determining
3013whether a C++ template specialization is ODR-equivalent), but is not part of
3014the type.
3015
3016The enable_if expression is evaluated as if it were the body of a
3017bool-returning constexpr function declared with the arguments of the function
3018it is being applied to, then called with the parameters at the call site. If the
3019result is false or could not be determined through constant expression
3020evaluation, then this overload will not be chosen and the provided string may
3021be used in a diagnostic if the compile fails as a result.
3022
3023Because the enable_if expression is an unevaluated context, there are no global
3024state changes, nor the ability to pass information from the enable_if
3025expression to the function body. For example, suppose we want calls to
3026strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
3027strbuf) only if the size of strbuf can be determined:
3028
3029```c++
3030__attribute__((always_inline))
3031static inline size_t strnlen(const char *s, size_t maxlen)
3032 __attribute__((overloadable))
3033 __attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
3034 "chosen when the buffer size is known but 'maxlen' is not")))
3035{
3036 return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
3037}
3038```
3039
3040Multiple enable_if attributes may be applied to a single declaration. In this
3041case, the enable_if expressions are evaluated from left to right in the
3042following manner. First, the candidates whose enable_if expressions evaluate to
3043false or cannot be evaluated are discarded. If the remaining candidates do not
3044share ODR-equivalent enable_if expressions, the overload resolution is
3045ambiguous. Otherwise, enable_if overload resolution continues with the next
3046enable_if attribute on the candidates that have not been discarded and have
3047remaining enable_if attributes. In this way, we pick the most specific
3048overload out of a number of viable overloads using enable_if.
3049
3050```c++
3051void f() __attribute__((enable_if(true, ""))); // #1
3052void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2
3053
3054void g(int i, int j) __attribute__((enable_if(i, ""))); // #1
3055void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2
3056```
3057
3058In this example, a call to f() is always resolved to #2, as the first enable_if
3059expression is ODR-equivalent for both declarations, but #1 does not have another
3060enable_if expression to continue evaluating, so the next round of evaluation has
3061only a single candidate. In a call to g(1, 1), the call is ambiguous even though
3062#2 has more enable_if attributes, because the first enable_if expressions are
3063not ODR-equivalent.
3064
3065Query for this feature with `__has_attribute(enable_if)`.
3066
3067Note that functions with one or more `enable_if` attributes may not have
3068their address taken, unless all of the conditions specified by said
3069`enable_if` are constants that evaluate to `true`. For example:
3070
3071```c
3072const int TrueConstant = 1;
3073const int FalseConstant = 0;
3074int f(int a) __attribute__((enable_if(a > 0, "")));
3075int g(int a) __attribute__((enable_if(a == 0 || a != 0, "")));
3076int h(int a) __attribute__((enable_if(1, "")));
3077int i(int a) __attribute__((enable_if(TrueConstant, "")));
3078int j(int a) __attribute__((enable_if(FalseConstant, "")));
3079
3080void fn() {
3081 int (*ptr)(int);
3082 ptr = &f; // error: 'a > 0' is not always true
3083 ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant
3084 ptr = &h; // OK: 1 is a truthy constant
3085 ptr = &i; // OK: 'TrueConstant' is a truthy constant
3086 ptr = &j; // error: 'FalseConstant' is a constant, but not truthy
3087}
3088```
3089
3090Because `enable_if` evaluation happens during overload resolution,
3091`enable_if` may give unintuitive results when used with templates, depending
3092on when overloads are resolved. In the example below, clang will emit a
3093diagnostic about no viable overloads for `foo` in `bar`, but not in `baz`:
3094
3095```c++
3096double foo(int i) __attribute__((enable_if(i > 0, "")));
3097void *foo(int i) __attribute__((enable_if(i <= 0, "")));
3098template <int I>
3099auto bar() { return foo(I); }
3100
3101template <typename T>
3102auto baz() { return foo(T::number); }
3103
3104struct WithNumber { constexpr static int number = 1; };
3105void callThem() {
3106 bar<sizeof(WithNumber)>();
3107 baz<WithNumber>();
3108}
3109```
3110
3111This is because, in `bar`, `foo` is resolved prior to template
3112instantiation, so the value for `I` isn't known (thus, both `enable_if`
3113conditions for `foo` fail). However, in `baz`, `foo` is resolved during
3114template instantiation, so the value for `T::number` is known.)reST";
3115
3116static const char AttrDoc_EnforceTCB[] = R"reST(The `enforce_tcb` attribute can be placed on functions to enforce that a
3117trusted compute base (TCB) does not call out of the TCB. This generates a
3118warning every time a function not marked with an `enforce_tcb` attribute is
3119called from a function with the `enforce_tcb` attribute. A function may be a
3120part of multiple TCBs. Invocations through function pointers are currently
3121not checked. Builtins are considered to a part of every TCB.
3122
3123- `enforce_tcb(Name)` indicates that this function is a part of the TCB named `Name`)reST";
3124
3125static const char AttrDoc_EnforceTCBLeaf[] = R"reST(The `enforce_tcb_leaf` attribute satisfies the requirement enforced by
3126`enforce_tcb` for the marked function to be in the named TCB but does not
3127continue to check the functions called from within the leaf function.
3128
3129- `enforce_tcb_leaf(Name)` indicates that this function is a part of the TCB named `Name`)reST";
3130
3131static const char AttrDoc_EnumExtensibility[] = R"reST(Attribute `enum_extensibility` is used to distinguish between enum definitions
3132that are extensible and those that are not. The attribute can take either
3133`closed` or `open` as an argument. `closed` indicates a variable of the
3134enum type takes a value that corresponds to one of the enumerators listed in the
3135enum definition or, when the enum is annotated with `flag_enum`, a value that
3136can be constructed using values corresponding to the enumerators. `open`
3137indicates a variable of the enum type can take any values allowed by the
3138standard and instructs clang to be more lenient when issuing warnings.
3139
3140```c
3141enum __attribute__((enum_extensibility(closed))) ClosedEnum {
3142 A0, A1
3143};
3144
3145enum __attribute__((enum_extensibility(open))) OpenEnum {
3146 B0, B1
3147};
3148
3149enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum {
3150 C0 = 1 << 0, C1 = 1 << 1
3151};
3152
3153enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum {
3154 D0 = 1 << 0, D1 = 1 << 1
3155};
3156
3157void foo1() {
3158 enum ClosedEnum ce;
3159 enum OpenEnum oe;
3160 enum ClosedFlagEnum cfe;
3161 enum OpenFlagEnum ofe;
3162
3163 ce = A1; // no warnings
3164 ce = 100; // warning issued
3165 oe = B1; // no warnings
3166 oe = 100; // no warnings
3167 cfe = C0 | C1; // no warnings
3168 cfe = C0 | C1 | 4; // warning issued
3169 ofe = D0 | D1; // no warnings
3170 ofe = D0 | D1 | 4; // no warnings
3171}
3172```)reST";
3173
3174static const char AttrDoc_Error[] = R"reST(The `error` and `warning` function attributes can be used to specify a
3175custom diagnostic to be emitted when a call to such a function is not
3176eliminated via optimizations. This can be used to create compile time
3177assertions that depend on optimizations, while providing diagnostics
3178pointing to precise locations of the call site in the source.
3179
3180```c++
3181__attribute__((warning("oh no"))) void dontcall();
3182void foo() {
3183 if (someCompileTimeAssertionThatsTrue)
3184 dontcall(); // Warning
3185
3186 dontcall(); // Warning
3187
3188 if (someCompileTimeAssertionThatsFalse)
3189 dontcall(); // No Warning
3190 sizeof(dontcall()); // No Warning
3191}
3192```
3193
3194When the call occurs through inlined functions, the
3195`-fdiagnostics-show-inlining-chain` option can be used to show the
3196inlining chain that led to the call. This helps identify which call site
3197triggered the diagnostic when the attributed function is called from
3198multiple locations through inline functions.
3199
3200When enabled, this option automatically uses debug info for accurate source
3201locations if available (`-gline-directives-only` (implicitly enabled at
3202`-g1`) or higher), or falls back to a heuristic based on metadata tracking.
3203When falling back, a note is emitted suggesting `-gline-directives-only` for
3204more accurate locations.)reST";
3205
3206static const char AttrDoc_ExcludeFromExplicitInstantiation[] = R"reST(The `exclude_from_explicit_instantiation` attribute opts-out a member of a
3207class template from being part of explicit template instantiations of that
3208class template. This means that an explicit instantiation will not instantiate
3209members of the class template marked with the attribute, but also that code
3210where an extern template declaration of the enclosing class template is visible
3211will not take for granted that an external instantiation of the class template
3212would provide those members (which would otherwise be a link error, since the
3213explicit instantiation won't provide those members). For example, let's say we
3214don't want the `data()` method to be part of libc++'s ABI. To make sure it
3215is not exported from the dylib, we give it hidden visibility:
3216
3217```c++
3218// in <string>
3219template <class CharT>
3220class basic_string {
3221public:
3222 __attribute__((__visibility__("hidden")))
3223 const value_type* data() const noexcept { ... }
3224};
3225
3226template class basic_string<char>;
3227```
3228
3229Since an explicit template instantiation declaration for `basic_string<char>`
3230is provided, the compiler is free to assume that `basic_string<char>::data()`
3231will be provided by another translation unit, and it is free to produce an
3232external call to this function. However, since `data()` has hidden visibility
3233and the explicit template instantiation is provided in a shared library (as
3234opposed to simply another translation unit), `basic_string<char>::data()`
3235won't be found and a link error will ensue. This happens because the compiler
3236assumes that `basic_string<char>::data()` is part of the explicit template
3237instantiation declaration, when it really isn't. To tell the compiler that
3238`data()` is not part of the explicit template instantiation declaration, the
3239`exclude_from_explicit_instantiation` attribute can be used:
3240
3241```c++
3242// in <string>
3243template <class CharT>
3244class basic_string {
3245public:
3246 __attribute__((__visibility__("hidden")))
3247 __attribute__((exclude_from_explicit_instantiation))
3248 const value_type* data() const noexcept { ... }
3249};
3250
3251template class basic_string<char>;
3252```
3253
3254Now, the compiler won't assume that `basic_string<char>::data()` is provided
3255externally despite there being an explicit template instantiation declaration:
3256the compiler will implicitly instantiate `basic_string<char>::data()` in the
3257TUs where it is used.
3258
3259This attribute can be used on static and non-static member functions of class
3260templates, static data members of class templates and member classes of class
3261templates.
3262
3263**Interaction with `__declspec(dllexport)` and `__declspec(dllimport)`**
3264
3265For a DLL platform (i.e., Windows), this attribute also means "this member will
3266never be exported or imported". Despite its name, this semantics applies to
3267implicit instantiations and non-template entities as well.
3268
3269```c++
3270// in <exception>
3271class __declspec(dllimport) nested_exception {
3272 ...
3273public:
3274 __attribute__((exclude_from_explicit_instantiation))
3275 exception_ptr nested_ptr() const noexcept { ... }
3276};
3277```
3278
3279In this case, `nested_exception::nested_ptr` will never be attempted to be
3280imported.)reST";
3281
3282static const char AttrDoc_ExplicitInit[] = R"reST(The `clang::require_explicit_initialization` attribute indicates that a
3283field of an aggregate must be initialized explicitly by the user when an object
3284of the aggregate type is constructed. The attribute supports both C and C++,
3285but its usage is invalid on non-aggregates.
3286
3287Note that this attribute is *not* a memory safety feature, and is *not* intended
3288to guard against use of uninitialized memory.
3289
3290Rather, it is intended for use in "parameter-objects", used to simulate,
3291for example, the passing of named parameters.
3292Except inside unevaluated contexts, the attribute generates a warning when
3293explicit initializers for such variables are not provided (this occurs
3294regardless of whether any in-class field initializers exist):
3295
3296```c++
3297struct Buffer {
3298 void *address [[clang::require_explicit_initialization]];
3299 size_t length [[clang::require_explicit_initialization]] = 0;
3300};
3301
3302struct ArrayIOParams {
3303 size_t count [[clang::require_explicit_initialization]];
3304 size_t element_size [[clang::require_explicit_initialization]];
3305 int flags = 0;
3306};
3307
3308size_t ReadArray(FILE *file, struct Buffer buffer,
3309 struct ArrayIOParams params);
3310
3311int main() {
3312 unsigned int buf[512];
3313 ReadArray(stdin, {
3314 buf
3315 // warning: field 'length' is not explicitly initialized
3316 }, {
3317 .count = sizeof(buf) / sizeof(*buf),
3318 // warning: field 'element_size' is not explicitly initialized
3319 // (Note that a missing initializer for 'flags' is not diagnosed, because
3320 // the field is not marked as requiring explicit initialization.)
3321 });
3322}
3323```)reST";
3324
3325static const char AttrDoc_ExtVectorType[] = R"reST(The `ext_vector_type(N)` attribute specifies that a type is a vector with N
3326elements, directly mapping to an LLVM vector type. Originally from OpenCL, it
3327allows element access the array subscript operator `[]`, `sN` where N is
3328a hexadecimal value, or `x, y, z, w` for graphics-style indexing.
3329This attribute enables efficient SIMD operations and is usable in
3330general-purpose code.
3331
3332```c++
3333template <typename T, uint32_t N>
3334constexpr T simd_reduce(T [[clang::ext_vector_type(N)]] v) {
3335 static_assert((N & (N - 1)) == 0, "N must be a power of two");
3336 if constexpr (N == 1)
3337 return v[0];
3338 else
3339 return simd_reduce<T, N / 2>(v.hi + v.lo);
3340}
3341```
3342
3343The vector type also supports swizzling up to sixteen elements. This can be done
3344using the object accessors. The OpenCL documentation lists all of the accepted
3345values.
3346
3347```c++
3348using f16_x16 = _Float16 __attribute__((ext_vector_type(16)));
3349
3350f16_x16 reverse(f16_x16 v) { return v.sfedcba9876543210; }
3351```
3352
3353See the OpenCL documentation for some more complete examples.)reST";
3354
3355static const char AttrDoc_ExternalSourceSymbol[] = R"reST(The `external_source_symbol` attribute specifies that a declaration originates
3356from an external source and describes the nature of that source.
3357
3358The fact that Clang is capable of recognizing declarations that were defined
3359externally can be used to provide better tooling support for mixed-language
3360projects or projects that rely on auto-generated code. For instance, an IDE that
3361uses Clang and that supports mixed-language projects can use this attribute to
3362provide a correct "jump-to-definition" feature. For a concrete example,
3363consider a protocol that's defined in a Swift file:
3364
3365```swift
3366@objc public protocol SwiftProtocol {
3367 func method()
3368}
3369```
3370
3371This protocol can be used from Objective-C code by including a header file that
3372was generated by the Swift compiler. The declarations in that header can use
3373the `external_source_symbol` attribute to make Clang aware of the fact
3374that `SwiftProtocol` actually originates from a Swift module:
3375
3376```objc
3377__attribute__((external_source_symbol(language="Swift",defined_in="module")))
3378@protocol SwiftProtocol
3379@required
3380- (void) method;
3381@end
3382```
3383
3384Consequently, when "jump-to-definition" is performed at a location that
3385references `SwiftProtocol`, the IDE can jump to the original definition in
3386the Swift source file rather than jumping to the Objective-C declaration in the
3387auto-generated header file.
3388
3389The `external_source_symbol` attribute is a comma-separated list that includes
3390clauses that describe the origin and the nature of the particular declaration.
3391Those clauses can be:
3392
3393language=*string-literal*
3394
3395: The name of the source language in which this declaration was defined.
3396
3397defined_in=*string-literal*
3398
3399: The name of the source container in which the declaration was defined. The
3400 exact definition of source container is language-specific, e.g. Swift's
3401 source containers are modules, so `defined_in` should specify the Swift
3402 module name.
3403
3404USR=*string-literal*
3405
3406: String that specifies a unified symbol resolution (USR) value for this
3407 declaration. USR string uniquely identifies this particular declaration, and
3408 is typically used when constructing an index of a codebase.
3409 The USR value in this attribute is expected to be generated by an external
3410 compiler that compiled the native declaration using its original source
3411 language. The exact format of the USR string and its other attributes
3412 are determined by the specification of this declaration's source language.
3413 When not specified, Clang's indexer will use the Clang USR for this symbol.
3414 User can query to see if Clang supports the use of the `USR` clause in
3415 the `external_source_symbol` attribute with
3416 `__has_attribute(external_source_symbol) >= 20230206`.
3417
3418generated_declaration
3419
3420: This declaration was automatically generated by some tool.
3421
3422The clauses can be specified in any order. The clauses that are listed above are
3423all optional, but the attribute has to have at least one clause.)reST";
3424
3425static const char AttrDoc_FallThrough[] = R"reST(The `fallthrough` (or `clang::fallthrough`) attribute is used
3426to annotate intentional fall-through
3427between switch labels. It can only be applied to a null statement placed at a
3428point of execution between any statement and the next switch label. It is
3429common to mark these places with a specific comment, but this attribute is
3430meant to replace comments with a more strict annotation, which can be checked
3431by the compiler. This attribute doesn't change semantics of the code and can
3432be used wherever an intended fall-through occurs. It is designed to mimic
3433control-flow statements like `break;`, so it can be placed in most places
3434where `break;` can, but only if there are no statements on the execution path
3435between it and the next switch label.
3436
3437By default, Clang does not warn on unannotated fallthrough from one `switch`
3438case to another. Diagnostics on fallthrough without a corresponding annotation
3439can be enabled with the `-Wimplicit-fallthrough` argument.
3440
3441Here is an example:
3442
3443```c++
3444// compile with -Wimplicit-fallthrough
3445switch (n) {
3446case 22:
3447case 33: // no warning: no statements between case labels
3448 f();
3449case 44: // warning: unannotated fall-through
3450 g();
3451 [[clang::fallthrough]];
3452case 55: // no warning
3453 if (x) {
3454 h();
3455 break;
3456 }
3457 else {
3458 i();
3459 [[clang::fallthrough]];
3460 }
3461case 66: // no warning
3462 p();
3463 [[clang::fallthrough]]; // warning: fallthrough annotation does not
3464 // directly precede case label
3465 q();
3466case 77: // warning: unannotated fall-through
3467 r();
3468}
3469```)reST";
3470
3471static const char AttrDoc_FastCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
3472function to use ECX and EDX as register parameters and clear parameters off of
3473the stack on return. This convention does not support variadic calls or
3474unprototyped functions in C, and has no effect on x86_64 targets. This calling
3475convention is supported primarily for compatibility with existing code. Users
3476seeking register parameters should use the `regparm` attribute, which does
3477not require callee-cleanup. See the documentation for [`__fastcall`][__fastcall] on MSDN.
3478
3479[__fastcall]: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx)reST";
3480
3481static const char AttrDoc_Final[] = R"reST()reST";
3482
3483static const char AttrDoc_FlagEnum[] = R"reST(This attribute can be added to an enumerator to signal to the compiler that it
3484is intended to be used as a flag type. This will cause the compiler to assume
3485that the range of the type includes all of the values that you can get by
3486manipulating bits of the enumerator when issuing warnings.)reST";
3487
3488static const char AttrDoc_Flatten[] = R"reST(The `flatten` attribute causes calls within the attributed function to
3489be inlined unless it is impossible to do so, for example if the body of the
3490callee is unavailable or if the callee has the `noinline` attribute.)reST";
3491
3492static const char AttrDoc_Format[] = R"reST(Clang supports the `format` attribute, which indicates that the function
3493accepts (among other possibilities) a `printf` or `scanf`-like format string
3494and corresponding arguments or a `va_list` that contains these arguments.
3495
3496Please see [GCC documentation about format attribute](http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html) to find details
3497about attribute syntax.
3498
3499Clang implements two kinds of checks with this attribute.
3500
35011. Clang checks that the function with the `format` attribute is called with
3502 a format string that uses format specifiers that are allowed, and that
3503 arguments match the format string. This is the `-Wformat` warning, it is
3504 on by default.
3505
35062. Clang checks that the format string argument is a literal string. This is
3507 the `-Wformat-nonliteral` warning, it is off by default.
3508
3509 Clang implements this mostly the same way as GCC, but there is a difference
3510 for functions that accept a `va_list` argument (for example, `vprintf`).
3511 GCC does not emit `-Wformat-nonliteral` warning for calls to such
3512 functions. Clang does not warn if the format string comes from a function
3513 parameter, where the function is annotated with a compatible attribute,
3514 otherwise it warns. For example:
3515
3516 ```c
3517 __attribute__((__format__ (__scanf__, 1, 3)))
3518 void foo(const char* s, char *buf, ...) {
3519 va_list ap;
3520 va_start(ap, buf);
3521
3522 vprintf(s, ap); // warning: format string is not a string literal
3523 }
3524 ```
3525
3526 In this case we warn because `s` contains a format string for a
3527 `scanf`-like function, but it is passed to a `printf`-like function.
3528
3529 If the attribute is removed, clang still warns, because the format string is
3530 not a string literal.
3531
3532 Another example:
3533
3534 ```c
3535 __attribute__((__format__ (__printf__, 1, 3)))
3536 void foo(const char* s, char *buf, ...) {
3537 va_list ap;
3538 va_start(ap, buf);
3539
3540 vprintf(s, ap); // warning
3541 }
3542 ```
3543
3544 In this case Clang does not warn because the format string `s` and
3545 the corresponding arguments are annotated. If the arguments are
3546 incorrect, the caller of `foo` will receive a warning.
3547
3548As an extension to GCC's behavior, Clang accepts the `format` attribute on
3549non-variadic functions. Clang checks non-variadic format functions for the same
3550classes of issues that can be found on variadic functions, as controlled by the
3551same warning flags, except that the types of formatted arguments is forced by
3552the function signature. For example:
3553
3554```c
3555__attribute__((__format__(__printf__, 1, 2)))
3556void fmt(const char *s, const char *a, int b);
3557
3558void bar(void) {
3559 fmt("%s %i", "hello", 123); // OK
3560 fmt("%i %g", "hello", 123); // warning: arguments don't match format
3561 extern const char *fmt;
3562 fmt(fmt, "hello", 123); // warning: format string is not a string literal
3563}
3564```
3565
3566When using the format attribute on a variadic function, the first data parameter
3567must be the index of the ellipsis in the parameter list. Clang will generate
3568a diagnostic otherwise, as it wouldn't be possible to forward that argument list
3569to `printf`-family functions. For instance, this is an error:
3570
3571```c
3572__attribute__((__format__(__printf__, 1, 2)))
3573void fmt(const char *s, int b, ...);
3574// ^ error: format attribute parameter 3 is out of bounds
3575// (must be __printf__, 1, 3)
3576```
3577
3578Using the `format` attribute on a non-variadic function emits a GCC
3579compatibility diagnostic.)reST";
3580
3581static const char AttrDoc_FormatArg[] = R"reST(No documentation.)reST";
3582
3583static const char AttrDoc_FormatMatches[] = R"reST(The `format` attribute is the basis for the enforcement of diagnostics in the
3584`-Wformat` family, but it only handles the case where the format string is
3585passed along with the arguments it is going to format. It cannot handle the case
3586where the format string and the format arguments are passed separately from each
3587other. For instance:
3588
3589```c
3590static const char *first_name;
3591static double todays_temperature;
3592static int wind_speed;
3593
3594void say_hi(const char *fmt) {
3595 printf(fmt, first_name, todays_temperature);
3596 // ^ warning: format string is not a string literal
3597 printf(fmt, first_name, wind_speed);
3598 // ^ warning: format string is not a string literal
3599}
3600
3601int main() {
3602 say_hi("hello %s, it is %g degrees outside");
3603 say_hi("hello %s, it is %d degrees outside!");
3604 // ^ no diagnostic, but %d cannot format doubles
3605}
3606```
3607
3608In this example, `fmt` is expected to format a `const char *` and a
3609`double`, but these values are not passed to `say_hi`. Without the
3610`format` attribute (which cannot apply in this case), the -Wformat-nonliteral
3611diagnostic unnecessarily triggers in the body of `say_hi`, and incorrect
3612`say_hi` call sites do not trigger a diagnostic.
3613
3614To complement the `format` attribute, Clang also defines the
3615`format_matches` attribute. Its syntax is similar to the `format`
3616attribute's, but instead of taking the index of the first formatted value
3617argument, it takes a C string literal with the expected specifiers:
3618
3619```c
3620static const char *first_name;
3621static double todays_temperature;
3622static int wind_speed;
3623
3624__attribute__((__format_matches__(printf, 1, "%s %g")))
3625void say_hi(const char *fmt) {
3626 printf(fmt, first_name, todays_temperature); // no dignostic
3627 printf(fmt, first_name, wind_speed); // warning: format specifies type 'int' but the argument has type 'double'
3628}
3629
3630int main() {
3631 say_hi("hello %s, it is %g degrees outside");
3632 say_hi("it is %g degrees outside, have a good day %s!");
3633 // warning: format specifies 'double' where 'const char *' is required
3634 // warning: format specifies 'const char *' where 'double' is required
3635}
3636```
3637
3638The third argument to `format_matches` is expected to evaluate to a **C string
3639literal** even when the format string would normally be a different type for the
3640given flavor, like a `CFStringRef` or a `NSString *`.
3641
3642The only requirement on the format string literal is that it has specifiers
3643that are compatible with the arguments that will be used. It can contain
3644arbitrary non-format characters. For instance, for the purposes of compile-time
3645validation, `"%s scored %g%% on her test"` and `"%s%g"` are interchangeable
3646as the format string argument. As a means of self-documentation, users may
3647prefer the former when it provides a useful example of an expected format
3648string.
3649
3650In the implementation of a function with the `format_matches` attribute,
3651format verification works as if the format string was identical to the one
3652specified in the attribute.
3653
3654```c
3655__attribute__((__format_matches__(printf, 1, "%s %g")))
3656void say_hi(const char *fmt) {
3657 printf(fmt, "person", 546);
3658 // ^ warning: format specifies type 'double' but the
3659 // argument has type 'int'
3660 // note: format string is defined here:
3661 // __attribute__((__format_matches__(printf, 1, "%s %g")))
3662 // ^~
3663}
3664```
3665
3666At the call sites of functions with the `format_matches` attribute, format
3667verification instead compares the two format strings to evaluate their
3668equivalence. Each format flavor defines equivalence between format specifiers.
3669Generally speaking, two specifiers are equivalent if they format the same type.
3670For instance, in the `printf` flavor, `%2i` and `%-0.5d` are compatible.
3671When `-Wformat-signedness` is disabled, `%d` and `%u` are compatible. For
3672a negative example, `%ld` is incompatible with `%d`.
3673
3674Do note the following un-obvious cases:
3675
3676- Passing `NULL` as the format string does not trigger format diagnostics.
3677- When the format string is not NULL, it cannot miss specifiers, even in
3678 trailing positions. For instance, `%d` is not accepted when the required
3679 format is `%d %d %d`.
3680- While checks for the `format` attribute tolerate sone size mismatches
3681 that standard argument promotion renders immaterial (such as formatting an
3682 `int` with `%hhd`, which specifies a `char`-sized integer), checks for
3683 `format_matches` require specified argument sizes to match exactly.
3684- Format strings expecting a variable modifier (such as `%*s`) are
3685 incompatible with format strings that would itemize the variable modifiers
3686 (such as `%i %s`), even if the two specify ABI-compatible argument lists.
3687- All pointer specifiers, modifiers aside, are mutually incompatible. For
3688 instance, `%s` is not compatible with `%p`, and `%p` is not compatible
3689 with `%n`, and `%hhn` is incompatible with `%s`, even if the pointers
3690 are ABI-compatible or identical on the selected platform. However, `%0.5s`
3691 is compatible with `%s`, since the difference only exists in modifier flags.
3692 This is not overridable with `-Wformat-pedantic` or its inverse, which
3693 control similar behavior in `-Wformat`.
3694
3695At this time, clang implements `format_matches` only for format types in the
3696`printf` family. This includes variants such as Apple's NSString format and
3697the FreeBSD `kprintf`, but excludes `scanf`. Using a known but unsupported
3698format silently fails in order to be compatible with other implementations that
3699would support these formats.)reST";
3700
3701static const char AttrDoc_FunctionReturnThunks[] = R"reST(The attribute `function_return` can replace return instructions with jumps to
3702target-specific symbols. This attribute supports 2 possible values,
3703corresponding to the values supported by the `-mfunction-return=` command
3704line flag:
3705
3706- `__attribute__((function_return("keep")))` to disable related transforms.
3707 This is useful for undoing global setting from `-mfunction-return=` locally
3708 for individual functions.
3709- `__attribute__((function_return("thunk-extern")))` to replace returns with
3710 jumps, while NOT emitting the thunk.
3711
3712The values `thunk` and `thunk-inline` from GCC are not supported.
3713
3714The symbol used for `thunk-extern` is target specific:
3715
3716- X86: `__x86_return_thunk`
3717
3718As such, this function attribute is currently only supported on X86 targets.)reST";
3719
3720static const char AttrDoc_GCCStruct[] = R"reST(The `ms_struct` and `gcc_struct` attributes request the compiler to enter a
3721special record layout compatibility mode which mimics the layout of Microsoft or
3722Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the
3723requested ABI, the attribute does nothing. However, if it does not, annotated
3724structure or class is laid out in a special compatibility mode, which slightly
3725changes offsets for fields and bit-fields. The intention is to match the layout
3726of the requested ABI for structures which only use C features.
3727
3728Note that the default behavior can be controlled by `-mms-bitfields` and
3729`-mno-ms-bitfields` switches and via `#pragma ms_struct`.
3730
3731The primary difference is for bitfields, where the MS variant only packs
3732adjacent fields into the same allocation unit if they have integral types
3733of the same size, while the GCC/Itanium variant packs all fields in a bitfield
3734tightly.)reST";
3735
3736static const char AttrDoc_GNUInline[] = R"reST(The `gnu_inline` changes the meaning of `extern inline` to use GNU inline
3737semantics, meaning:
3738
3739- If any declaration that is declared `inline` is not declared `extern`,
3740 then the `inline` keyword is just a hint. In particular, an out-of-line
3741 definition is still emitted for a function with external linkage, even if all
3742 call sites are inlined, unlike in C99 and C++ inline semantics.
3743- If all declarations that are declared `inline` are also declared
3744 `extern`, then the function body is present only for inlining and no
3745 out-of-line version is emitted.
3746
3747Some important consequences: `static inline` emits an out-of-line
3748version if needed, a plain `inline` definition emits an out-of-line version
3749always, and an `extern inline` definition (in a header) followed by a
3750(non-`extern`) `inline` declaration in a source file emits an out-of-line
3751version of the function in that source file but provides the function body for
3752inlining to all includers of the header.
3753
3754Either `__GNUC_GNU_INLINE__` (GNU inline semantics) or
3755`__GNUC_STDC_INLINE__` (C99 semantics) will be defined (they are mutually
3756exclusive). If `__GNUC_STDC_INLINE__` is defined, then the `gnu_inline`
3757function attribute can be used to get GNU inline semantics on a per function
3758basis. If `__GNUC_GNU_INLINE__` is defined, then the translation unit is
3759already being compiled with GNU inline semantics as the implied default. It is
3760unspecified which macro is defined in a C++ compilation.
3761
3762GNU inline semantics are the default behavior with `-std=gnu89`,
3763`-std=c89`, `-fgnu89-inline`, or `-std=iso9899:199409`.)reST";
3764
3765static const char AttrDoc_GuardedBy[] = R"reST(No documentation.)reST";
3766
3767static const char AttrDoc_GuardedVar[] = R"reST(No documentation.)reST";
3768
3769static const char AttrDoc_HIPManaged[] = R"reST(The `__managed__` attribute can be applied to a global variable declaration in HIP.
3770A managed variable is emitted as an undefined global symbol in the device binary and is
3771registered by `__hipRegisterManagedVar` in init functions. The HIP runtime allocates
3772managed memory and uses it to define the symbol when loading the device binary.
3773A managed variable can be accessed in both device and host code.)reST";
3774
3775static const char AttrDoc_HLSLAppliedSemantic[] = R"reST()reST";
3776
3777static const char AttrDoc_HLSLAssociatedResourceDecl[] = R"reST()reST";
3778
3779static const char AttrDoc_HLSLColumnMajor[] = R"reST(The `row_major` and `column_major` keywords specify the memory layout
3780of an HLSL matrix type.
3781
3782- `row_major`: Matrices are stored in memory row-by-row.
3783- `column_major`: Matrices are stored in memory column-by-column (default).
3784
3785Example:
3786
3787```hlsl
3788row_major float2x2 myMatrix;
3789```)reST";
3790
3791static const char AttrDoc_HLSLContainedType[] = R"reST(The `hlsl::contained_type` attribute specifies the type of the HLSL resource
3792represented by a member variable of type `__hlsl_resource_t`.
3793
3794This attribute is only valid for resource handles, and is an implementation
3795detail of clang's HLSL implementation. For more information see
3796{doc}`HLSL Resource Types <HLSL/ResourceTypes>`.)reST";
3797
3798static const char AttrDoc_HLSLControlFlowHint[] = R"reST(The `branch` and `flatten` attributes can be applied to *if* and *switch*
3799statements in the HLSL language mode to provide hints for how the backend
3800should execute them.
3801
3802- `branch` means that control flow is preferred. The condition should be
3803 evaluated first and we should only execute the block guarded by it.
3804
3805- `flatten` means that control flow should be avoided. All blocks should be
3806 executed and variables that are modified should be conditionally assigned.
3807
3808These control flow hints are preserved through the compilation and emitted in a
3809backend-specific way.
3810
3811For details, see the Direct3D documentation for [if Statement][if Statement]
3812and [switch Statement][switch Statement].
3813
3814[if Statement]: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-if
3815[switch Statement]: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-switch)reST";
3816
3817static const char AttrDoc_HLSLGroupSharedAddressSpace[] = R"reST(HLSL enables threads of a compute shader to exchange values via shared memory.
3818HLSL provides barrier primitives such as GroupMemoryBarrierWithGroupSync,
3819and so on to ensure the correct ordering of reads and writes to shared memory
3820in the shader and to avoid data races.
3821Here's an example to declare a groupshared variable.
3822
3823```c++
3824groupshared GSData data[5*5*1];
3825```
3826
3827The full documentation is available here: <https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-syntax#group-shared>)reST";
3828
3829static const char AttrDoc_HLSLInterpolationModifier[] = R"reST(The HLSL keywords `nointerpolation`, `linear`, `centroid`,
3830`noperspective`, `sample`, and `center` control interpolation of pixel
3831shader inputs and vertex shader outputs.
3832
3833When applied to an aggregate type, the modifier propagates recursively to every
3834scalar or vector of the type. A modifier on an inner field overrides one
3835inherited from an enclosing declaration.
3836
3837`nointerpolation` cannot be combined with another interpolation modifier.
3838For pixel shader inputs and vertex shader outputs, it cannot be used on
3839`SV_Position`. Integer, boolean, and 64-bit floating-point components only
3840support `nointerpolation`.
3841
3842Unqualified pixel shader inputs and vertex shader outputs default to `linear`
3843for floating-point components of at most 32 bits and `nointerpolation` otherwise.
3844In DirectX signatures, `SV_Position` uses the corresponding `noperspective` mode.
3845Vertex shader inputs, pixel shader outputs, and signatures in other shader
3846stages have no interpolation mode so their interpolation modifiers are ignored.
3847
3848For SPIR-V targets, `nointerpolation`, `noperspective`, `centroid`, and `sample`
3849emit `Flat`, `NoPerspective`, `Centroid`, and `Sample` decorations, respectively.
3850`linear` and `center` use the SPIR-V defaults and require no decoration.
3851Sample-qualified interfaces also require the `SampleRateShading` capability.
3852For `SV_Barycentrics` inputs, `noperspective` selects the `BaryCoordNoPerspKHR`
3853built-in instead of adding a `NoPerspective` decoration; `centroid` and `sample`
3854still decorate the selected built-in.)reST";
3855
3856static const char AttrDoc_HLSLIsArray[] = R"reST(The `hlsl::is_array` attribute specifies that the HLSL resource represented
3857by a member variable of type `__hlsl_resource_t` has array dimensions.
3858
3859This attribute is only valid for resource handles, and is an implementation
3860detail of clang's HLSL implementation. For more information see
3861{doc}`HLSL Resource Types <HLSL/ResourceTypes>`.)reST";
3862
3863static const char AttrDoc_HLSLIsCounter[] = R"reST(The `hlsl::is_counter` attribute specifies that the HLSL resource represented
3864by a member variable of type `__hlsl_resource_t` is a counter buffer.
3865
3866This attribute is only valid for resource handles, and is an implementation
3867detail of clang's HLSL implementation. For more information see
3868{doc}`HLSL Resource Types <HLSL/ResourceTypes>`.)reST";
3869
3870static const char AttrDoc_HLSLIsMultiSampled[] = R"reST(The `hlsl::is_array` attribute specifies that the HLSL resource represented
3871by a member variable of type `__hlsl_resource_t` is multisampled.
3872
3873This attribute is only valid for resource handles, and is an implementation
3874detail of clang's HLSL implementation. For more information see
3875{doc}`HLSL Resource Types <HLSL/ResourceTypes>`.)reST";
3876
3877static const char AttrDoc_HLSLIsROV[] = R"reST(The `hlsl::is_rov` attribute specifies that the HLSL resource represented by
3878a member variable of type `__hlsl_resource_t` is a rasterizer ordered view.
3879
3880This attribute is only valid for resource handles, and is an implementation
3881detail of clang's HLSL implementation. For more information see
3882{doc}`HLSL Resource Types <HLSL/ResourceTypes>`.)reST";
3883
3884static const char AttrDoc_HLSLLoopHint[] = R"reST(The `[loop]` directive allows loop optimization hints to be
3885specified for the subsequent loop. The directive allows unrolling to
3886be disabled and is not compatible with `[unroll(x)]`.
3887
3888Specifying the parameter, `[loop]`, directs the
3889unroller to not unroll the loop.
3890
3891```hlsl
3892[loop]
3893for (...) {
3894 ...
3895}
3896```
3897
3898```hlsl
3899[loop]
3900while (...) {
3901 ...
3902}
3903```
3904
3905```hlsl
3906[loop]
3907do {
3908 ...
3909} while (...)
3910```
3911
3912See [hlsl loop extensions](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-for)
3913for details.)reST";
3914
3915static const char AttrDoc_HLSLNumThreads[] = R"reST(The `numthreads` attribute applies to HLSL shaders where explcit thread counts
3916are required. The `X`, `Y`, and `Z` values provided to the attribute
3917dictate the thread id. Total number of threads executed is `X * Y * Z`.
3918
3919The full documentation is available here: <https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-numthreads>)reST";
3920
3921static const char AttrDoc_HLSLPackOffset[] = R"reST(The packoffset attribute is used to change the layout of a cbuffer.
3922Attribute spelling in HLSL is: `packoffset( c[Subcomponent][.component] )`.
3923A subcomponent is a register number, which is an integer. A component is in the form of [.xyzw].
3924
3925Examples:
3926
3927```hlsl
3928cbuffer A {
3929 float3 a : packoffset(c0.y);
3930 float4 b : packoffset(c4);
3931}
3932```
3933
3934The full documentation is available here: <https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-packoffset>)reST";
3935
3936static const char AttrDoc_HLSLParamModifier[] = R"reST(HLSL function parameters are passed by value. Parameter declarations support
3937three qualifiers to denote parameter passing behavior. The three qualifiers are
3938`in`, `out` and `inout`.
3939
3940Parameters annotated with `in` or with no annotation are passed by value from
3941the caller to the callee.
3942
3943Parameters annotated with `out` are written to the argument after the callee
3944returns (Note: arguments values passed into `out` parameters *are not* copied
3945into the callee).
3946
3947Parameters annotated with `inout` are copied into the callee via a temporary,
3948and copied back to the argument after the callee returns.)reST";
3949
3950static const char AttrDoc_HLSLParsedSemantic[] = R"reST()reST";
3951
3952static const char AttrDoc_HLSLRawBuffer[] = R"reST(The `hlsl::raw_buffer` attribute specifies that the HLSL resource represented
3953by a member variable of type `__hlsl_resource_t` has raw buffer semantics.
3954
3955This attribute is only valid for resource handles, and is an implementation
3956detail of clang's HLSL implementation. For more information see
3957{doc}`HLSL Resource Types <HLSL/ResourceTypes>`.)reST";
3958
3959static const char AttrDoc_HLSLResourceBinding[] = R"reST(The resource binding attribute sets the virtual register and logical register space for a resource.
3960Attribute spelling in HLSL is: `register(slot [, space])`.
3961`slot` takes the format `[type][number]`,
3962where `type` is a single character specifying the resource type and `number` is the virtual register number.
3963
3964Register types are:
3965t for shader resource views (SRV),
3966s for samplers,
3967u for unordered access views (UAV),
3968b for constant buffer views (CBV).
3969
3970Register space is specified in the format `space[number]` and defaults to `space0` if omitted.
3971Here're resource binding examples with and without space:
3972
3973```hlsl
3974RWBuffer<float> Uav : register(u3, space1);
3975Buffer<float> Buf : register(t1);
3976```
3977
3978The full documentation is available here: <https://docs.microsoft.com/en-us/windows/win32/direct3d12/resource-binding-in-hlsl>)reST";
3979
3980static const char AttrDoc_HLSLResourceClass[] = R"reST(The `hlsl::resource_class` attribute specifies the resource class of the HLSL
3981resource represented by a member variable of type `__hlsl_resource_t`,
3982declaring it to be an SRV, UAV, CBuffer, or Sampler resource.
3983
3984This attribute is only valid for resource handles, and is an implementation
3985detail of clang's HLSL implementation. For more information see
3986{doc}`HLSL Resource Types <HLSL/ResourceTypes>`.)reST";
3987
3988static const char AttrDoc_HLSLResourceDimension[] = R"reST(The `hlsl::dimension` attribute specifies the dimensions of the HLSL resource
3989represented by a member variable of type `__hlsl_resource_t`, declaring the
3990resource to have Unknown, 1D, 2D, 3D, or Cube dimension.
3991
3992This attribute is only valid for resource handles, and is an implementation
3993detail of clang's HLSL implementation. For more information see
3994{doc}`HLSL Resource Types <HLSL/ResourceTypes>`.)reST";
3995
3996static const char AttrDoc_HLSLRowMajor[] = R"reST(The `row_major` and `column_major` keywords specify the memory layout
3997of an HLSL matrix type.
3998
3999- `row_major`: Matrices are stored in memory row-by-row.
4000- `column_major`: Matrices are stored in memory column-by-column (default).
4001
4002Example:
4003
4004```hlsl
4005row_major float2x2 myMatrix;
4006```)reST";
4007
4008static const char AttrDoc_HLSLShader[] = R"reST(The `shader` type attribute applies to HLSL shader entry functions to
4009identify the shader type for the entry function.
4010The syntax is:
4011
4012```text
4013[shader(string-literal)]
4014```
4015
4016where the string literal is one of: "pixel", "vertex", "geometry", "hull",
4017"domain", "compute", "raygeneration", "intersection", "anyhit", "closesthit",
4018"miss", "callable", "mesh", "amplification". Normally the shader type is set
4019by shader target with the `-T` option like `-Tps_6_1`. When compiling to a
4020library target like `lib_6_3`, the shader type attribute can help the
4021compiler to identify the shader type. It is mostly used by Raytracing shaders
4022where shaders must be compiled into a library and linked at runtime.)reST";
4023
4024static const char AttrDoc_HLSLUnparsedSemantic[] = R"reST()reST";
4025
4026static const char AttrDoc_HLSLVkBinding[] = R"reST(The `[[vk::binding]]` attribute allows you to explicitly specify the descriptor
4027set and binding for a resource when targeting SPIR-V. This is particularly
4028useful when you need different bindings for SPIR-V and DXIL, as the `register`
4029attribute can be used for DXIL-specific bindings.
4030
4031The attribute takes two integer arguments: the binding and the descriptor set.
4032The descriptor set is optional and defaults to 0 if not provided.
4033
4034```c++
4035// A structured buffer with binding 23 in descriptor set 102.
4036[[vk::binding(23, 102)]] StructuredBuffer<float> Buf;
4037
4038// A structured buffer with binding 14 in descriptor set 0.
4039[[vk::binding(14)]] StructuredBuffer<float> Buf2;
4040
4041// A cbuffer with binding 1 in descriptor set 2.
4042[[vk::binding(1, 2)]] cbuffer MyCBuffer {
4043 float4x4 worldViewProj;
4044};
4045```)reST";
4046
4047static const char AttrDoc_HLSLVkBuiltIn[] = R"reST(Some Vulkan built-in variables have no equivalent in native HLSL, so no
4048system-value semantic can express them. The `[[vk::builtin]]` attribute marks a
4049stage input/output variable as a SPIR-V built-in variable, identified by name.
4050Allowed on function parameters, function returns, and struct fields. This
4051attribute has no effect when used outside of an entrypoint parameter/parameter
4052field/return value.
4053
4054The attribute is only available when targeting SPIR-V. For any other target it
4055is ignored with an "unknown attribute ignored" warning.
4056
4057The attribute takes a single string literal argument naming the built-in.
4058Currently supported built-ins:
4059
4060* `PointSize`: the GLSL equivalent is `gl_PointSize`. Must be a scalar
4061 `float`, or a `half` when native 16-bit types are not enabled (it is then
4062 treated as `float`). Can be used as a vertex or mesh shader output, or as a
4063 hull, domain or geometry shader input or output. It cannot be used in a pixel
4064 shader.
4065
4066A declaration annotated with `[[vk::builtin]]` does not take part in
4067`vk::location` assignment, and cannot also be annotated with `[[vk::location]]`.
4068
4069```c++
4070struct VSOutput {
4071 [[vk::location(0)]] float4 color : COLOR;
4072 [[vk::builtin("PointSize")]] float size : PSIZE;
4073};
4074```)reST";
4075
4076static const char AttrDoc_HLSLVkConstantId[] = R"reST(The `vk::constant_id` attribute specifies the id for a SPIR-V specialization
4077constant. The attribute applies to const global scalar variables. The variable must be initialized with a C++11 constexpr.
4078In SPIR-V, the
4079variable will be replaced with an `OpSpecConstant` with the given id.
4080The syntax is:
4081
4082```text
4083[[vk::constant_id(<Id>)]] const T Name = <Init>
4084```)reST";
4085
4086static const char AttrDoc_HLSLVkExtBuiltinInput[] = R"reST(Vulkan shaders have `Input` builtins. Those variables are externally
4087initialized by the driver/pipeline, but each copy is private to the current
4088lane.
4089
4090Those builtins can be declared using the `[[vk::ext_builtin_input]]` attribute
4091like follows:
4092
4093```c++
4094[[vk::ext_builtin_input(/* WorkgroupId */ 26)]]
4095static const uint3 groupid;
4096```
4097
4098This variable will be lowered into a module-level variable, with the `Input`
4099storage class, and the `BuiltIn 26` decoration.
4100
4101The full documentation for this inline SPIR-V attribute can be found here:
4102<https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md>)reST";
4103
4104static const char AttrDoc_HLSLVkExtBuiltinOutput[] = R"reST(Vulkan shaders have `Output` builtins. Those variables are externally
4105visible to the driver/pipeline, but each copy is private to the current
4106lane.
4107
4108Those builtins can be declared using the `[[vk::ext_builtin_output]]`
4109attribute like follows:
4110
4111```c++
4112[[vk::ext_builtin_output(/* Position */ 0)]]
4113static float4 position;
4114```
4115
4116This variable will be lowered into a module-level variable, with the `Output`
4117storage class, and the `BuiltIn 0` decoration.
4118
4119The full documentation for this inline SPIR-V attribute can be found here:
4120<https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md>)reST";
4121
4122static const char AttrDoc_HLSLVkLocation[] = R"reST(Attribute used for specifying the location number for the stage input/output
4123variables. Allowed on function parameters, function returns, and struct
4124fields. This parameter has no effect when used outside of an entrypoint
4125parameter/parameter field/return value.
4126
4127This attribute maps to the `Location` SPIR-V decoration.)reST";
4128
4129static const char AttrDoc_HLSLVkPushConstant[] = R"reST(Vulkan shaders have `PushConstants`
4130
4131The `[[vk::push_constant]]` attribute allows you to declare this
4132global variable as a push constant when targeting Vulkan.
4133This attribute is ignored otherwise.
4134
4135This attribute must be applied to the variable, not underlying type.
4136The variable type must be a struct, per the requirements of Vulkan, "there
4137must be no more than one push constant block statically used per shader entry
4138point.")reST";
4139
4140static const char AttrDoc_HLSLWaveSize[] = R"reST(The `WaveSize` attribute specifies a wave size on a shader entry point in order
4141to indicate either that a shader depends on or strongly prefers a specific wave
4142size.
4143There're 2 versions of the attribute: `WaveSize` and `RangedWaveSize`.
4144The syntax for `WaveSize` is:
4145
4146```text
4147[WaveSize(<numLanes>)]
4148```
4149
4150The allowed wave sizes that an HLSL shader may specify are the powers of 2
4151between 4 and 128, inclusive.
4152In other words, the set: [4, 8, 16, 32, 64, 128].
4153
4154The syntax for `RangedWaveSize` is:
4155
4156```text
4157[WaveSize(<minWaveSize>, <maxWaveSize>, [prefWaveSize])]
4158```
4159
4160Where minWaveSize is the minimum wave size supported by the shader representing
4161the beginning of the allowed range, maxWaveSize is the maximum wave size
4162supported by the shader representing the end of the allowed range, and
4163prefWaveSize is the optional preferred wave size representing the size expected
4164to be the most optimal for this shader.
4165
4166`WaveSize` is available for HLSL shader model 6.6 and later.
4167`RangedWaveSize` available for HLSL shader model 6.8 and later.
4168
4169The full documentation is available here: <https://microsoft.github.io/DirectX-Specs/d3d/HLSL_SM_6_6_WaveSize.html>
4170and <https://microsoft.github.io/hlsl-specs/proposals/0013-wave-size-range.html>)reST";
4171
4172static const char AttrDoc_HexagonHLXVectorStackLimit[] = R"reST(The ``hlx_vector_stack_limit`` attribute (Hexagon only) sets a limit, in bytes,
4173on the HLX vector stack frame of a function. HLX vectors that are stored on the
4174stack are placed on a separate stack in VTCM. If the function needs a larger
4175vector stack frame, the compiler reports an error.
4176
4177The attribute overrides the limit set with ``-fhlx-vector-stack-limit=<bytes>``.
4178
4179.. code-block:: c
4180
4181 void foo(void) __attribute__((hlx_vector_stack_limit(8192)));)reST";
4182
4183static const char AttrDoc_Hot[] = R"reST(`__attribute__((hot))` marks a function as hot, as a manual alternative to PGO hotness data.
4184If PGO data is available, the annotation `__attribute__((hot))` overrides the profile count based hotness (unlike `__attribute__((cold))`).)reST";
4185
4186static const char AttrDoc_HybridPatchable[] = R"reST(The `hybrid_patchable` attribute declares an ARM64EC function with an additional
4187x86-64 thunk, which may be patched at runtime.
4188
4189For more information see
4190[ARM64EC ABI documentation](https://learn.microsoft.com/en-us/windows/arm/arm64ec-abi).)reST";
4191
4192static const char AttrDoc_IBAction[] = R"reST(No documentation.)reST";
4193
4194static const char AttrDoc_IBOutlet[] = R"reST(No documentation.)reST";
4195
4196static const char AttrDoc_IBOutletCollection[] = R"reST(No documentation.)reST";
4197
4198static const char AttrDoc_IFunc[] = R"reST(`__attribute__((ifunc("resolver")))` is used to mark that the address of a
4199declaration should be resolved at runtime by calling a resolver function.
4200
4201The symbol name of the resolver function is given in quotes. A function with
4202this name (after mangling) must be defined in the current translation unit; it
4203may be `static`. The resolver function should return a pointer.
4204
4205The `ifunc` attribute may only be used on a function declaration. A function
4206declaration with an `ifunc` attribute is considered to be a definition of the
4207declared entity. The entity must not have weak linkage; for example, in C++,
4208it cannot be applied to a declaration if a definition at that location would be
4209considered inline.
4210
4211Not all targets support this attribute:
4212
4213- ELF target support depends on both the linker and runtime linker, and is
4214 available in at least lld 4.0 and later, binutils 2.20.1 and later, glibc
4215 v2.11.1 and later, and FreeBSD 9.1 and later.
4216- Mach-O targets support it, but with slightly different semantics: the resolver
4217 is run at first call, instead of at load time by the runtime linker.
4218- Windows target supports it on AArch64, but with different semantics: the
4219 `ifunc` is replaced with a global function pointer, and the call is replaced
4220 with an indirect call. The function pointer is initialized by a constructor
4221 that calls the resolver.
4222- Baremetal target supports it on AVR.
4223- AIX/XCOFF supports it via a compiler-only solution. An ifunc appears as a
4224 regular function (has an entry point `.foo[PR]` and a function descriptor
4225 `foo[DS]`). The entry point is a stub that branches to the function address
4226 in the descriptor, and the descriptor is initialized via a constructor
4227 function (`__init_ifuncs`) that is linked into every shared object and
4228 executable. `__init_ifuncs` calls the resolver of each ifunc and stores the
4229 result in the corresponding descriptor.
4230- Other targets currently do not support this attribute.)reST";
4231
4232static const char AttrDoc_InferredNoReturn[] = R"reST()reST";
4233
4234static const char AttrDoc_InitPriority[] = R"reST(In C++, the order in which global variables are initialized across translation
4235units is unspecified, unlike the ordering within a single translation unit. The
4236`init_priority` attribute allows you to specify a relative ordering for the
4237initialization of objects declared at namespace scope in C++ within a single
4238linked image on supported platforms. The priority is given as an integer constant
4239expression between 101 and 65535 (inclusive). Priorities outside of that range are
4240reserved for use by the implementation. A lower value indicates a higher priority
4241of initialization. Note that only the relative ordering of values is important.
4242For example:
4243
4244```c++
4245struct SomeType { SomeType(); };
4246__attribute__((init_priority(200))) SomeType Obj1;
4247__attribute__((init_priority(101))) SomeType Obj2;
4248```
4249
4250`Obj2` will be initialized *before* `Obj1` despite the usual order of
4251initialization being the opposite.
4252
4253Note that this attribute does not control the initialization order of objects
4254across final linked image boundaries like shared objects and executables.
4255
4256On Windows, `init_seg(compiler)` is represented with a priority of 200 and
4257`init_seg(library)` is represented with a priority of 400. `init_seg(user)`
4258uses the default 65535 priority.
4259
4260On MachO platforms, this attribute also does not control the order of initialization
4261across translation units, where it only affects the order within a single TU.
4262
4263This attribute is only supported for C++ and Objective-C++ and is ignored in
4264other language modes.)reST";
4265
4266static const char AttrDoc_InitSeg[] = R"reST(The attribute applied by `pragma init_seg()` controls the section into
4267which global initialization function pointers are emitted. It is only
4268available with `-fms-extensions`. Typically, this function pointer is
4269emitted into `.CRT$XCU` on Windows. The user can change the order of
4270initialization by using a different section name with the same
4271`.CRT$XC` prefix and a suffix that sorts lexicographically before or
4272after the standard `.CRT$XCU` sections. See the [init_seg][init_seg]
4273documentation on MSDN for more information.
4274
4275[init_seg]: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx)reST";
4276
4277static const char AttrDoc_IntelOclBicc[] = R"reST(No documentation.)reST";
4278
4279static const char AttrDoc_InternalLinkage[] = R"reST(The `internal_linkage` attribute changes the linkage type of the declaration
4280to internal. This is similar to C-style `static`, but can be used on classes
4281and class methods. When applied to a class definition, this attribute affects
4282all methods and static data members of that class. This can be used to contain
4283the ABI of a C++ library by excluding unwanted class methods from the export
4284tables.)reST";
4285
4286static const char AttrDoc_LTOVisibilityPublic[] = R"reST(See {doc}`LTOVisibility`.)reST";
4287
4288static const char AttrDoc_LayoutVersion[] = R"reST(The layout_version attribute requests that the compiler utilize the class
4289layout rules of a particular compiler version.
4290This attribute only applies to struct, class, and union types.
4291It is only supported when using the Microsoft C++ ABI.)reST";
4292
4293static const char AttrDoc_Leaf[] = R"reST(The `leaf` attribute is used as a compiler hint to improve dataflow analysis
4294in library functions. Functions marked with the `leaf` attribute are not allowed
4295to jump back into the caller's translation unit, whether through invoking a
4296callback function, an external function call, use of `longjmp`, or other means.
4297Therefore, they cannot use or modify any data that does not escape the caller function's
4298compilation unit.
4299
4300For more information see the
4301[GCC common attributes documentation](https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html))reST";
4302
4303static const char AttrDoc_LifetimeBound[] = R"reST(The `lifetimebound` attribute on a function parameter or implicit object
4304parameter indicates that objects that are referred to by that parameter may
4305also be referred to by the return value of the annotated function (or, for a
4306parameter of a constructor, by the value of the constructed object).
4307
4308By default, a reference is considered to refer to its referenced object, a
4309pointer is considered to refer to its pointee, a `std::initializer_list<T>`
4310is considered to refer to its underlying array, and aggregates (arrays and
4311simple `struct`s) are considered to refer to all objects that their
4312transitive subobjects refer to.
4313
4314Clang warns if it is able to detect that an object or reference refers to
4315another object with a shorter lifetime. For example, Clang will warn if a
4316function returns a reference to a local variable, or if a reference is bound to
4317a temporary object whose lifetime is not extended. By using the
4318`lifetimebound` attribute, this determination can be extended to look through
4319user-declared functions. For example:
4320
4321```c++
4322#include <map>
4323#include <string>
4324
4325using namespace std::literals;
4326
4327// Returns m[key] if key is present, or default_value if not.
4328template<typename T, typename U>
4329const U &get_or_default(const std::map<T, U> &m [[clang::lifetimebound]],
4330 const T &key, /* note, not lifetimebound */
4331 const U &default_value [[clang::lifetimebound]]) {
4332 if (auto iter = m.find(key); iter != m.end()) return iter->second;
4333 else return default_value;
4334}
4335
4336int main() {
4337 std::map<std::string, std::string> m;
4338 // warning: temporary bound to local reference 'val1' will be destroyed
4339 // at the end of the full-expression
4340 const std::string &val1 = get_or_default(m, "foo"s, "bar"s);
4341
4342 // No warning in this case.
4343 std::string def_val = "bar"s;
4344 const std::string &val2 = get_or_default(m, "foo"s, def_val);
4345
4346 return 0;
4347}
4348```
4349
4350The attribute can be applied to the implicit `this` parameter of a member
4351function by writing the attribute after the function type:
4352
4353```c++
4354struct string {
4355 // The returned pointer should not outlive '*this'.
4356 const char *data() const [[clang::lifetimebound]];
4357};
4358```
4359
4360This attribute is inspired by the C++ committee paper [P0936R0](http://wg21.link/p0936r0), but does not affect whether temporary objects
4361have their lifetimes extended.)reST";
4362
4363static const char AttrDoc_LifetimeCaptureBy[] = R"reST(Similar to [lifetimebound], the `lifetime_capture_by` attribute family on a
4364function parameter or implicit object parameter indicates that a capturing
4365entity may refer to the object referred to by that parameter. The capturing
4366entity can be named in `lifetime_capture_by(X)` or selected by one of the
4367standalone special forms listed below.
4368
4369Below is a list of types of the parameters and what they're considered to refer to:
4370
4371- A reference param (of non-view type) is considered to refer to its referenced object.
4372- A pointer param (of non-view type) is considered to refer to its pointee.
4373- View type param (type annotated with `[[gsl::Pointer()]]`) is considered to refer
4374 to its pointee (gsl owner). This holds true even if the view type appears as a reference
4375 in the parameter. For example, both `std::string_view` and
4376 `const std::string_view &` are considered to refer to a `std::string`.
4377- A `std::initializer_list<T>` is considered to refer to its underlying array.
4378- Aggregates (arrays and simple `struct`s) are considered to refer to all
4379 objects that their transitive subobjects refer to.
4380
4381Clang would diagnose when a temporary object is used as an argument to such an
4382annotated parameter.
4383In this case, the capturing entity `X` could capture a dangling reference to this
4384temporary object.
4385
4386```c++
4387void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
4388 s.insert(a);
4389}
4390void use() {
4391 std::set<std::string_view> s;
4392 addToSet(std::string(), s); // Warning: object whose reference is captured by 's' will be destroyed at the end of the full-expression.
4393 // ^^^^^^^^^^^^^
4394 std::string local;
4395 addToSet(local, s); // Ok.
4396}
4397```
4398
4399The capturing entity can be one of the following:
4400
4401- Another (named) function parameter.
4402
4403 ```c++
4404 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
4405 s.insert(a);
4406 }
4407 ```
4408
4409- `this` (in case of member functions), written as
4410 `lifetime_capture_by_this`.
4411
4412 ```c++
4413 class S {
4414 void addToSet(std::string_view a [[clang::lifetime_capture_by_this]]) {
4415 s.insert(a);
4416 }
4417 std::set<std::string_view> s;
4418 };
4419 ```
4420
4421 Note: When applied to a constructor parameter, `[[clang::lifetime_capture_by_this]]` is just an alias of `[[clang::lifetimebound]]`.
4422
4423- `global` and `unknown`, written as `lifetime_capture_by_global` and
4424 `lifetime_capture_by_unknown` respectively.
4425
4426 ```c++
4427 std::set<std::string_view> s;
4428 void addToSet(std::string_view a [[clang::lifetime_capture_by_global]]) {
4429 s.insert(a);
4430 }
4431 void addSomewhere(std::string_view a [[clang::lifetime_capture_by_unknown]]);
4432 ```
4433
4434The attribute can be applied to the implicit `this` parameter of a member
4435function by writing the attribute after the function type:
4436
4437```c++
4438struct S {
4439 const char *data(std::set<S*>& s) [[clang::lifetime_capture_by(s)]] {
4440 s.insert(this);
4441 }
4442};
4443```
4444
4445The parameter-list form supports specifying more than one capturing entity:
4446
4447```c++
4448void addToSets(std::string_view a [[clang::lifetime_capture_by(s1, s2)]],
4449 std::set<std::string_view>& s1,
4450 std::set<std::string_view>& s2) {
4451 s1.insert(a);
4452 s2.insert(a);
4453}
4454```
4455
4456Distinct `lifetime_capture_by` forms can also be combined on the same
4457declaration, but each form can appear at most once. For example,
4458`[[clang::lifetime_capture_by(s), clang::lifetime_capture_by_this]]` is
4459allowed, but two `[[clang::lifetime_capture_by(...)]]` attributes or two
4460`[[clang::lifetime_capture_by_this]]` attributes on the same declaration are
4461rejected.
4462
4463Limitation: The capturing entity `X` is not used by the analysis and is
4464used for documentation purposes only. This is because the analysis is
4465statement-local and only detects use of a temporary as an argument to the
4466annotated parameter.
4467
4468```c++
4469void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s);
4470void use() {
4471 std::set<std::string_view> s;
4472 if (foo()) {
4473 std::string str;
4474 addToSet(str, s); // Not detected.
4475 }
4476}
4477```)reST";
4478
4479static const char AttrDoc_Likely[] = R"reST(The `likely` and `unlikely` attributes are used as compiler hints.
4480The attributes are used to aid the compiler to determine which branch is
4481likely or unlikely to be taken. This is done by marking the branch substatement
4482with one of the two attributes.
4483
4484It isn't allowed to annotate a single statement with both `likely` and
4485`unlikely`. Annotating the `true` and `false` branch of an `if`
4486statement with the same likelihood attribute will result in a diagnostic and
4487the attributes are ignored on both branches.
4488
4489In a `switch` statement it's allowed to annotate multiple `case` labels
4490or the `default` label with the same likelihood attribute. This makes
4491\* all labels without an attribute have a neutral likelihood,
4492\* all labels marked `[[likely]]` have an equally positive likelihood, and
4493\* all labels marked `[[unlikely]]` have an equally negative likelihood.
4494The neutral likelihood is the more likely of path execution than the negative
4495likelihood. The positive likelihood is the more likely of path of execution
4496than the neutral likelihood.
4497
4498These attributes have no effect on the generated code when using
4499PGO (Profile-Guided Optimization) or at optimization level 0.
4500
4501In Clang, the attributes will be ignored if they're not placed on
4502\* the `case` or `default` label of a `switch` statement,
4503\* or on the substatement of an `if` or `else` statement,
4504\* or on the substatement of an `for` or `while` statement.
4505The C++ Standard recommends to honor them on every statement in the
4506path of execution, but that can be confusing:
4507
4508```c++
4509if (b) {
4510 [[unlikely]] --b; // Per the standard this is in the path of
4511 // execution, so this branch should be considered
4512 // unlikely. However, Clang ignores the attribute
4513 // here since it is not on the substatement.
4514}
4515
4516if (b) {
4517 --b;
4518 if(b)
4519 return;
4520 [[unlikely]] --b; // Not in the path of execution,
4521} // the branch has no likelihood information.
4522
4523if (b) {
4524 --b;
4525 foo(b);
4526 // Whether or not the next statement is in the path of execution depends
4527 // on the declaration of foo():
4528 // In the path of execution: void foo(int);
4529 // Not in the path of execution: [[noreturn]] void foo(int);
4530 // This means the likelihood of the branch depends on the declaration
4531 // of foo().
4532 [[unlikely]] --b;
4533}
4534```
4535
4536Below are some example usages of the likelihood attributes and their effects:
4537
4538```c++
4539if (b) [[likely]] { // Placement on the first statement in the branch.
4540 // The compiler will optimize to execute the code here.
4541} else {
4542}
4543
4544if (b)
4545 [[unlikely]] b++; // Placement on the first statement in the branch.
4546else {
4547 // The compiler will optimize to execute the code here.
4548}
4549
4550if (b) {
4551 [[unlikely]] b++; // Placement on the second statement in the branch.
4552} // The attribute will be ignored.
4553
4554if (b) [[likely]] {
4555 [[unlikely]] b++; // No contradiction since the second attribute
4556} // is ignored.
4557
4558if (b)
4559 ;
4560else [[likely]] {
4561 // The compiler will optimize to execute the code here.
4562}
4563
4564if (b)
4565 ;
4566else
4567 // The compiler will optimize to execute the next statement.
4568 [[likely]] b = f();
4569
4570if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
4571else [[likely]]; // and the attributes are ignored.
4572
4573if (b)
4574 [[likely]] int i = 5; // Issues a diagnostic since the attribute
4575 // isn't allowed on a declaration.
4576
4577switch (i) {
4578 [[likely]] case 1: // This value is likely
4579 ...
4580 break;
4581
4582 [[unlikely]] case 2: // This value is unlikely
4583 ...
4584 [[fallthrough]];
4585
4586 case 3: // No likelihood attribute
4587 ...
4588 [[likely]] break; // No effect
4589
4590 case 4: [[likely]] { // attribute on substatement has no effect
4591 ...
4592 break;
4593 }
4594
4595 [[unlikely]] default: // All other values are unlikely
4596 ...
4597 break;
4598}
4599
4600switch (i) {
4601 [[likely]] case 0: // This value and code path is likely
4602 ...
4603 [[fallthrough]];
4604
4605 case 1: // No likelihood attribute, code path is neutral
4606 break; // falling through has no effect on the likelihood
4607
4608 case 2: // No likelihood attribute, code path is neutral
4609 [[fallthrough]];
4610
4611 [[unlikely]] default: // This value and code path are both unlikely
4612 break;
4613}
4614
4615for(int i = 0; i != size; ++i) [[likely]] {
4616 ... // The loop is the likely path of execution
4617}
4618
4619for(const auto &E : Elements) [[likely]] {
4620 ... // The loop is the likely path of execution
4621}
4622
4623while(i != size) [[unlikely]] {
4624 ... // The loop is the unlikely path of execution
4625} // The generated code will optimize to skip the loop body
4626
4627while(true) [[unlikely]] {
4628 ... // The attribute has no effect
4629} // Clang elides the comparison and generates an infinite
4630 // loop
4631```)reST";
4632
4633static const char AttrDoc_LoaderUninitialized[] = R"reST(The `loader_uninitialized` attribute can be placed on global variables to
4634indicate that the variable does not need to be zero initialized by the loader.
4635On most targets, zero-initialization does not incur any additional cost.
4636For example, most general purpose operating systems deliberately ensure
4637that all memory is properly initialized in order to avoid leaking privileged
4638information from the kernel or other programs. However, some targets
4639do not make this guarantee, and on these targets, avoiding an unnecessary
4640zero-initialization can have a significant impact on load times and/or code
4641size.
4642
4643A declaration with this attribute is a non-tentative definition just as if it
4644provided an initializer. Variables with this attribute are considered to be
4645uninitialized in the same sense as a local variable, and the programs must
4646write to them before reading from them. If the variable's type is a C++ class
4647type with a non-trivial default constructor, or an array thereof, this attribute
4648only suppresses the static zero-initialization of the variable, not the dynamic
4649initialization provided by executing the default constructor.)reST";
4650
4651static const char AttrDoc_LockReturned[] = R"reST(No documentation.)reST";
4652
4653static const char AttrDoc_LocksExcluded[] = R"reST(No documentation.)reST";
4654
4655static const char AttrDoc_LoopHint[] = R"reST(The `#pragma clang loop` directive allows loop optimization hints to be
4656specified for the subsequent loop. The directive allows pipelining to be
4657disabled, or vectorization, vector predication, interleaving, and unrolling to
4658be enabled or disabled. Vector width, vector predication, interleave count,
4659unrolling count, and the initiation interval for pipelining can be explicitly
4660specified. See
4661{ref}`loop hint optimizations <langext-loop-hint-optimizations>` for details.)reST";
4662
4663static const char AttrDoc_M68kInterrupt[] = R"reST(No documentation.)reST";
4664
4665static const char AttrDoc_M68kRTD[] = R"reST(On M68k targets, this attribute changes the calling convention of a function
4666to clear parameters off the stack on return. In other words, callee is
4667responsible for cleaning out the stack space allocated for incoming paramters.
4668This convention does not support variadic calls or unprototyped functions in C.
4669When targeting M68010 or newer CPUs, this calling convention is implemented
4670using the `rtd` instruction.)reST";
4671
4672static const char AttrDoc_MIGServerRoutine[] = R"reST(The Mach Interface Generator release-on-success convention dictates
4673
4674functions that follow it to only release arguments passed to them when they
4675return "success" (a `kern_return_t` error code that indicates that
4676no errors have occurred). Otherwise the release is performed by the MIG client
4677that called the function. The annotation `__attribute__((mig_server_routine))`
4678is applied in order to specify which functions are expected to follow the
4679convention. This allows the Static Analyzer to find bugs caused by violations of
4680that convention. The attribute would normally appear on the forward declaration
4681of the actual server routine in the MIG server header, but it may also be
4682added to arbitrary functions that need to follow the same convention - for
4683example, a user can add them to auxiliary functions called by the server routine
4684that have their return value of type `kern_return_t` unconditionally returned
4685from the routine. The attribute can be applied to C++ methods, and in this case
4686it will be automatically applied to overrides if the method is virtual. The
4687attribute can also be written using C++11 syntax: `[[mig::server_routine]]`.)reST";
4688
4689static const char AttrDoc_MSABI[] = R"reST(On non-Windows x86_64 and aarch64 targets, this attribute changes the calling convention of
4690a function to match the default convention used on Windows. This
4691attribute has no effect on Windows targets or non-x86_64, non-aarch64 targets.)reST";
4692
4693static const char AttrDoc_MSAllocator[] = R"reST(The `__declspec(allocator)` attribute is applied to functions that allocate
4694memory, such as operator new in C++. When CodeView debug information is emitted
4695(enabled by `clang -gcodeview` or `clang-cl /Z7`), Clang will attempt to
4696record the code offset of heap allocation call sites in the debug info. It will
4697also record the type being allocated using some local heuristics. The Visual
4698Studio debugger uses this information to [profile memory usage][profile memory usage].
4699
4700This attribute does not affect optimizations in any way, unlike GCC's
4701`__attribute__((malloc))`.
4702
4703[profile memory usage]: https://docs.microsoft.com/en-us/visualstudio/profiling/memory-usage)reST";
4704
4705static const char AttrDoc_MSConstexpr[] = R"reST(The `[[msvc::constexpr]]` attribute can be applied only to a function
4706definition or a `return` statement. It does not impact function declarations.
4707A `[[msvc::constexpr]]` function cannot be `constexpr` or `consteval`.
4708A `[[msvc::constexpr]]` function is treated as if it were a `constexpr` function
4709when it is evaluated in a constant context of `[[msvc::constexpr]] return` statement.
4710Otherwise, it is treated as a regular function.
4711
4712Semantics of this attribute are enabled only under MSVC compatibility
4713(`-fms-compatibility-version`) 19.33 and later.)reST";
4714
4715static const char AttrDoc_MSInheritance[] = R"reST(This collection of keywords is enabled under `-fms-extensions` and controls
4716the pointer-to-member representation used on `*-*-win32` targets.
4717
4718The `*-*-win32` targets utilize a pointer-to-member representation which
4719varies in size and alignment depending on the definition of the underlying
4720class.
4721
4722However, this is problematic when a forward declaration is only available and
4723no definition has been made yet. In such cases, Clang is forced to utilize the
4724most general representation that is available to it.
4725
4726These keywords make it possible to use a pointer-to-member representation other
4727than the most general one regardless of whether or not the definition will ever
4728be present in the current translation unit.
4729
4730This family of keywords belong between the `class-key` and `class-name`:
4731
4732```c++
4733struct __single_inheritance S;
4734int S::*i;
4735struct S {};
4736```
4737
4738This keyword can be applied to class templates but only has an effect when used
4739on full specializations:
4740
4741```c++
4742template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
4743template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
4744template <> struct __single_inheritance A<int, float>;
4745```
4746
4747Note that choosing an inheritance model less general than strictly necessary is
4748an error:
4749
4750```c++
4751struct __multiple_inheritance S; // error: inheritance model does not match definition
4752int S::*i;
4753struct S {};
4754```)reST";
4755
4756static const char AttrDoc_MSNoVTable[] = R"reST(This attribute can be added to a class declaration or definition to signal to
4757the compiler that constructors and destructors will not reference the virtual
4758function table. It is only supported when using the Microsoft C++ ABI.)reST";
4759
4760static const char AttrDoc_MSP430Interrupt[] = R"reST(No documentation.)reST";
4761
4762static const char AttrDoc_MSStruct[] = R"reST(The `ms_struct` and `gcc_struct` attributes request the compiler to enter a
4763special record layout compatibility mode which mimics the layout of Microsoft or
4764Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the
4765requested ABI, the attribute does nothing. However, if it does not, annotated
4766structure or class is laid out in a special compatibility mode, which slightly
4767changes offsets for fields and bit-fields. The intention is to match the layout
4768of the requested ABI for structures which only use C features.
4769
4770Note that the default behavior can be controlled by `-mms-bitfields` and
4771`-mno-ms-bitfields` switches and via `#pragma ms_struct`.
4772
4773The primary difference is for bitfields, where the MS variant only packs
4774adjacent fields into the same allocation unit if they have integral types
4775of the same size, while the GCC/Itanium variant packs all fields in a bitfield
4776tightly.)reST";
4777
4778static const char AttrDoc_MSVtorDisp[] = R"reST()reST";
4779
4780static const char AttrDoc_MallocSpan[] = R"reST(The `malloc_span` attribute can be used to mark that a function which acts
4781like a system memory allocation function and returns a span-like structure,
4782where the returned memory range does not alias storage from any other object
4783accessible to the caller.
4784
4785In this context, a span-like structure is assumed to have two non-static data
4786members, one of which is a pointer to the start of the allocated memory and
4787the other one is either an integer type containing the size of the actually
4788allocated memory or a pointer to the end of the allocated region. Note, static
4789data members do not impact whether a type is span-like or not.
4790
4791In combination with the `alloc_size` attribute, if the begin pointer is
4792non-null, the size of the returned span-like object has to be greater or equal
4793to the number of bytes guaranteed to be dereferenceable by `alloc_size`. It also
4794guarantees that the number of dereferenceable bytes is at least size.)reST";
4795
4796static const char AttrDoc_MaxFieldAlignment[] = R"reST()reST";
4797
4798static const char AttrDoc_MayAlias[] = R"reST(No documentation.)reST";
4799
4800static const char AttrDoc_MaybeUndef[] = R"reST(The `maybe_undef` attribute can be placed on a function parameter. It indicates
4801that the parameter is allowed to use undef values. It informs the compiler
4802to insert a freeze LLVM IR instruction on the function parameter.
4803Please note that this is an attribute that is used as an internal
4804implementation detail and not intended to be used by external users.
4805
4806In languages HIP, CUDA etc., some functions have multi-threaded semantics and
4807it is enough for only one or some threads to provide defined arguments.
4808Depending on semantics, undef arguments in some threads don't produce
4809undefined results in the function call. Since, these functions accept undefined
4810arguments, `maybe_undef` attribute can be placed.
4811
4812Sample usage:
4813
4814```c
4815void maybeundeffunc(int __attribute__((maybe_undef))param);
4816```)reST";
4817
4818static const char AttrDoc_MicroMips[] = R"reST(Clang supports the GNU style `__attribute__((micromips))` and
4819`__attribute__((nomicromips))` attributes on MIPS targets. These attributes
4820may be attached to a function definition and instructs the backend to generate
4821or not to generate microMIPS code for that function.
4822
4823These attributes override the `-mmicromips` and `-mno-micromips` options
4824on the command line.)reST";
4825
4826static const char AttrDoc_MinSize[] = R"reST(This function attribute indicates that optimization passes and code generator passes
4827make choices that keep the function code size as small as possible. Optimizations may
4828also sacrifice runtime performance in order to minimize the size of the generated code.)reST";
4829
4830static const char AttrDoc_MinVectorWidth[] = R"reST(Clang supports the `__attribute__((min_vector_width(width)))` attribute. This
4831attribute may be attached to a function and informs the backend that this
4832function desires vectors of at least this width to be generated. Target-specific
4833maximum vector widths still apply. This means even if you ask for something
4834larger than the target supports, you will only get what the target supports.
4835This attribute is meant to be a hint to control target heuristics that may
4836generate narrower vectors than what the target hardware supports.
4837
4838This is currently used by the X86 target to allow some CPUs that support 512-bit
4839vectors to be limited to using 256-bit vectors to avoid frequency penalties.
4840This is currently enabled with the `-prefer-vector-width=256` command line
4841option. The `min_vector_width` attribute can be used to prevent the backend
4842from trying to split vector operations to match the `prefer-vector-width`. All
4843X86 vector intrinsics from x86intrin.h already set this attribute. Additionally,
4844use of any of the X86-specific vector builtins will implicitly set this
4845attribute on the calling function. The intent is that explicitly writing vector
4846code using the X86 intrinsics will prevent `prefer-vector-width` from
4847affecting the code.)reST";
4848
4849static const char AttrDoc_Mips16[] = R"reST(No documentation.)reST";
4850
4851static const char AttrDoc_MipsInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt("ARGUMENT")))` attribute on
4852MIPS targets. This attribute may be attached to a function definition and instructs
4853the backend to generate appropriate function entry/exit code so that it can be used
4854directly as an interrupt service routine.
4855
4856By default, the compiler will produce a function prologue and epilogue suitable for
4857an interrupt service routine that handles an External Interrupt Controller (eic)
4858generated interrupt. This behavior can be explicitly requested with the "eic"
4859argument.
4860
4861Otherwise, for use with vectored interrupt mode, the argument passed should be
4862of the form "vector=LEVEL" where LEVEL is one of the following values:
4863"sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will
4864then set the interrupt mask to the corresponding level which will mask all
4865interrupts up to and including the argument.
4866
4867The semantics are as follows:
4868
4869- The prologue is modified so that the Exception Program Counter (EPC) and
4870 Status coprocessor registers are saved to the stack. The interrupt mask is
4871 set so that the function can only be interrupted by a higher priority
4872 interrupt. The epilogue will restore the previous values of EPC and Status.
4873- The prologue and epilogue are modified to save and restore all non-kernel
4874 registers as necessary.
4875- The FPU is disabled in the prologue, as the floating pointer registers are not
4876 spilled to the stack.
4877- The function return sequence is changed to use an exception return instruction.
4878- The parameter sets the interrupt mask for the function corresponding to the
4879 interrupt level specified. If no mask is specified the interrupt mask
4880 defaults to "eic".)reST";
4881
4882static const char AttrDoc_MipsLongCall[] = R"reST(Clang supports the `__attribute__((long_call))`, `__attribute__((far))`,
4883and `__attribute__((near))` attributes on MIPS targets. These attributes may
4884only be added to function declarations and change the code generated
4885by the compiler when directly calling the function. The `near` attribute
4886allows calls to the function to be made using the `jal` instruction, which
4887requires the function to be located in the same naturally aligned 256MB
4888segment as the caller. The `long_call` and `far` attributes are synonyms
4889and require the use of a different call sequence that works regardless
4890of the distance between the functions.
4891
4892These attributes have no effect for position-independent code.
4893
4894These attributes take priority over command line switches such
4895as `-mlong-calls` and `-mno-long-calls`.)reST";
4896
4897static const char AttrDoc_MipsShortCall[] = R"reST(Clang supports the `__attribute__((long_call))`, `__attribute__((far))`,
4898`__attribute__((short__call))`, and `__attribute__((near))` attributes
4899on MIPS targets. These attributes may only be added to function declarations
4900and change the code generated by the compiler when directly calling
4901the function. The `short_call` and `near` attributes are synonyms and
4902allow calls to the function to be made using the `jal` instruction, which
4903requires the function to be located in the same naturally aligned 256MB segment
4904as the caller. The `long_call` and `far` attributes are synonyms and
4905require the use of a different call sequence that works regardless
4906of the distance between the functions.
4907
4908These attributes have no effect for position-independent code.
4909
4910These attributes take priority over command line switches such
4911as `-mlong-calls` and `-mno-long-calls`.)reST";
4912
4913static const char AttrDoc_Mode[] = R"reST(No documentation.)reST";
4914
4915static const char AttrDoc_ModularFormat[] = R"reST(The `modular_format` attribute can be applied to a function that bears the
4916`format` attribute (or standard library functions) to indicate that the
4917implementation is "modular", that is, that the implementation is logically
4918divided into a number of named aspects. When the compiler can determine that
4919not all aspects of the implementation are needed for a given call, the compiler
4920may redirect the call to the identifier given as the first argument to the
4921attribute (the modular implementation function).
4922
4923The second argument is an implementation name, and the remaining arguments are
4924aspects of the format string for the compiler to report. The implementation
4925name is an unevaluated identifier in the C namespace.
4926
4927The compiler reports that a call requires an aspect by issuing a relocation for
4928the symbol `<impl_name>_<aspect>` at the point of the call. This arranges for
4929code and data needed to support the aspect of the implementation to be brought
4930into the link to satisfy weak references in the modular implemenation function.
4931If the compiler does not understand an aspect, it must summarily consider any
4932call to require that aspect.
4933
4934For example, say `printf` is annotated with
4935`modular_format(__modular_printf, "__printf", "float")`. Then, a call to
4936`printf(var, 42)` would be untouched. A call to `printf("%d", 42)` would
4937become a call to `__modular_printf` with the same arguments, as would
4938`printf("%f", 42.0)`. The latter would be accompanied with a strong
4939relocation against the symbol `__printf_float`, which would bring floating
4940point support for `printf` into the link.
4941
4942If the attribute appears more than once on a declaration, or across a chain of
4943redeclarations, it is an error for the attributes to have different arguments,
4944excepting that the aspects may be in any order.
4945
4946The following aspects are currently supported:
4947
4948- `fixed`: The call has a C ISO 18037 fixed-point argument.
4949- `float`: The call has a floating-point argument.)reST";
4950
4951static const char AttrDoc_MustTail[] = R"reST(If a `return` statement is marked `musttail`, this indicates that the
4952compiler must generate a tail call for the program to be correct, even when
4953optimizations are disabled. This guarantees that the call will not cause
4954unbounded stack growth if it is part of a recursive cycle in the call graph.
4955
4956If the callee is a virtual function that is implemented by a thunk, there is
4957no guarantee in general that the thunk tail-calls the implementation of the
4958virtual function, so such a call in a recursive cycle can still result in
4959unbounded stack growth.
4960
4961`clang::musttail` can only be applied to a `return` statement whose value
4962is the result of a function call (even functions returning void must use
4963`return`, although no value is returned). The target function must have the
4964same number of arguments as the caller. The types of the return value and all
4965arguments must be similar according to C++ rules (differing only in cv
4966qualifiers or array size), including the implicit "this" argument, if any.
4967Any variables in scope, including all arguments to the function and the
4968return value must be trivially destructible. The calling convention of the
4969caller and callee must match, and they must not be variadic functions or have
4970old style K&R C function declarations.
4971
4972The lifetimes of all local variables and function parameters end immediately
4973before the call to the function. This means that it is undefined behaviour to
4974pass a pointer or reference to a local variable to the called function, which
4975is not the case without the attribute. Clang will emit a warning in common
4976cases where this happens.
4977
4978`clang::musttail` provides assurances that the tail call can be optimized on
4979all targets, not just one.)reST";
4980
4981static const char AttrDoc_NSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4982(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4983convention (e.g. functions starting with "get" are assumed to return at
4984`+0`).
4985
4986It can be overridden using a family of the following attributes. In
4987Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
4988a function communicates that the object is returned at `+1`, and the caller
4989is responsible for freeing it.
4990Similarly, the annotation `__attribute__((ns_returns_not_retained))`
4991specifies that the object is returned at `+0` and the ownership remains with
4992the callee.
4993The annotation `__attribute__((ns_consumes_self))` specifies that
4994the Objective-C method call consumes the reference to `self`, e.g. by
4995attaching it to a supplied parameter.
4996Additionally, parameters can have an annotation
4997`__attribute__((ns_consumed))`, which specifies that passing an owned object
4998as that parameter effectively transfers the ownership, and the caller is no
4999longer responsible for it.
5000These attributes affect code generation when interacting with ARC code, and
5001they are used by the Clang Static Analyzer.
5002
5003In C programs using CoreFoundation, a similar set of attributes:
5004`__attribute__((cf_returns_not_retained))`,
5005`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
5006have the same respective semantics when applied to CoreFoundation objects.
5007These attributes affect code generation when interacting with ARC code, and
5008they are used by the Clang Static Analyzer.
5009
5010(os-retained-attr-family)=
5011
5012Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5013the same attribute family is present:
5014`__attribute__((os_returns_not_retained))`,
5015`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
5016with the same respective semantics.
5017Similar to `__attribute__((ns_consumes_self))`,
5018`__attribute__((os_consumes_this))` specifies that the method call consumes
5019the reference to "this" (e.g., when attaching it to a different object supplied
5020as a parameter).
5021Out parameters (parameters the function is meant to write into,
5022either via pointers-to-pointers or references-to-pointers)
5023may be annotated with `__attribute__((os_returns_retained))`
5024or `__attribute__((os_returns_not_retained))` which specifies that the object
5025written into the out parameter should (or respectively should not) be released
5026after use.
5027Since often out parameters may or may not be written depending on the exit
5028code of the function,
5029annotations `__attribute__((os_returns_retained_on_zero))`
5030and `__attribute__((os_returns_retained_on_non_zero))` specify that
5031an out parameter at `+1` is written if and only if the function returns a zero
5032(respectively non-zero) error code.
5033Observe that return-code-dependent out parameter annotations are only
5034available for retained out parameters, as non-retained object do not have to be
5035released by the callee.
5036These attributes are only used by the Clang Static Analyzer.
5037
5038The family of attributes `X_returns_X_retained` can be added to functions,
5039C++ methods, and Objective-C methods and properties.
5040Attributes `X_consumed` can be added to parameters of methods, functions,
5041and Objective-C methods.)reST";
5042
5043static const char AttrDoc_NSConsumesSelf[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5044(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5045convention (e.g. functions starting with "get" are assumed to return at
5046`+0`).
5047
5048It can be overridden using a family of the following attributes. In
5049Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
5050a function communicates that the object is returned at `+1`, and the caller
5051is responsible for freeing it.
5052Similarly, the annotation `__attribute__((ns_returns_not_retained))`
5053specifies that the object is returned at `+0` and the ownership remains with
5054the callee.
5055The annotation `__attribute__((ns_consumes_self))` specifies that
5056the Objective-C method call consumes the reference to `self`, e.g. by
5057attaching it to a supplied parameter.
5058Additionally, parameters can have an annotation
5059`__attribute__((ns_consumed))`, which specifies that passing an owned object
5060as that parameter effectively transfers the ownership, and the caller is no
5061longer responsible for it.
5062These attributes affect code generation when interacting with ARC code, and
5063they are used by the Clang Static Analyzer.
5064
5065In C programs using CoreFoundation, a similar set of attributes:
5066`__attribute__((cf_returns_not_retained))`,
5067`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
5068have the same respective semantics when applied to CoreFoundation objects.
5069These attributes affect code generation when interacting with ARC code, and
5070they are used by the Clang Static Analyzer.
5071
5072(os-retained-attr-family)=
5073
5074Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5075the same attribute family is present:
5076`__attribute__((os_returns_not_retained))`,
5077`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
5078with the same respective semantics.
5079Similar to `__attribute__((ns_consumes_self))`,
5080`__attribute__((os_consumes_this))` specifies that the method call consumes
5081the reference to "this" (e.g., when attaching it to a different object supplied
5082as a parameter).
5083Out parameters (parameters the function is meant to write into,
5084either via pointers-to-pointers or references-to-pointers)
5085may be annotated with `__attribute__((os_returns_retained))`
5086or `__attribute__((os_returns_not_retained))` which specifies that the object
5087written into the out parameter should (or respectively should not) be released
5088after use.
5089Since often out parameters may or may not be written depending on the exit
5090code of the function,
5091annotations `__attribute__((os_returns_retained_on_zero))`
5092and `__attribute__((os_returns_retained_on_non_zero))` specify that
5093an out parameter at `+1` is written if and only if the function returns a zero
5094(respectively non-zero) error code.
5095Observe that return-code-dependent out parameter annotations are only
5096available for retained out parameters, as non-retained object do not have to be
5097released by the callee.
5098These attributes are only used by the Clang Static Analyzer.
5099
5100The family of attributes `X_returns_X_retained` can be added to functions,
5101C++ methods, and Objective-C methods and properties.
5102Attributes `X_consumed` can be added to parameters of methods, functions,
5103and Objective-C methods.)reST";
5104
5105static const char AttrDoc_NSErrorDomain[] = R"reST(In Cocoa frameworks in Objective-C, one can group related error codes in enums
5106and categorize these enums with error domains.
5107
5108The `ns_error_domain` attribute indicates a global `NSString` or
5109`CFString` constant representing the error domain that an error code belongs
5110to. For pointer uniqueness and code size this is a constant symbol, not a
5111literal.
5112
5113The domain and error code need to be used together. The `ns_error_domain`
5114attribute links error codes to their domain at the source level.
5115
5116This metadata is useful for documentation purposes, for static analysis, and for
5117improving interoperability between Objective-C and Swift. It is not used for
5118code generation in Objective-C.
5119
5120For example:
5121
5122```objc
5123#define NS_ERROR_ENUM(_type, _name, _domain) \
5124 enum _name : _type _name; enum __attribute__((ns_error_domain(_domain))) _name : _type
5125
5126extern NSString *const MyErrorDomain;
5127typedef NS_ERROR_ENUM(unsigned char, MyErrorEnum, MyErrorDomain) {
5128 MyErrFirst,
5129 MyErrSecond,
5130};
5131```)reST";
5132
5133static const char AttrDoc_NSReturnsAutoreleased[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5134(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5135convention (e.g. functions starting with "get" are assumed to return at
5136`+0`).
5137
5138It can be overridden using a family of the following attributes. In
5139Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
5140a function communicates that the object is returned at `+1`, and the caller
5141is responsible for freeing it.
5142Similarly, the annotation `__attribute__((ns_returns_not_retained))`
5143specifies that the object is returned at `+0` and the ownership remains with
5144the callee.
5145The annotation `__attribute__((ns_consumes_self))` specifies that
5146the Objective-C method call consumes the reference to `self`, e.g. by
5147attaching it to a supplied parameter.
5148Additionally, parameters can have an annotation
5149`__attribute__((ns_consumed))`, which specifies that passing an owned object
5150as that parameter effectively transfers the ownership, and the caller is no
5151longer responsible for it.
5152These attributes affect code generation when interacting with ARC code, and
5153they are used by the Clang Static Analyzer.
5154
5155In C programs using CoreFoundation, a similar set of attributes:
5156`__attribute__((cf_returns_not_retained))`,
5157`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
5158have the same respective semantics when applied to CoreFoundation objects.
5159These attributes affect code generation when interacting with ARC code, and
5160they are used by the Clang Static Analyzer.
5161
5162(os-retained-attr-family)=
5163
5164Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5165the same attribute family is present:
5166`__attribute__((os_returns_not_retained))`,
5167`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
5168with the same respective semantics.
5169Similar to `__attribute__((ns_consumes_self))`,
5170`__attribute__((os_consumes_this))` specifies that the method call consumes
5171the reference to "this" (e.g., when attaching it to a different object supplied
5172as a parameter).
5173Out parameters (parameters the function is meant to write into,
5174either via pointers-to-pointers or references-to-pointers)
5175may be annotated with `__attribute__((os_returns_retained))`
5176or `__attribute__((os_returns_not_retained))` which specifies that the object
5177written into the out parameter should (or respectively should not) be released
5178after use.
5179Since often out parameters may or may not be written depending on the exit
5180code of the function,
5181annotations `__attribute__((os_returns_retained_on_zero))`
5182and `__attribute__((os_returns_retained_on_non_zero))` specify that
5183an out parameter at `+1` is written if and only if the function returns a zero
5184(respectively non-zero) error code.
5185Observe that return-code-dependent out parameter annotations are only
5186available for retained out parameters, as non-retained object do not have to be
5187released by the callee.
5188These attributes are only used by the Clang Static Analyzer.
5189
5190The family of attributes `X_returns_X_retained` can be added to functions,
5191C++ methods, and Objective-C methods and properties.
5192Attributes `X_consumed` can be added to parameters of methods, functions,
5193and Objective-C methods.)reST";
5194
5195static const char AttrDoc_NSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5196(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5197convention (e.g. functions starting with "get" are assumed to return at
5198`+0`).
5199
5200It can be overridden using a family of the following attributes. In
5201Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
5202a function communicates that the object is returned at `+1`, and the caller
5203is responsible for freeing it.
5204Similarly, the annotation `__attribute__((ns_returns_not_retained))`
5205specifies that the object is returned at `+0` and the ownership remains with
5206the callee.
5207The annotation `__attribute__((ns_consumes_self))` specifies that
5208the Objective-C method call consumes the reference to `self`, e.g. by
5209attaching it to a supplied parameter.
5210Additionally, parameters can have an annotation
5211`__attribute__((ns_consumed))`, which specifies that passing an owned object
5212as that parameter effectively transfers the ownership, and the caller is no
5213longer responsible for it.
5214These attributes affect code generation when interacting with ARC code, and
5215they are used by the Clang Static Analyzer.
5216
5217In C programs using CoreFoundation, a similar set of attributes:
5218`__attribute__((cf_returns_not_retained))`,
5219`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
5220have the same respective semantics when applied to CoreFoundation objects.
5221These attributes affect code generation when interacting with ARC code, and
5222they are used by the Clang Static Analyzer.
5223
5224(os-retained-attr-family)=
5225
5226Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5227the same attribute family is present:
5228`__attribute__((os_returns_not_retained))`,
5229`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
5230with the same respective semantics.
5231Similar to `__attribute__((ns_consumes_self))`,
5232`__attribute__((os_consumes_this))` specifies that the method call consumes
5233the reference to "this" (e.g., when attaching it to a different object supplied
5234as a parameter).
5235Out parameters (parameters the function is meant to write into,
5236either via pointers-to-pointers or references-to-pointers)
5237may be annotated with `__attribute__((os_returns_retained))`
5238or `__attribute__((os_returns_not_retained))` which specifies that the object
5239written into the out parameter should (or respectively should not) be released
5240after use.
5241Since often out parameters may or may not be written depending on the exit
5242code of the function,
5243annotations `__attribute__((os_returns_retained_on_zero))`
5244and `__attribute__((os_returns_retained_on_non_zero))` specify that
5245an out parameter at `+1` is written if and only if the function returns a zero
5246(respectively non-zero) error code.
5247Observe that return-code-dependent out parameter annotations are only
5248available for retained out parameters, as non-retained object do not have to be
5249released by the callee.
5250These attributes are only used by the Clang Static Analyzer.
5251
5252The family of attributes `X_returns_X_retained` can be added to functions,
5253C++ methods, and Objective-C methods and properties.
5254Attributes `X_consumed` can be added to parameters of methods, functions,
5255and Objective-C methods.)reST";
5256
5257static const char AttrDoc_NSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5258(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5259convention (e.g. functions starting with "get" are assumed to return at
5260`+0`).
5261
5262It can be overridden using a family of the following attributes. In
5263Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
5264a function communicates that the object is returned at `+1`, and the caller
5265is responsible for freeing it.
5266Similarly, the annotation `__attribute__((ns_returns_not_retained))`
5267specifies that the object is returned at `+0` and the ownership remains with
5268the callee.
5269The annotation `__attribute__((ns_consumes_self))` specifies that
5270the Objective-C method call consumes the reference to `self`, e.g. by
5271attaching it to a supplied parameter.
5272Additionally, parameters can have an annotation
5273`__attribute__((ns_consumed))`, which specifies that passing an owned object
5274as that parameter effectively transfers the ownership, and the caller is no
5275longer responsible for it.
5276These attributes affect code generation when interacting with ARC code, and
5277they are used by the Clang Static Analyzer.
5278
5279In C programs using CoreFoundation, a similar set of attributes:
5280`__attribute__((cf_returns_not_retained))`,
5281`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
5282have the same respective semantics when applied to CoreFoundation objects.
5283These attributes affect code generation when interacting with ARC code, and
5284they are used by the Clang Static Analyzer.
5285
5286(os-retained-attr-family)=
5287
5288Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5289the same attribute family is present:
5290`__attribute__((os_returns_not_retained))`,
5291`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
5292with the same respective semantics.
5293Similar to `__attribute__((ns_consumes_self))`,
5294`__attribute__((os_consumes_this))` specifies that the method call consumes
5295the reference to "this" (e.g., when attaching it to a different object supplied
5296as a parameter).
5297Out parameters (parameters the function is meant to write into,
5298either via pointers-to-pointers or references-to-pointers)
5299may be annotated with `__attribute__((os_returns_retained))`
5300or `__attribute__((os_returns_not_retained))` which specifies that the object
5301written into the out parameter should (or respectively should not) be released
5302after use.
5303Since often out parameters may or may not be written depending on the exit
5304code of the function,
5305annotations `__attribute__((os_returns_retained_on_zero))`
5306and `__attribute__((os_returns_retained_on_non_zero))` specify that
5307an out parameter at `+1` is written if and only if the function returns a zero
5308(respectively non-zero) error code.
5309Observe that return-code-dependent out parameter annotations are only
5310available for retained out parameters, as non-retained object do not have to be
5311released by the callee.
5312These attributes are only used by the Clang Static Analyzer.
5313
5314The family of attributes `X_returns_X_retained` can be added to functions,
5315C++ methods, and Objective-C methods and properties.
5316Attributes `X_consumed` can be added to parameters of methods, functions,
5317and Objective-C methods.)reST";
5318
5319static const char AttrDoc_Naked[] = R"reST(No documentation.)reST";
5320
5321static const char AttrDoc_NoAlias[] = R"reST(The `noalias` attribute indicates that the only memory accesses inside
5322function are loads and stores from objects pointed to by its pointer-typed
5323arguments, with arbitrary offsets.)reST";
5324
5325static const char AttrDoc_NoBuiltin[] = R"reST(The `__attribute__((no_builtin))` is similar to the `-fno-builtin` flag
5326except it is specific to the body of a function. The attribute may also be
5327applied to a virtual function but has no effect on the behavior of overriding
5328functions in a derived class.
5329
5330It accepts one or more strings corresponding to the specific names of the
5331builtins to disable (e.g. "memcpy", "memset").
5332If the attribute is used without parameters it will disable all buitins at
5333once.
5334
5335```c++
5336// The compiler is not allowed to add any builtin to foo's body.
5337void foo(char* data, size_t count) __attribute__((no_builtin)) {
5338 // The compiler is not allowed to convert the loop into
5339 // `__builtin_memset(data, 0xFE, count);`.
5340 for (size_t i = 0; i < count; ++i)
5341 data[i] = 0xFE;
5342}
5343
5344// The compiler is not allowed to add the `memcpy` builtin to bar's body.
5345void bar(char* data, size_t count) __attribute__((no_builtin("memcpy"))) {
5346 // The compiler is allowed to convert the loop into
5347 // `__builtin_memset(data, 0xFE, count);` but cannot generate any
5348 // `__builtin_memcpy`
5349 for (size_t i = 0; i < count; ++i)
5350 data[i] = 0xFE;
5351}
5352```)reST";
5353
5354static const char AttrDoc_NoCommon[] = R"reST(No documentation.)reST";
5355
5356static const char AttrDoc_NoConvergent[] = R"reST(This attribute prevents a function from being treated as convergent; when a
5357function is marked `noconvergent`, calls to that function are not
5358automatically assumed to be convergent, unless such calls are explicitly marked
5359as `convergent`. If a statement is marked as `noconvergent`, any calls to
5360inline `asm` in that statement are no longer treated as convergent.
5361
5362In languages following SPMD/SIMT programming model, e.g., CUDA/HIP, function
5363declarations and inline asm calls are treated as convergent by default for
5364correctness. This `noconvergent` attribute is helpful for developers to
5365prevent them from being treated as convergent when it's safe.
5366
5367```c
5368__device__ float bar(float);
5369__device__ float foo(float) __attribute__((noconvergent)) {}
5370
5371__device__ int example(void) {
5372 float x;
5373 [[clang::noconvergent]] x = bar(x); // no effect on convergence
5374 [[clang::noconvergent]] { asm volatile ("nop"); } // the asm call is non-convergent
5375}
5376```)reST";
5377
5378static const char AttrDoc_NoDebug[] = R"reST(The `nodebug` attribute allows you to suppress debugging information for a
5379function or method, for a variable that is not a parameter or a non-static
5380data member, or for a typedef or using declaration.)reST";
5381
5382static const char AttrDoc_NoDeref[] = R"reST(The `noderef` attribute causes clang to diagnose dereferences of annotated pointer types.
5383This is ideally used with pointers that point to special memory which cannot be read
5384from or written to, but allowing for the pointer to be used in pointer arithmetic.
5385The following are examples of valid expressions where dereferences are diagnosed:
5386
5387```c
5388int __attribute__((noderef)) *p;
5389int x = *p; // warning
5390
5391int __attribute__((noderef)) **p2;
5392x = **p2; // warning
5393
5394int * __attribute__((noderef)) *p3;
5395p = *p3; // warning
5396
5397struct S {
5398 int a;
5399};
5400struct S __attribute__((noderef)) *s;
5401x = s->a; // warning
5402x = (*s).a; // warning
5403```
5404
5405Not all dereferences may diagnose a warning if the value directed by the pointer may not be
5406accessed. The following are examples of valid expressions where may not be diagnosed:
5407
5408```c
5409int *q;
5410int __attribute__((noderef)) *p;
5411q = &*p;
5412q = *&p;
5413
5414struct S {
5415 int a;
5416};
5417struct S __attribute__((noderef)) *s;
5418p = &s->a;
5419p = &(*s).a;
5420```
5421
5422`noderef` is currently only supported for pointers and arrays and not usable
5423for references or Objective-C object pointers.
5424
5425```c++
5426int x = 2;
5427int __attribute__((noderef)) &y = x; // warning: 'noderef' can only be used on an array or pointer type
5428```
5429
5430```objc
5431id __attribute__((noderef)) obj = [NSObject new]; // warning: 'noderef' can only be used on an array or pointer type
5432```)reST";
5433
5434static const char AttrDoc_NoDestroy[] = R"reST(The `no_destroy` attribute specifies that a variable with static or thread
5435storage duration shouldn't have its exit-time destructor run. Annotating every
5436static and thread duration variable with this attribute is equivalent to
5437invoking clang with `-fno-c++-static-destructors`.
5438
5439If a variable is declared with this attribute, clang doesn't access check or
5440generate the type's destructor. If you have a type that you only want to be
5441annotated with `no_destroy`, you can therefore declare the destructor private:
5442
5443```c++
5444struct only_no_destroy {
5445 only_no_destroy();
5446private:
5447 ~only_no_destroy();
5448};
5449
5450[[clang::no_destroy]] only_no_destroy global; // fine!
5451```
5452
5453Note that destructors are still required for subobjects of aggregates annotated
5454with this attribute. This is because previously constructed subobjects need to
5455be destroyed if an exception gets thrown before the initialization of the
5456complete object is complete. For instance:
5457
5458```c++
5459void f() {
5460 try {
5461 [[clang::no_destroy]]
5462 static only_no_destroy array[10]; // error, only_no_destroy has a private destructor.
5463 } catch (...) {
5464 // Handle the error
5465 }
5466}
5467```
5468
5469Here, if the construction of `array[9]` fails with an exception, `array[0..8]`
5470will be destroyed, so the element's destructor needs to be accessible.)reST";
5471
5472static const char AttrDoc_NoDuplicate[] = R"reST(The `noduplicate` attribute can be placed on function declarations to control
5473whether function calls to this function can be duplicated or not as a result of
5474optimizations. This is required for the implementation of functions with
5475certain special requirements, like the OpenCL "barrier" function, that might
5476need to be run concurrently by all the threads that are executing in lockstep
5477on the hardware. For example this attribute applied on the function
5478`nodupfunc` in the code below avoids that:
5479
5480```c
5481void nodupfunc() __attribute__((noduplicate));
5482// Setting it as a C++11 attribute is also valid
5483// void nodupfunc() [[clang::noduplicate]];
5484void foo();
5485void bar();
5486
5487nodupfunc();
5488if (a > n) {
5489 foo();
5490} else {
5491 bar();
5492}
5493```
5494
5495gets possibly modified by some optimizations into code similar to this:
5496
5497```c
5498if (a > n) {
5499 nodupfunc();
5500 foo();
5501} else {
5502 nodupfunc();
5503 bar();
5504}
5505```
5506
5507where the call to `nodupfunc` is duplicated and sunk into the two branches
5508of the condition.)reST";
5509
5510static const char AttrDoc_NoEscape[] = R"reST(`noescape` placed on a function parameter of a pointer type is used to inform
5511the compiler that the pointer cannot escape: that is, no reference to the object
5512the pointer points to that is derived from the parameter value will survive
5513after the function returns. Users are responsible for making sure parameters
5514annotated with `noescape` do not actually escape. The optimizer may make
5515assumptions based on the fact that it knows that a call to the function does
5516not escape a certain parameter, so incorrectly annotating a parameter with
5517`noescape` leads to undefined behavior. The callee is also not allowed to
5518deallocate memory through a `noescape` parameter: the optimizer does not make
5519assumptions based on this information at the moment, but may do so in the
5520future. Some cases of invalid uses of `noescape` can be found with
5521{ref}`-Wlifetime-safety-noescape <Wlifetime-safety-noescape>`.
5522
5523For example:
5524
5525```c
5526int *gp;
5527
5528void nonescapingFunc(__attribute__((noescape)) int *p) {
5529 *p += 100; // OK.
5530}
5531
5532void escapingFunc(__attribute__((noescape)) int *p) {
5533 gp = p; // Not OK.
5534}
5535
5536void freeingFunc(__attribute__((noescape)) int *p) {
5537 free(p); // Not OK.
5538}
5539```
5540
5541Since `noescape` is a parameter attribute and not a type attribute, it only
5542applies to the outermost pointer level, regardless of where in the parameter
5543declaration you place it:
5544
5545```c
5546int **gp;
5547
5548void nestingEscapes(__attribute__((noescape)) int **p) {
5549 gp = p; // Not OK.
5550 *gp = *p; // OK, p does not escape.
5551}
5552```
5553
5554Additionally, when the parameter is a
5555{doc}`block pointer <BlockLanguageSpec>`, the same restriction applies to
5556copies of the block. For example:
5557
5558```c
5559typedef void (^BlockTy)();
5560BlockTy g0, g1;
5561
5562void nonescapingFunc(__attribute__((noescape)) BlockTy block) {
5563 block(); // OK.
5564}
5565
5566void escapingFunc(__attribute__((noescape)) BlockTy block) {
5567 g0 = block; // Not OK.
5568 g1 = Block_copy(block); // Not OK either.
5569}
5570```
5571
5572The function *is* allowed to leak information about the memory address of the
5573pointer, but not any provenance of the allocation:
5574
5575```c
5576bool isNull(__attribute__((noescape)) void *p) {
5577 return !p; // OK.
5578}
5579
5580uintptr_t gi;
5581
5582void escapingAddress(__attribute__((noescape)) int *p) {
5583 // OK *if and only if* gi is never casted back to a pointer.
5584 gi = (uintptr_t)p;
5585}
5586
5587bool usingEscapedAddress(int *p) {
5588 return (uintptr_t)p > gi; // OK.
5589}
5590
5591bool usingEscapedPointer(int *p) {
5592 return p > (int*)gi; // Not OK.
5593}
5594
5595int *gp;
5596
5597void escapingEndFunc(__attribute__((noescape)) int *p, size_t len) {
5598 gp = p + len; // Not OK.
5599}
5600```)reST";
5601
5602static const char AttrDoc_NoFieldProtection[] = R"reST(No documentation.)reST";
5603
5604static const char AttrDoc_NoInline[] = R"reST(This function attribute suppresses the inlining of a function at the call sites
5605of the function.
5606
5607`[[clang::noinline]]` spelling can be used as a statement attribute; other
5608spellings of the attribute are not supported on statements. If a statement is
5609marked `[[clang::noinline]]` and contains calls, those calls inside the
5610statement will not be inlined by the compiler.
5611
5612`__noinline__` can be used as a keyword in CUDA/HIP languages. This is to
5613avoid diagnostics due to usage of `__attribute__((__noinline__))`
5614with `__noinline__` defined as a macro as `__attribute__((noinline))`.
5615
5616```c
5617int example(void) {
5618 int r;
5619 [[clang::noinline]] foo();
5620 [[clang::noinline]] r = bar();
5621 return r;
5622}
5623```)reST";
5624
5625static const char AttrDoc_NoInstrumentFunction[] = R"reST(No documentation.)reST";
5626
5627static const char AttrDoc_NoMerge[] = R"reST(If a statement is marked `nomerge` and contains call expressions, those call
5628expressions inside the statement will not be merged during optimization. This
5629attribute can be used to prevent the optimizer from obscuring the source
5630location of certain calls. For example, it will prevent tail merging otherwise
5631identical code sequences that raise an exception or terminate the program. Tail
5632merging normally reduces the precision of source location information, making
5633stack traces less useful for debugging. This attribute gives the user control
5634over the tradeoff between code size and debug information precision.
5635
5636`nomerge` attribute can also be used as function attribute to prevent all
5637calls to the specified function from merging. It has no effect on indirect
5638calls to such functions. For example:
5639
5640```c++
5641[[clang::nomerge]] void foo(int) {}
5642
5643void bar(int x) {
5644 auto *ptr = foo;
5645 if (x) foo(1); else foo(2); // will not be merged
5646 if (x) ptr(1); else ptr(2); // indirect call, can be merged
5647}
5648```
5649
5650`nomerge` attribute can also be used for pointers to functions to
5651prevent calls through such pointer from merging. In such case the
5652effect applies only to a specific function pointer. For example:
5653
5654```c++
5655[[clang::nomerge]] void (*foo)(int);
5656
5657void bar(int x) {
5658 auto *ptr = foo;
5659 if (x) foo(1); else foo(2); // will not be merged
5660 if (x) ptr(1); else ptr(2); // 'ptr' has no 'nomerge' attribute, can be merged
5661}
5662```)reST";
5663
5664static const char AttrDoc_NoMicroMips[] = R"reST(Clang supports the GNU style `__attribute__((micromips))` and
5665`__attribute__((nomicromips))` attributes on MIPS targets. These attributes
5666may be attached to a function definition and instructs the backend to generate
5667or not to generate microMIPS code for that function.
5668
5669These attributes override the `-mmicromips` and `-mno-micromips` options
5670on the command line.)reST";
5671
5672static const char AttrDoc_NoMips16[] = R"reST(No documentation.)reST";
5673
5674static const char AttrDoc_NoOutline[] = R"reST(This function attribute suppresses outlining from the annotated function.
5675
5676Outlining is the process where common parts of separate functions are extracted
5677into a separate function (or assembly snippet), and calls to that function or
5678snippet are inserted in the original functions. In this way, it can be seen as
5679the opposite of inlining. It can help to reduce code size.)reST";
5680
5681static const char AttrDoc_NoProfileFunction[] = R"reST(Use the `no_profile_instrument_function` attribute on a function declaration
5682to denote that the compiler should not instrument the function with
5683profile-related instrumentation, such as via the
5684`-fprofile-generate` / `-fprofile-instr-generate` /
5685`-fcs-profile-generate` / `-fprofile-arcs` flags.)reST";
5686
5687static const char AttrDoc_NoRandomizeLayout[] = R"reST(The attribute `randomize_layout`, when attached to a C structure, selects it
5688for structure layout field randomization; a compile-time hardening technique. A
5689"seed" value, is specified via the `-frandomize-layout-seed=` command line flag.
5690For example:
5691
5692```bash
5693SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
5694make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
5695```
5696
5697You can also supply the seed in a file with `-frandomize-layout-seed-file=`.
5698For example:
5699
5700```bash
5701od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
5702make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
5703```
5704
5705The randomization is deterministic based for a given seed, so the entire
5706program should be compiled with the same seed, but keep the seed safe
5707otherwise.
5708
5709The attribute `no_randomize_layout`, when attached to a C structure,
5710instructs the compiler that this structure should not have its field layout
5711randomized.)reST";
5712
5713static const char AttrDoc_NoReturn[] = R"reST(No documentation.)reST";
5714
5715static const char AttrDoc_NoSanitize[] = R"reST(Use the `no_sanitize` attribute on a function or a global variable
5716declaration to specify that a particular instrumentation or set of
5717instrumentations should not be applied.
5718
5719The attribute takes a list of string literals with the following accepted
5720values:
5721
5722- all values accepted by `-fno-sanitize=`;
5723- `coverage`, to disable SanitizerCoverage instrumentation.
5724
5725For example, `__attribute__((no_sanitize("address", "thread")))` specifies
5726that AddressSanitizer and ThreadSanitizer should not be applied to the function
5727or variable. Using `__attribute__((no_sanitize("coverage")))` specifies that
5728SanitizerCoverage should not be applied to the function.
5729
5730See {ref}`Controlling Code Generation <controlling-code-generation>` for a
5731full list of supported sanitizer flags.)reST";
5732
5733static const char AttrDoc_NoSpecializations[] = R"reST(`[[clang::no_specializations]]` can be applied to function, class, or variable
5734templates for which neither an explicit specialization nor a partial specialization should be declared by users. This is primarily
5735used to diagnose user specializations of standard library type traits.)reST";
5736
5737static const char AttrDoc_NoSpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
5738that [Speculative Load Hardening][slh] is *not* needed for the function body.
5739This can also be applied to a method in Objective C. This attribute will take
5740precedence over the command line flag in the case where
5741{option}`-mspeculative-load-hardening` is specified.
5742
5743Warning: This attribute may not prevent Speculative Load Hardening from being
5744enabled for a function which inlines a function that has the
5745`speculative_load_hardening` attribute. This is intended to provide a
5746maximally conservative model where the code that is marked with the
5747`speculative_load_hardening` attribute will always (even when inlined)
5748be hardened. A user of this attribute may want to mark functions called by
5749a function they do not want to be hardened with the `noinline` attribute.
5750
5751For example:
5752
5753```c
5754__attribute__((speculative_load_hardening))
5755int foo(int i) {
5756 return i;
5757}
5758
5759// Note: bar() may still have speculative load hardening enabled if
5760// foo() is inlined into bar(). Mark foo() with __attribute__((noinline))
5761// to avoid this situation.
5762__attribute__((no_speculative_load_hardening))
5763int bar(int i) {
5764 return foo(i);
5765}
5766```)reST";
5767
5768static const char AttrDoc_NoSplitStack[] = R"reST(The `no_split_stack` attribute disables the emission of the split stack
5769preamble for a particular function. It has no effect if `-fsplit-stack`
5770is not specified.)reST";
5771
5772static const char AttrDoc_NoStackProtector[] = R"reST(Clang supports the GNU style `__attribute__((no_stack_protector))` and Microsoft
5773style `__declspec(safebuffers)` attribute which disables
5774the stack protector on the specified function. This attribute is useful for
5775selectively disabling the stack protector on some functions when building with
5776`-fstack-protector` compiler option.
5777
5778For example, it disables the stack protector for the function `foo` but function
5779`bar` will still be built with the stack protector with the `-fstack-protector`
5780option.
5781
5782```c
5783int __attribute__((no_stack_protector))
5784foo (int x); // stack protection will be disabled for foo.
5785
5786int bar(int y); // bar can be built with the stack protector.
5787```)reST";
5788
5789static const char AttrDoc_NoThreadSafetyAnalysis[] = R"reST(No documentation.)reST";
5790
5791static const char AttrDoc_NoThrow[] = R"reST(Clang supports the GNU style `__attribute__((nothrow))` and Microsoft style
5792`__declspec(nothrow)` attribute as an equivalent of `noexcept` on function
5793declarations. This attribute informs the compiler that the annotated function
5794does not throw an exception. This prevents exception-unwinding. This attribute
5795is particularly useful on functions in the C Standard Library that are
5796guaranteed to not throw an exception.)reST";
5797
5798static const char AttrDoc_NoTrivialAutoVarInit[] = R"reST(The `__declspec(no_init_all)` attribute disables the automatic initialization
5799that the {option}`-ftrivial-auto-var-init` flag would have applied to locals in
5800a marked function, or instances of a marked type. Note that this attribute has
5801no effect for locals that are automatically initialized without the
5802{option}`-ftrivial-auto-var-init` flag.)reST";
5803
5804static const char AttrDoc_NoUniqueAddress[] = R"reST(The `no_unique_address` attribute allows tail padding in a non-static data
5805member to overlap other members of the enclosing class (and in the special
5806case when the type is empty, permits it to fully overlap other members).
5807The field is laid out as if a base class were encountered at the corresponding
5808point within the class (except that it does not share a vptr with the enclosing
5809object).
5810
5811Example usage:
5812
5813```c++
5814template<typename T, typename Alloc> struct my_vector {
5815 T *p;
5816 [[no_unique_address]] Alloc alloc;
5817 // ...
5818};
5819static_assert(sizeof(my_vector<int, std::allocator<int>>) == sizeof(int*));
5820```
5821
5822`[[no_unique_address]]` is a standard C++20 attribute. Clang supports its use
5823in C++11 onwards.
5824
5825On MSVC targets, `[[no_unique_address]]` is ignored; use
5826`[[msvc::no_unique_address]]` instead. Currently there is no guarantee of ABI
5827compatibility or stability with MSVC.)reST";
5828
5829static const char AttrDoc_NoUwtable[] = R"reST(Clang supports the `nouwtable` attribute which skips emitting
5830the unwind table entry for the specified function. This attribute is useful for
5831selectively emitting the unwind table entry on some functions when building with
5832`-funwind-tables` compiler option.)reST";
5833
5834static const char AttrDoc_NonAllocating[] = R"reST(Declares that a function or function type either does or does not allocate heap memory, according
5835to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5836is false, the attribute is equivalent to `allocating`.)reST";
5837
5838static const char AttrDoc_NonBlocking[] = R"reST(Declares that a function or function type either does or does not block in any way, according
5839to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5840is false, the attribute is equivalent to `blocking`.
5841
5842For the purposes of diagnostics, `nonblocking` is considered to include the
5843`nonallocating` guarantee and is therefore a "stronger" constraint or attribute.)reST";
5844
5845static const char AttrDoc_NonNull[] = R"reST(The `nonnull` attribute indicates that some function parameters must not be
5846null, and can be used in several different ways. It's original usage
5847([from GCC](https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes))
5848is as a function (or Objective-C method) attribute that specifies which
5849parameters of the function are nonnull in a comma-separated list. For example:
5850
5851```c
5852extern void * my_memcpy (void *dest, const void *src, size_t len)
5853 __attribute__((nonnull (1, 2)));
5854```
5855
5856Here, the `nonnull` attribute indicates that parameters 1 and 2
5857cannot have a null value. Omitting the parenthesized list of parameter indices
5858means that all parameters of pointer type cannot be null:
5859
5860```c
5861extern void * my_memcpy (void *dest, const void *src, size_t len)
5862 __attribute__((nonnull));
5863```
5864
5865Clang also allows the `nonnull` attribute to be placed directly on a function
5866(or Objective-C method) parameter, eliminating the need to specify the
5867parameter index ahead of type. For example:
5868
5869```c
5870extern void * my_memcpy (void *dest __attribute__((nonnull)),
5871 const void *src __attribute__((nonnull)), size_t len);
5872```
5873
5874Note that the `nonnull` attribute indicates that passing null to a non-null
5875parameter is undefined behavior, which the optimizer may take advantage of to,
5876e.g., remove null checks. The `_Nonnull` type qualifier indicates that a
5877pointer cannot be null in a more general manner (because it is part of the type
5878system) and does not imply undefined behavior, making it more widely applicable.)reST";
5879
5880static const char AttrDoc_NonString[] = R"reST(The `nonstring` attribute can be applied to the declaration of a variable or
5881a field whose type is a character pointer or character array to specify that
5882the buffer is not intended to behave like a null-terminated string. This will
5883silence diagnostics with code like:
5884
5885```c
5886char BadStr[3] = "foo"; // No space for the null terminator, diagnosed
5887__attribute__((nonstring)) char NotAStr[3] = "foo"; // Not diagnosed
5888```)reST";
5889
5890static const char AttrDoc_NotTailCalled[] = R"reST(The `not_tail_called` attribute prevents tail-call optimization on statically
5891bound calls. Objective-c methods, and functions marked as `always_inline`
5892cannot be marked as `not_tail_called`.
5893
5894For example, it prevents tail-call optimization in the following case:
5895
5896```c
5897int __attribute__((not_tail_called)) foo1(int);
5898
5899int foo2(int a) {
5900 return foo1(a); // No tail-call optimization on direct calls.
5901}
5902```
5903
5904However, it doesn't prevent tail-call optimization in this case:
5905
5906```c
5907int __attribute__((not_tail_called)) foo1(int);
5908
5909int foo2(int a) {
5910 int (*fn)(int) = &foo1;
5911
5912 // not_tail_called has no effect on an indirect call even if the call can
5913 // be resolved at compile time.
5914 return (*fn)(a);
5915}
5916```
5917
5918Generally, marking an overriding virtual function as `not_tail_called` is
5919not useful, because this attribute is a property of the static type. Calls
5920made through a pointer or reference to the base class type will respect
5921the `not_tail_called` attribute of the base class's member function,
5922regardless of the runtime destination of the call:
5923
5924```c++
5925struct Foo { virtual void f(); };
5926struct Bar : Foo {
5927 [[clang::not_tail_called]] void f() override;
5928};
5929void callera(Bar& bar) {
5930 Foo& foo = bar;
5931 // not_tail_called has no effect on here, even though the
5932 // underlying method is f from Bar.
5933 foo.f();
5934 bar.f(); // No tail-call optimization on here.
5935}
5936```)reST";
5937
5938static const char AttrDoc_OMPAllocateDecl[] = R"reST()reST";
5939
5940static const char AttrDoc_OMPAssume[] = R"reST(Clang supports the `[[omp::assume("assumption")]]` attribute to
5941provide additional information to the optimizer. The string-literal, here
5942"assumption", will be attached to the function declaration such that later
5943analysis and optimization passes can assume the "assumption" to hold.
5944This is similar to {ref}`__builtin_assume <langext-__builtin_assume>` but
5945instead of an expression that can be assumed to be non-zero, the assumption is
5946expressed as a string and it holds for the entire function.
5947
5948A function can have multiple assume attributes and they propagate from prior
5949declarations to later definitions. Multiple assumptions are aggregated into a
5950single comma separated string. Thus, one can provide multiple assumptions via
5951a comma separated string, i.a.,
5952`[[omp::assume("assumption1,assumption2")]]`.
5953
5954While LLVM plugins might provide more assumption strings, the default LLVM
5955optimization passes are aware of the following assumptions:
5956
5957```none
5958"omp_no_openmp"
5959"omp_no_openmp_routines"
5960"omp_no_parallelism"
5961"omp_no_openmp_constructs"
5962```
5963
5964The OpenMP standard defines the meaning of OpenMP assumptions ("omp_XYZ" is
5965spelled "XYZ" in the [OpenMP 5.1 Standard][openmp 5.1 standard]).
5966
5967[openmp 5.1 standard]: https://www.openmp.org/spec-html/5.1/openmpsu37.html#x56-560002.5.2)reST";
5968
5969static const char AttrDoc_OMPCaptureKind[] = R"reST()reST";
5970
5971static const char AttrDoc_OMPCaptureNoInit[] = R"reST()reST";
5972
5973static const char AttrDoc_OMPDeclareSimdDecl[] = R"reST(The `declare simd` construct can be applied to a function to enable the creation
5974of one or more versions that can process multiple arguments using SIMD
5975instructions from a single invocation in a SIMD loop. The `declare simd`
5976directive is a declarative directive. There may be multiple `declare simd`
5977directives for a function. The use of a `declare simd` construct on a function
5978enables the creation of SIMD versions of the associated function that can be
5979used to process multiple arguments from a single invocation from a SIMD loop
5980concurrently.
5981The syntax of the `declare simd` construct is as follows:
5982
5983```none
5984#pragma omp declare simd [clause[[,] clause] ...] new-line
5985[#pragma omp declare simd [clause[[,] clause] ...] new-line]
5986[...]
5987function definition or declaration
5988```
5989
5990where clause is one of the following:
5991
5992```none
5993simdlen(length)
5994linear(argument-list[:constant-linear-step])
5995aligned(argument-list[:alignment])
5996uniform(argument-list)
5997inbranch
5998notinbranch
5999```)reST";
6000
6001static const char AttrDoc_OMPDeclareTargetDecl[] = R"reST(The `declare target` directive specifies that variables and functions are mapped
6002to a device for OpenMP offload mechanism.
6003
6004The syntax of the declare target directive is as follows:
6005
6006```c
6007#pragma omp declare target new-line
6008declarations-definition-seq
6009#pragma omp end declare target new-line
6010```
6011
6012or
6013
6014```c
6015#pragma omp declare target (extended-list) new-line
6016```
6017
6018or
6019
6020```c
6021#pragma omp declare target clause[ [,] clause ... ] new-line
6022```
6023
6024where clause is one of the following:
6025
6026```c
6027to(extended-list)
6028link(list)
6029device_type(host | nohost | any)
6030```)reST";
6031
6032static const char AttrDoc_OMPDeclareVariant[] = R"reST(The `declare variant` directive declares a specialized variant of a base
6033function and specifies the context in which that specialized variant is used.
6034The declare variant directive is a declarative directive.
6035The syntax of the `declare variant` construct is as follows:
6036
6037```none
6038#pragma omp declare variant(variant-func-id) clause new-line
6039[#pragma omp declare variant(variant-func-id) clause new-line]
6040[...]
6041function definition or declaration
6042```
6043
6044where clause is one of the following:
6045
6046```none
6047match(context-selector-specification)
6048```
6049
6050and where `variant-func-id` is the name of a function variant that is either a
6051base language identifier or, for C++, a template-id.
6052
6053Clang provides the following context selector extensions, used via
6054`implementation={extension(EXTENSION)}`:
6055
6056```none
6057match_all
6058match_any
6059match_none
6060disable_implicit_base
6061allow_templates
6062bind_to_declaration
6063```
6064
6065The match extensions change when the *entire* context selector is considered a
6066match for an OpenMP context. The default is `all`, with `none` no trait in the
6067selector is allowed to be in the OpenMP context, with `any` a single trait in
6068both the selector and OpenMP context is sufficient. Only a single match
6069extension trait is allowed per context selector.
6070The disable extensions remove default effects of the `begin declare variant`
6071applied to a definition. If `disable_implicit_base` is given, we will not
6072introduce an implicit base function for a variant if no base function was
6073found. The variant is still generated but will never be called, due to the
6074absence of a base function and consequently calls to a base function.
6075The allow extensions change when the `begin declare variant` effect is
6076applied to a definition. If `allow_templates` is given, template function
6077definitions are considered as specializations of existing or assumed template
6078declarations with the same name. The template parameters for the base functions
6079are used to instantiate the specialization. If `bind_to_declaration` is given,
6080apply the same variant rules to function declarations. This allows the user to
6081override declarations with only a function declaration.)reST";
6082
6083static const char AttrDoc_OMPGroupPrivateDecl[] = R"reST()reST";
6084
6085static const char AttrDoc_OMPInvariantPredicateBound[] = R"reST()reST";
6086
6087static const char AttrDoc_OMPReferencedVar[] = R"reST()reST";
6088
6089static const char AttrDoc_OMPTargetIndirectCall[] = R"reST()reST";
6090
6091static const char AttrDoc_OMPThreadPrivateDecl[] = R"reST()reST";
6092
6093static const char AttrDoc_OSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6094(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6095convention (e.g. functions starting with "get" are assumed to return at
6096`+0`).
6097
6098It can be overridden using a family of the following attributes. In
6099Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6100a function communicates that the object is returned at `+1`, and the caller
6101is responsible for freeing it.
6102Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6103specifies that the object is returned at `+0` and the ownership remains with
6104the callee.
6105The annotation `__attribute__((ns_consumes_self))` specifies that
6106the Objective-C method call consumes the reference to `self`, e.g. by
6107attaching it to a supplied parameter.
6108Additionally, parameters can have an annotation
6109`__attribute__((ns_consumed))`, which specifies that passing an owned object
6110as that parameter effectively transfers the ownership, and the caller is no
6111longer responsible for it.
6112These attributes affect code generation when interacting with ARC code, and
6113they are used by the Clang Static Analyzer.
6114
6115In C programs using CoreFoundation, a similar set of attributes:
6116`__attribute__((cf_returns_not_retained))`,
6117`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6118have the same respective semantics when applied to CoreFoundation objects.
6119These attributes affect code generation when interacting with ARC code, and
6120they are used by the Clang Static Analyzer.
6121
6122(os-retained-attr-family)=
6123
6124Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6125the same attribute family is present:
6126`__attribute__((os_returns_not_retained))`,
6127`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6128with the same respective semantics.
6129Similar to `__attribute__((ns_consumes_self))`,
6130`__attribute__((os_consumes_this))` specifies that the method call consumes
6131the reference to "this" (e.g., when attaching it to a different object supplied
6132as a parameter).
6133Out parameters (parameters the function is meant to write into,
6134either via pointers-to-pointers or references-to-pointers)
6135may be annotated with `__attribute__((os_returns_retained))`
6136or `__attribute__((os_returns_not_retained))` which specifies that the object
6137written into the out parameter should (or respectively should not) be released
6138after use.
6139Since often out parameters may or may not be written depending on the exit
6140code of the function,
6141annotations `__attribute__((os_returns_retained_on_zero))`
6142and `__attribute__((os_returns_retained_on_non_zero))` specify that
6143an out parameter at `+1` is written if and only if the function returns a zero
6144(respectively non-zero) error code.
6145Observe that return-code-dependent out parameter annotations are only
6146available for retained out parameters, as non-retained object do not have to be
6147released by the callee.
6148These attributes are only used by the Clang Static Analyzer.
6149
6150The family of attributes `X_returns_X_retained` can be added to functions,
6151C++ methods, and Objective-C methods and properties.
6152Attributes `X_consumed` can be added to parameters of methods, functions,
6153and Objective-C methods.)reST";
6154
6155static const char AttrDoc_OSConsumesThis[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6156(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6157convention (e.g. functions starting with "get" are assumed to return at
6158`+0`).
6159
6160It can be overridden using a family of the following attributes. In
6161Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6162a function communicates that the object is returned at `+1`, and the caller
6163is responsible for freeing it.
6164Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6165specifies that the object is returned at `+0` and the ownership remains with
6166the callee.
6167The annotation `__attribute__((ns_consumes_self))` specifies that
6168the Objective-C method call consumes the reference to `self`, e.g. by
6169attaching it to a supplied parameter.
6170Additionally, parameters can have an annotation
6171`__attribute__((ns_consumed))`, which specifies that passing an owned object
6172as that parameter effectively transfers the ownership, and the caller is no
6173longer responsible for it.
6174These attributes affect code generation when interacting with ARC code, and
6175they are used by the Clang Static Analyzer.
6176
6177In C programs using CoreFoundation, a similar set of attributes:
6178`__attribute__((cf_returns_not_retained))`,
6179`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6180have the same respective semantics when applied to CoreFoundation objects.
6181These attributes affect code generation when interacting with ARC code, and
6182they are used by the Clang Static Analyzer.
6183
6184(os-retained-attr-family)=
6185
6186Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6187the same attribute family is present:
6188`__attribute__((os_returns_not_retained))`,
6189`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6190with the same respective semantics.
6191Similar to `__attribute__((ns_consumes_self))`,
6192`__attribute__((os_consumes_this))` specifies that the method call consumes
6193the reference to "this" (e.g., when attaching it to a different object supplied
6194as a parameter).
6195Out parameters (parameters the function is meant to write into,
6196either via pointers-to-pointers or references-to-pointers)
6197may be annotated with `__attribute__((os_returns_retained))`
6198or `__attribute__((os_returns_not_retained))` which specifies that the object
6199written into the out parameter should (or respectively should not) be released
6200after use.
6201Since often out parameters may or may not be written depending on the exit
6202code of the function,
6203annotations `__attribute__((os_returns_retained_on_zero))`
6204and `__attribute__((os_returns_retained_on_non_zero))` specify that
6205an out parameter at `+1` is written if and only if the function returns a zero
6206(respectively non-zero) error code.
6207Observe that return-code-dependent out parameter annotations are only
6208available for retained out parameters, as non-retained object do not have to be
6209released by the callee.
6210These attributes are only used by the Clang Static Analyzer.
6211
6212The family of attributes `X_returns_X_retained` can be added to functions,
6213C++ methods, and Objective-C methods and properties.
6214Attributes `X_consumed` can be added to parameters of methods, functions,
6215and Objective-C methods.)reST";
6216
6217static const char AttrDoc_OSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6218(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6219convention (e.g. functions starting with "get" are assumed to return at
6220`+0`).
6221
6222It can be overridden using a family of the following attributes. In
6223Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6224a function communicates that the object is returned at `+1`, and the caller
6225is responsible for freeing it.
6226Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6227specifies that the object is returned at `+0` and the ownership remains with
6228the callee.
6229The annotation `__attribute__((ns_consumes_self))` specifies that
6230the Objective-C method call consumes the reference to `self`, e.g. by
6231attaching it to a supplied parameter.
6232Additionally, parameters can have an annotation
6233`__attribute__((ns_consumed))`, which specifies that passing an owned object
6234as that parameter effectively transfers the ownership, and the caller is no
6235longer responsible for it.
6236These attributes affect code generation when interacting with ARC code, and
6237they are used by the Clang Static Analyzer.
6238
6239In C programs using CoreFoundation, a similar set of attributes:
6240`__attribute__((cf_returns_not_retained))`,
6241`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6242have the same respective semantics when applied to CoreFoundation objects.
6243These attributes affect code generation when interacting with ARC code, and
6244they are used by the Clang Static Analyzer.
6245
6246(os-retained-attr-family)=
6247
6248Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6249the same attribute family is present:
6250`__attribute__((os_returns_not_retained))`,
6251`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6252with the same respective semantics.
6253Similar to `__attribute__((ns_consumes_self))`,
6254`__attribute__((os_consumes_this))` specifies that the method call consumes
6255the reference to "this" (e.g., when attaching it to a different object supplied
6256as a parameter).
6257Out parameters (parameters the function is meant to write into,
6258either via pointers-to-pointers or references-to-pointers)
6259may be annotated with `__attribute__((os_returns_retained))`
6260or `__attribute__((os_returns_not_retained))` which specifies that the object
6261written into the out parameter should (or respectively should not) be released
6262after use.
6263Since often out parameters may or may not be written depending on the exit
6264code of the function,
6265annotations `__attribute__((os_returns_retained_on_zero))`
6266and `__attribute__((os_returns_retained_on_non_zero))` specify that
6267an out parameter at `+1` is written if and only if the function returns a zero
6268(respectively non-zero) error code.
6269Observe that return-code-dependent out parameter annotations are only
6270available for retained out parameters, as non-retained object do not have to be
6271released by the callee.
6272These attributes are only used by the Clang Static Analyzer.
6273
6274The family of attributes `X_returns_X_retained` can be added to functions,
6275C++ methods, and Objective-C methods and properties.
6276Attributes `X_consumed` can be added to parameters of methods, functions,
6277and Objective-C methods.)reST";
6278
6279static const char AttrDoc_OSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6280(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6281convention (e.g. functions starting with "get" are assumed to return at
6282`+0`).
6283
6284It can be overridden using a family of the following attributes. In
6285Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6286a function communicates that the object is returned at `+1`, and the caller
6287is responsible for freeing it.
6288Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6289specifies that the object is returned at `+0` and the ownership remains with
6290the callee.
6291The annotation `__attribute__((ns_consumes_self))` specifies that
6292the Objective-C method call consumes the reference to `self`, e.g. by
6293attaching it to a supplied parameter.
6294Additionally, parameters can have an annotation
6295`__attribute__((ns_consumed))`, which specifies that passing an owned object
6296as that parameter effectively transfers the ownership, and the caller is no
6297longer responsible for it.
6298These attributes affect code generation when interacting with ARC code, and
6299they are used by the Clang Static Analyzer.
6300
6301In C programs using CoreFoundation, a similar set of attributes:
6302`__attribute__((cf_returns_not_retained))`,
6303`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6304have the same respective semantics when applied to CoreFoundation objects.
6305These attributes affect code generation when interacting with ARC code, and
6306they are used by the Clang Static Analyzer.
6307
6308(os-retained-attr-family)=
6309
6310Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6311the same attribute family is present:
6312`__attribute__((os_returns_not_retained))`,
6313`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6314with the same respective semantics.
6315Similar to `__attribute__((ns_consumes_self))`,
6316`__attribute__((os_consumes_this))` specifies that the method call consumes
6317the reference to "this" (e.g., when attaching it to a different object supplied
6318as a parameter).
6319Out parameters (parameters the function is meant to write into,
6320either via pointers-to-pointers or references-to-pointers)
6321may be annotated with `__attribute__((os_returns_retained))`
6322or `__attribute__((os_returns_not_retained))` which specifies that the object
6323written into the out parameter should (or respectively should not) be released
6324after use.
6325Since often out parameters may or may not be written depending on the exit
6326code of the function,
6327annotations `__attribute__((os_returns_retained_on_zero))`
6328and `__attribute__((os_returns_retained_on_non_zero))` specify that
6329an out parameter at `+1` is written if and only if the function returns a zero
6330(respectively non-zero) error code.
6331Observe that return-code-dependent out parameter annotations are only
6332available for retained out parameters, as non-retained object do not have to be
6333released by the callee.
6334These attributes are only used by the Clang Static Analyzer.
6335
6336The family of attributes `X_returns_X_retained` can be added to functions,
6337C++ methods, and Objective-C methods and properties.
6338Attributes `X_consumed` can be added to parameters of methods, functions,
6339and Objective-C methods.)reST";
6340
6341static const char AttrDoc_OSReturnsRetainedOnNonZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6342(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6343convention (e.g. functions starting with "get" are assumed to return at
6344`+0`).
6345
6346It can be overridden using a family of the following attributes. In
6347Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6348a function communicates that the object is returned at `+1`, and the caller
6349is responsible for freeing it.
6350Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6351specifies that the object is returned at `+0` and the ownership remains with
6352the callee.
6353The annotation `__attribute__((ns_consumes_self))` specifies that
6354the Objective-C method call consumes the reference to `self`, e.g. by
6355attaching it to a supplied parameter.
6356Additionally, parameters can have an annotation
6357`__attribute__((ns_consumed))`, which specifies that passing an owned object
6358as that parameter effectively transfers the ownership, and the caller is no
6359longer responsible for it.
6360These attributes affect code generation when interacting with ARC code, and
6361they are used by the Clang Static Analyzer.
6362
6363In C programs using CoreFoundation, a similar set of attributes:
6364`__attribute__((cf_returns_not_retained))`,
6365`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6366have the same respective semantics when applied to CoreFoundation objects.
6367These attributes affect code generation when interacting with ARC code, and
6368they are used by the Clang Static Analyzer.
6369
6370(os-retained-attr-family)=
6371
6372Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6373the same attribute family is present:
6374`__attribute__((os_returns_not_retained))`,
6375`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6376with the same respective semantics.
6377Similar to `__attribute__((ns_consumes_self))`,
6378`__attribute__((os_consumes_this))` specifies that the method call consumes
6379the reference to "this" (e.g., when attaching it to a different object supplied
6380as a parameter).
6381Out parameters (parameters the function is meant to write into,
6382either via pointers-to-pointers or references-to-pointers)
6383may be annotated with `__attribute__((os_returns_retained))`
6384or `__attribute__((os_returns_not_retained))` which specifies that the object
6385written into the out parameter should (or respectively should not) be released
6386after use.
6387Since often out parameters may or may not be written depending on the exit
6388code of the function,
6389annotations `__attribute__((os_returns_retained_on_zero))`
6390and `__attribute__((os_returns_retained_on_non_zero))` specify that
6391an out parameter at `+1` is written if and only if the function returns a zero
6392(respectively non-zero) error code.
6393Observe that return-code-dependent out parameter annotations are only
6394available for retained out parameters, as non-retained object do not have to be
6395released by the callee.
6396These attributes are only used by the Clang Static Analyzer.
6397
6398The family of attributes `X_returns_X_retained` can be added to functions,
6399C++ methods, and Objective-C methods and properties.
6400Attributes `X_consumed` can be added to parameters of methods, functions,
6401and Objective-C methods.)reST";
6402
6403static const char AttrDoc_OSReturnsRetainedOnZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6404(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6405convention (e.g. functions starting with "get" are assumed to return at
6406`+0`).
6407
6408It can be overridden using a family of the following attributes. In
6409Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6410a function communicates that the object is returned at `+1`, and the caller
6411is responsible for freeing it.
6412Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6413specifies that the object is returned at `+0` and the ownership remains with
6414the callee.
6415The annotation `__attribute__((ns_consumes_self))` specifies that
6416the Objective-C method call consumes the reference to `self`, e.g. by
6417attaching it to a supplied parameter.
6418Additionally, parameters can have an annotation
6419`__attribute__((ns_consumed))`, which specifies that passing an owned object
6420as that parameter effectively transfers the ownership, and the caller is no
6421longer responsible for it.
6422These attributes affect code generation when interacting with ARC code, and
6423they are used by the Clang Static Analyzer.
6424
6425In C programs using CoreFoundation, a similar set of attributes:
6426`__attribute__((cf_returns_not_retained))`,
6427`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6428have the same respective semantics when applied to CoreFoundation objects.
6429These attributes affect code generation when interacting with ARC code, and
6430they are used by the Clang Static Analyzer.
6431
6432(os-retained-attr-family)=
6433
6434Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6435the same attribute family is present:
6436`__attribute__((os_returns_not_retained))`,
6437`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6438with the same respective semantics.
6439Similar to `__attribute__((ns_consumes_self))`,
6440`__attribute__((os_consumes_this))` specifies that the method call consumes
6441the reference to "this" (e.g., when attaching it to a different object supplied
6442as a parameter).
6443Out parameters (parameters the function is meant to write into,
6444either via pointers-to-pointers or references-to-pointers)
6445may be annotated with `__attribute__((os_returns_retained))`
6446or `__attribute__((os_returns_not_retained))` which specifies that the object
6447written into the out parameter should (or respectively should not) be released
6448after use.
6449Since often out parameters may or may not be written depending on the exit
6450code of the function,
6451annotations `__attribute__((os_returns_retained_on_zero))`
6452and `__attribute__((os_returns_retained_on_non_zero))` specify that
6453an out parameter at `+1` is written if and only if the function returns a zero
6454(respectively non-zero) error code.
6455Observe that return-code-dependent out parameter annotations are only
6456available for retained out parameters, as non-retained object do not have to be
6457released by the callee.
6458These attributes are only used by the Clang Static Analyzer.
6459
6460The family of attributes `X_returns_X_retained` can be added to functions,
6461C++ methods, and Objective-C methods and properties.
6462Attributes `X_consumed` can be added to parameters of methods, functions,
6463and Objective-C methods.)reST";
6464
6465static const char AttrDoc_ObjCBoxable[] = R"reST(Structs and unions marked with the `objc_boxable` attribute can be used
6466with the Objective-C boxed expression syntax, `@(...)`.
6467
6468**Usage**: `__attribute__((objc_boxable))`. This attribute
6469can only be placed on a declaration of a trivially-copyable struct or union:
6470
6471```objc
6472struct __attribute__((objc_boxable)) some_struct {
6473 int i;
6474};
6475union __attribute__((objc_boxable)) some_union {
6476 int i;
6477 float f;
6478};
6479typedef struct __attribute__((objc_boxable)) _some_struct some_struct;
6480
6481// ...
6482
6483some_struct ss;
6484NSValue *boxed = @(ss);
6485```)reST";
6486
6487static const char AttrDoc_ObjCBridge[] = R"reST(No documentation.)reST";
6488
6489static const char AttrDoc_ObjCBridgeMutable[] = R"reST(No documentation.)reST";
6490
6491static const char AttrDoc_ObjCBridgeRelated[] = R"reST(No documentation.)reST";
6492
6493static const char AttrDoc_ObjCClassStub[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
6494instantiated at runtime.
6495
6496Unlike `__attribute__((objc_runtime_visible))`, a class having this attribute
6497still has a "class stub" that is visible to the linker. This allows categories
6498to be defined. Static message sends with the class as a receiver use a special
6499access pattern to ensure the class is lazily instantiated from the class stub.
6500
6501Classes annotated with this attribute cannot be subclassed and cannot have
6502implementations defined for them. This attribute is intended for use in
6503Swift-generated headers for classes defined in Swift.
6504
6505Adding or removing this attribute to a class is an ABI-breaking change.)reST";
6506
6507static const char AttrDoc_ObjCDesignatedInitializer[] = R"reST(No documentation.)reST";
6508
6509static const char AttrDoc_ObjCDirect[] = R"reST(The `objc_direct` attribute can be used to mark an Objective-C method as
6510being *direct*. A direct method is treated statically like an ordinary method,
6511but dynamically it behaves more like a C function. This lowers some of the costs
6512associated with the method but also sacrifices some of the ordinary capabilities
6513of Objective-C methods.
6514
6515A message send of a direct method calls the implementation directly, as if it
6516were a C function, rather than using ordinary Objective-C method dispatch. This
6517is substantially faster and potentially allows the implementation to be inlined,
6518but it also means the method cannot be overridden in subclasses or replaced
6519dynamically, as ordinary Objective-C methods can.
6520
6521Furthermore, a direct method is not listed in the class's method lists. This
6522substantially reduces the code-size overhead of the method but also means it
6523cannot be called dynamically using ordinary Objective-C method dispatch at all;
6524in particular, this means that it cannot override a superclass method or satisfy
6525a protocol requirement.
6526
6527Because a direct method cannot be overridden, it is an error to perform
6528a `super` message send of one.
6529
6530Although a message send of a direct method causes the method to be called
6531directly as if it were a C function, it still obeys Objective-C semantics in other
6532ways:
6533
6534- If the receiver is `nil`, the message send does nothing and returns the zero value
6535 for the return type.
6536- A message send of a direct class method will cause the class to be initialized,
6537 including calling the `+initialize` method if present.
6538- The implicit `_cmd` parameter containing the method's selector is still defined.
6539 In order to minimize code-size costs, the implementation will not emit a reference
6540 to the selector if the parameter is unused within the method.
6541
6542Symbols for direct method implementations are implicitly given hidden
6543visibility, meaning that they can only be called within the same linkage unit.
6544
6545It is an error to do any of the following:
6546
6547- declare a direct method in a protocol,
6548- declare an override of a direct method with a method in a subclass,
6549- declare an override of a non-direct method with a direct method in a subclass,
6550- declare a method with different directness in different class interfaces, or
6551- implement a non-direct method (as declared in any class interface) with a direct method.
6552
6553If any of these rules would be violated if every method defined in an
6554`@implementation` within a single linkage unit were declared in an
6555appropriate class interface, the program is ill-formed with no diagnostic
6556required. If a violation of this rule is not diagnosed, behavior remains
6557well-defined; this paragraph is simply reserving the right to diagnose such
6558conflicts in the future, not to treat them as undefined behavior.
6559
6560Additionally, Clang will warn about any `@selector` expression that
6561names a selector that is only known to be used for direct methods.
6562
6563For the purpose of these rules, a "class interface" includes a class's primary
6564`@interface` block, its class extensions, its categories, its declared protocols,
6565and all the class interfaces of its superclasses.
6566
6567An Objective-C property can be declared with the `direct` property
6568attribute. If a direct property declaration causes an implicit declaration of
6569a getter or setter method (that is, if the given method is not explicitly
6570declared elsewhere), the method is declared to be direct.
6571
6572Some programmers may wish to make many methods direct at once. In order
6573to simplify this, the `objc_direct_members` attribute is provided; see its
6574documentation for more information.)reST";
6575
6576static const char AttrDoc_ObjCDirectMembers[] = R"reST(The `objc_direct_members` attribute can be placed on an Objective-C
6577`@interface` or `@implementation` to mark that methods declared
6578therein should be considered direct by default. See the documentation
6579for `objc_direct` for more information about direct methods.
6580
6581When `objc_direct_members` is placed on an `@interface` block, every
6582method in the block is considered to be declared as direct. This includes any
6583implicit method declarations introduced by property declarations. If the method
6584redeclares a non-direct method, the declaration is ill-formed, exactly as if the
6585method was annotated with the `objc_direct` attribute.
6586
6587When `objc_direct_members` is placed on an `@implementation` block,
6588methods defined in the block are considered to be declared as direct unless
6589they have been previously declared as non-direct in any interface of the class.
6590This includes the implicit method definitions introduced by synthesized
6591properties, including auto-synthesized properties.)reST";
6592
6593static const char AttrDoc_ObjCException[] = R"reST(No documentation.)reST";
6594
6595static const char AttrDoc_ObjCExplicitProtocolImpl[] = R"reST(No documentation.)reST";
6596
6597static const char AttrDoc_ObjCExternallyRetained[] = R"reST(The `objc_externally_retained` attribute can be applied to strong local
6598variables, functions, methods, or blocks to opt into
6599{ref}`externally-retained semantics <arc.misc.externally_retained>`.
6600
6601When applied to the definition of a function, method, or block, every parameter
6602of the function with implicit strong retainable object pointer type is
6603considered externally-retained, and becomes `const`. By explicitly annotating
6604a parameter with `__strong`, you can opt back into the default
6605non-externally-retained behavior for that parameter. For instance,
6606`first_param` is externally-retained below, but not `second_param`:
6607
6608```objc
6609__attribute__((objc_externally_retained))
6610void f(NSArray *first_param, __strong NSArray *second_param) {
6611 // ...
6612}
6613```
6614
6615Likewise, when applied to a strong local variable, that variable becomes
6616`const` and is considered externally-retained.
6617
6618When compiled without `-fobjc-arc`, this attribute is ignored.)reST";
6619
6620static const char AttrDoc_ObjCGC[] = R"reST(No documentation.)reST";
6621
6622static const char AttrDoc_ObjCIndependentClass[] = R"reST(No documentation.)reST";
6623
6624static const char AttrDoc_ObjCInertUnsafeUnretained[] = R"reST()reST";
6625
6626static const char AttrDoc_ObjCKindOf[] = R"reST(No documentation.)reST";
6627
6628static const char AttrDoc_ObjCMethodFamily[] = R"reST(Many methods in Objective-C have conventional meanings determined by their
6629selectors. It is sometimes useful to be able to mark a method as having a
6630particular conventional meaning despite not having the right selector, or as
6631not having the conventional meaning that its selector would suggest. For these
6632use cases, we provide an attribute to specifically describe the "method family"
6633that a method belongs to.
6634
6635**Usage**: `__attribute__((objc_method_family(X)))`, where `X` is one of
6636`none`, `alloc`, `copy`, `init`, `mutableCopy`, or `new`. This
6637attribute can only be placed at the end of a method declaration:
6638
6639```objc
6640- (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
6641```
6642
6643Users who do not wish to change the conventional meaning of a method, and who
6644merely want to document its non-standard retain and release semantics, should
6645use the retaining behavior attributes (`ns_returns_retained`,
6646`ns_returns_not_retained`, etc).
6647
6648Query for this feature with `__has_attribute(objc_method_family)`.)reST";
6649
6650static const char AttrDoc_ObjCNSObject[] = R"reST(No documentation.)reST";
6651
6652static const char AttrDoc_ObjCNonLazyClass[] = R"reST(This attribute can be added to an Objective-C `@interface` or
6653`@implementation` declaration to add the class to the list of non-lazily
6654initialized classes. A non-lazy class will be initialized eagerly when the
6655Objective-C runtime is loaded. This is required for certain system classes which
6656have instances allocated in non-standard ways, such as the classes for blocks
6657and constant strings. Adding this attribute is essentially equivalent to
6658providing a trivial `+load` method but avoids the (fairly small) load-time
6659overheads associated with defining and calling such a method.)reST";
6660
6661static const char AttrDoc_ObjCNonRuntimeProtocol[] = R"reST(The `objc_non_runtime_protocol` attribute can be used to mark that an
6662Objective-C protocol is only used during static type-checking and doesn't need
6663to be represented dynamically. This avoids several small code-size and run-time
6664overheads associated with handling the protocol's metadata. A non-runtime
6665protocol cannot be used as the operand of a `@protocol` expression, and
6666dynamic attempts to find it with `objc_getProtocol` will fail.
6667
6668If a non-runtime protocol inherits from any ordinary protocols, classes and
6669derived protocols that declare conformance to the non-runtime protocol will
6670dynamically list their conformance to those bare protocols.)reST";
6671
6672static const char AttrDoc_ObjCOwnership[] = R"reST(No documentation.)reST";
6673
6674static const char AttrDoc_ObjCPreciseLifetime[] = R"reST(No documentation.)reST";
6675
6676static const char AttrDoc_ObjCRequiresPropertyDefs[] = R"reST(No documentation.)reST";
6677
6678static const char AttrDoc_ObjCRequiresSuper[] = R"reST(Some Objective-C classes allow a subclass to override a particular method in a
6679parent class but expect that the overriding method also calls the overridden
6680method in the parent class. For these cases, we provide an attribute to
6681designate that a method requires a "call to `super`" in the overriding
6682method in the subclass.
6683
6684**Usage**: `__attribute__((objc_requires_super))`. This attribute can only
6685be placed at the end of a method declaration:
6686
6687```objc
6688- (void)foo __attribute__((objc_requires_super));
6689```
6690
6691This attribute can only be applied the method declarations within a class, and
6692not a protocol. Currently this attribute does not enforce any placement of
6693where the call occurs in the overriding method (such as in the case of
6694`-dealloc` where the call must appear at the end). It checks only that it
6695exists.
6696
6697Note that on both OS X and iOS that the Foundation framework provides a
6698convenience macro `NS_REQUIRES_SUPER` that provides syntactic sugar for this
6699attribute:
6700
6701```objc
6702- (void)foo NS_REQUIRES_SUPER;
6703```
6704
6705This macro is conditionally defined depending on the compiler's support for
6706this attribute. If the compiler does not support the attribute the macro
6707expands to nothing.
6708
6709Operationally, when a method has this annotation the compiler will warn if the
6710implementation of an override in a subclass does not call super. For example:
6711
6712```objc
6713warning: method possibly missing a [super AnnotMeth] call
6714- (void) AnnotMeth{};
6715 ^
6716```)reST";
6717
6718static const char AttrDoc_ObjCReturnsInnerPointer[] = R"reST(No documentation.)reST";
6719
6720static const char AttrDoc_ObjCRootClass[] = R"reST(No documentation.)reST";
6721
6722static const char AttrDoc_ObjCRuntimeName[] = R"reST(By default, the Objective-C interface or protocol identifier is used
6723in the metadata name for that object. The `objc_runtime_name`
6724attribute allows annotated interfaces or protocols to use the
6725specified string argument in the object's metadata name instead of the
6726default name.
6727
6728**Usage**: `__attribute__((objc_runtime_name("MyLocalName")))`. This attribute
6729can only be placed before an @protocol or @interface declaration:
6730
6731```objc
6732__attribute__((objc_runtime_name("MyLocalName")))
6733@interface Message
6734@end
6735```)reST";
6736
6737static const char AttrDoc_ObjCRuntimeVisible[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
6738visible to the Objective-C runtime but not to the linker. Classes annotated
6739with this attribute cannot be subclassed and cannot have categories defined for
6740them.)reST";
6741
6742static const char AttrDoc_ObjCSubclassingRestricted[] = R"reST(This attribute can be added to an Objective-C `@interface` declaration to
6743ensure that this class cannot be subclassed.)reST";
6744
6745static const char AttrDoc_OpenACCRoutineAnnot[] = R"reST()reST";
6746
6747static const char AttrDoc_OpenACCRoutineDecl[] = R"reST()reST";
6748
6749static const char AttrDoc_OpenCLAccess[] = R"reST(The access qualifiers must be used with image object arguments or pipe arguments
6750to declare if they are being read or written by a kernel or function.
6751
6752The `read_only`, `__read_only`, `write_only`, `__write_only`, `read_write`, and `__read_write`
6753names are reserved for use as access qualifiers and shall not be used otherwise.
6754
6755```c
6756kernel void
6757foo (read_only image2d_t imageA,
6758 write_only image2d_t imageB) {
6759 ...
6760}
6761```
6762
6763In the above example imageA is a read-only 2D image object, and imageB is a
6764write-only 2D image object.
6765
6766The `read_write` (or `__read_write`) qualifier cannot be used with pipe arguments.
6767
6768More details can be found in the OpenCL C language Spec v2.0, Section 6.6.)reST";
6769
6770static const char AttrDoc_OpenCLConstantAddressSpace[] = R"reST(The constant address space attribute signals that an object is located in
6771a constant (non-modifiable) memory region. It is available to all work items.
6772Any type can be annotated with the constant address space attribute. Objects
6773with the constant address space qualifier can be declared in any scope and must
6774have an initializer.)reST";
6775
6776static const char AttrDoc_OpenCLGenericAddressSpace[] = R"reST(The generic address space attribute is only available with OpenCL v2.0 and later.
6777It can be used with pointer types. Variables in global and local scope and
6778function parameters in non-kernel functions can have the generic address space
6779type attribute. It is intended to be a placeholder for any other address space
6780except for `__constant` in OpenCL code which can be used with multiple address
6781spaces.)reST";
6782
6783static const char AttrDoc_OpenCLGlobalAddressSpace[] = R"reST(The global address space attribute specifies that an object is allocated in
6784global memory, which is accessible by all work items. The content stored in this
6785memory area persists between kernel executions. Pointer types to the global
6786address space are allowed as function parameters or local variables. Starting
6787with OpenCL v2.0, the global address space can be used with global (program
6788scope) variables and static local variable as well.)reST";
6789
6790static const char AttrDoc_OpenCLGlobalDeviceAddressSpace[] = R"reST(The `global_device` and `global_host` address space attributes specify that
6791an object is allocated in global memory on the device/host. It helps to
6792distinguish USM (Unified Shared Memory) pointers that access global device
6793memory from those that access global host memory. These new address spaces are
6794a subset of the `__global/opencl_global` address space, the full address space
6795set model for OpenCL 2.0 with the extension looks as follows:
6796
6797```text
6798generic->global->host
6799 ->device
6800 ->private
6801 ->local
6802constant
6803```
6804
6805As `global_device` and `global_host` are a subset of
6806`__global/opencl_global` address spaces it is allowed to convert
6807`global_device` and `global_host` address spaces to
6808`__global/opencl_global` address spaces (following ISO/IEC TR 18037 5.1.3
6809"Address space nesting and rules for pointers").
6810
6811These attributes are deprecated and may be removed in a future version of Clang.)reST";
6812
6813static const char AttrDoc_OpenCLGlobalHostAddressSpace[] = R"reST(The `global_device` and `global_host` address space attributes specify that
6814an object is allocated in global memory on the device/host. It helps to
6815distinguish USM (Unified Shared Memory) pointers that access global device
6816memory from those that access global host memory. These new address spaces are
6817a subset of the `__global/opencl_global` address space, the full address space
6818set model for OpenCL 2.0 with the extension looks as follows:
6819
6820```text
6821generic->global->host
6822 ->device
6823 ->private
6824 ->local
6825constant
6826```
6827
6828As `global_device` and `global_host` are a subset of
6829`__global/opencl_global` address spaces it is allowed to convert
6830`global_device` and `global_host` address spaces to
6831`__global/opencl_global` address spaces (following ISO/IEC TR 18037 5.1.3
6832"Address space nesting and rules for pointers").
6833
6834These attributes are deprecated and may be removed in a future version of Clang.)reST";
6835
6836static const char AttrDoc_OpenCLIntelReqdSubGroupSize[] = R"reST(The optional attribute intel_reqd_sub_group_size can be used to indicate that
6837the kernel must be compiled and executed with the specified subgroup size. When
6838this attribute is present, get_max_sub_group_size() is guaranteed to return the
6839specified integer value. This is important for the correctness of many subgroup
6840algorithms, and in some cases may be used by the compiler to generate more optimal
6841code. See
6842[`cl_intel_required_subgroup_size`](https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.html)
6843for details.)reST";
6844
6845static const char AttrDoc_OpenCLLocalAddressSpace[] = R"reST(The local address space specifies that an object is allocated in the local (work
6846group) memory area, which is accessible to all work items in the same work
6847group. The content stored in this memory region is not accessible after
6848the kernel execution ends. In a kernel function scope, any variable can be in
6849the local address space. In other scopes, only pointer types to the local address
6850space are allowed. Local address space variables cannot have an initializer.)reST";
6851
6852static const char AttrDoc_OpenCLPrivateAddressSpace[] = R"reST(The private address space specifies that an object is allocated in the private
6853(work item) memory. Other work items cannot access the same memory area and its
6854content is destroyed after work item execution ends. Local variables can be
6855declared in the private address space. Function arguments are always in the
6856private address space. Kernel function arguments of a pointer or an array type
6857cannot point to the private address space.)reST";
6858
6859static const char AttrDoc_OpenCLUnrollHint[] = R"reST(The `opencl_unroll_hint` attribute qualifier can be used to specify that a loop
6860(for, while and do loops) can be unrolled. This attribute qualifier can be
6861used to specify full unrolling or partial unrolling by a specified amount.
6862This is a compiler hint and the compiler may ignore this directive. See
6863[OpenCL v2.0](https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf)
6864s6.11.5 for details.)reST";
6865
6866static const char AttrDoc_OptimizeNone[] = R"reST(The `optnone` attribute suppresses essentially all optimizations
6867on a function or method, regardless of the optimization level applied to
6868the compilation unit as a whole. This is particularly useful when you
6869need to debug a particular function, but it is infeasible to build the
6870entire application without optimization. Avoiding optimization on the
6871specified function can improve the quality of the debugging information
6872for that function.
6873
6874This attribute is incompatible with the `always_inline` and `minsize`
6875attributes.
6876
6877Note that this attribute does not apply recursively to nested functions such as
6878lambdas or blocks when using declaration-specific attribute syntaxes such as double
6879square brackets (`[[]]`) or `__attribute__`. The `#pragma` syntax can be
6880used to apply the attribute to all functions, including nested functions, in a
6881range of source code.)reST";
6882
6883static const char AttrDoc_OverflowBehavior[] = R"reST(The `overflow_behavior` attribute provides fine-grained, type-level control
6884over how arithmetic operations on an integer type behave on overflow. It may be
6885applied to a `typedef`, to a variable or data member, or to an integer type
6886directly, and accepts one of two behaviors as its argument:
6887
6888- `wrap`: arithmetic on the attributed type wraps on overflow, using two's
6889 complement semantics. This is equivalent to `-fwrapv` but scoped to the
6890 attributed type, and works for both signed and unsigned types. UBSan's
6891 `signed-integer-overflow`, `unsigned-integer-overflow`,
6892 `implicit-signed-integer-truncation`, and
6893 `implicit-unsigned-integer-truncation` checks are suppressed for the type.
6894- `trap`: arithmetic on the attributed type is checked for overflow, enabling
6895 overflow checks for the type even when `-fwrapv` is in effect globally.
6896
6897```c++
6898typedef unsigned int __attribute__((overflow_behavior(trap))) non_wrapping_uint;
6899
6900non_wrapping_uint add_one(non_wrapping_uint a) {
6901 return a + 1; // Overflow is checked for this operation.
6902}
6903
6904int mul_alot(int n) {
6905 int __attribute__((overflow_behavior(wrap))) a = n;
6906 return a * 1337; // Overflow is not checked and is well-defined.
6907}
6908```
6909
6910The keyword spellings `__ob_wrap` and `__ob_trap` are equivalent to
6911`overflow_behavior(wrap)` and `overflow_behavior(trap)` respectively.
6912
6913The attribute wholly overrides global flags (`-ftrapv`, `-fwrapv`,
6914sanitizers, and Sanitizer Special Case Lists) for the attributed type. It can
6915only be applied to integer types.
6916
6917This feature is experimental and must be enabled with the `-cc1` option
6918`-fexperimental-overflow-behavior-types`. For full details on promotion and
6919conversion rules, pointer semantics, diagnostics, and interaction with
6920sanitizers, see {doc}`OverflowBehaviorTypes`.)reST";
6921
6922static const char AttrDoc_Overloadable[] = R"reST(Clang provides support for C++ function overloading in C. Function overloading
6923in C is introduced using the `overloadable` attribute. For example, one
6924might provide several overloaded versions of a `tgsin` function that invokes
6925the appropriate standard function computing the sine of a value with `float`,
6926`double`, or `long double` precision:
6927
6928```c
6929#include <math.h>
6930float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
6931double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
6932long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
6933```
6934
6935Given these declarations, one can call `tgsin` with a `float` value to
6936receive a `float` result, with a `double` to receive a `double` result,
6937etc. Function overloading in C follows the rules of C++ function overloading
6938to pick the best overload given the call arguments, with a few C-specific
6939semantics:
6940
6941- Conversion from `float` or `double` to `long double` is ranked as a
6942 floating-point promotion (per C99) rather than as a floating-point conversion
6943 (as in C++).
6944- A conversion from a pointer of type `T*` to a pointer of type `U*` is
6945 considered a pointer conversion (with conversion rank) if `T` and `U` are
6946 compatible types.
6947- A conversion from type `T` to a value of type `U` is permitted if `T`
6948 and `U` are compatible types. This conversion is given "conversion" rank.
6949- If no viable candidates are otherwise available, we allow a conversion from a
6950 pointer of type `T*` to a pointer of type `U*`, where `T` and `U` are
6951 incompatible. This conversion is ranked below all other types of conversions.
6952 Please note: `U` lacking qualifiers that are present on `T` is sufficient
6953 for `T` and `U` to be incompatible.
6954
6955The declaration of `overloadable` functions is restricted to function
6956declarations and definitions. If a function is marked with the `overloadable`
6957attribute, then all declarations and definitions of functions with that name,
6958except for at most one (see the note below about unmarked overloads), must have
6959the `overloadable` attribute. In addition, redeclarations of a function with
6960the `overloadable` attribute must have the `overloadable` attribute, and
6961redeclarations of a function without the `overloadable` attribute must *not*
6962have the `overloadable` attribute. e.g.,
6963
6964```c
6965int f(int) __attribute__((overloadable));
6966float f(float); // error: declaration of "f" must have the "overloadable" attribute
6967int f(int); // error: redeclaration of "f" must have the "overloadable" attribute
6968
6969int g(int) __attribute__((overloadable));
6970int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
6971
6972int h(int);
6973int h(int) __attribute__((overloadable)); // error: declaration of "h" must not
6974 // have the "overloadable" attribute
6975```
6976
6977Functions marked `overloadable` must have prototypes. Therefore, the
6978following code is ill-formed:
6979
6980```c
6981int h() __attribute__((overloadable)); // error: h does not have a prototype
6982```
6983
6984However, `overloadable` functions are allowed to use a ellipsis even if there
6985are no named parameters (as is permitted in C++). This feature is particularly
6986useful when combined with the `unavailable` attribute:
6987
6988```c++
6989void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
6990```
6991
6992Functions declared with the `overloadable` attribute have their names mangled
6993according to the same rules as C++ function names. For example, the three
6994`tgsin` functions in our motivating example get the mangled names
6995`_Z5tgsinf`, `_Z5tgsind`, and `_Z5tgsine`, respectively. There are two
6996caveats to this use of name mangling:
6997
6998- Future versions of Clang may change the name mangling of functions overloaded
6999 in C, so you should not depend on an specific mangling. To be completely
7000 safe, we strongly urge the use of `static inline` with `overloadable`
7001 functions.
7002- The `overloadable` attribute has almost no meaning when used in C++,
7003 because names will already be mangled and functions are already overloadable.
7004 However, when an `overloadable` function occurs within an `extern "C"`
7005 linkage specification, its name *will* be mangled in the same way as it
7006 would in C.
7007
7008For the purpose of backwards compatibility, at most one function with the same
7009name as other `overloadable` functions may omit the `overloadable`
7010attribute. In this case, the function without the `overloadable` attribute
7011will not have its name mangled.
7012
7013For example:
7014
7015```c
7016// Notes with mangled names assume Itanium mangling.
7017int f(int);
7018int f(double) __attribute__((overloadable));
7019void foo() {
7020 f(5); // Emits a call to f (not _Z1fi, as it would with an overload that
7021 // was marked with overloadable).
7022 f(1.0); // Emits a call to _Z1fd.
7023}
7024```
7025
7026Support for unmarked overloads is not present in some versions of clang. You may
7027query for it using `__has_extension(overloadable_unmarked)`.
7028
7029Query for this attribute with `__has_attribute(overloadable)`.)reST";
7030
7031static const char AttrDoc_Override[] = R"reST()reST";
7032
7033static const char AttrDoc_Owner[] = R"reST(:::{Note}
7034This attribute is experimental and its effect on analysis is subject to change in
7035a future version of clang.
7036:::
7037
7038The attribute `[[gsl::Owner(T)]]` applies to structs and classes that own an
7039object of type `T`:
7040
7041```
7042class [[gsl::Owner(int)]] IntOwner {
7043private:
7044 int value;
7045public:
7046 int *getInt() { return &value; }
7047};
7048```
7049
7050The argument `T` is optional and is ignored.
7051This attribute may be used by analysis tools and has no effect on code
7052generation. A `void` argument means that the class can own any type.
7053
7054See [Pointer](#pointer) for an example.)reST";
7055
7056static const char AttrDoc_Ownership[] = R"reST(:::{note}
7057In order for the Clang Static Analyzer to acknowledge these attributes, the
7058`Optimistic` config needs to be set to true for the checker
7059`unix.DynamicMemoryModeling`:
7060
7061`-Xclang -analyzer-config -Xclang unix.DynamicMemoryModeling:Optimistic=true`
7062:::
7063
7064These attributes are used by the Clang Static Analyzer's dynamic memory modeling
7065facilities to mark custom allocating/deallocating functions.
7066
7067All 3 attributes' first parameter of type string is the type of the allocation:
7068`malloc`, `new`, etc. to allow for catching {ref}`mismatched deallocation
7069<unix-MismatchedDeallocator>` bugs. The allocation type can be any string, e.g.
7070a function annotated with
7071returning a piece of memory of type `lasagna` but freed with a function
7072annotated to release `cheese` typed memory will result in mismatched
7073deallocation warning.
7074
7075The (currently) only allocation type having special meaning is `malloc` --
7076the Clang Static Analyzer makes sure that allocating functions annotated with
7077`malloc` are treated like they used the standard `malloc()`, and can be
7078safely deallocated with the standard `free()`.
7079
7080- Use `ownership_returns` to mark a function as an allocating function.
7081 It takes 1 or 2 arguments.
7082 The first argument is a user-provided identifier representing the "kind" of the allocation.
7083 This is basically what is enforced when checking the deallocation. This is mandatory.
7084 The second argument is optional.
7085 It represents the index of the parameter that represents the allocation size in bytes (counting from 1).
7086 The referenced parameter must have some integral type.
7087 This attribute may appear at most once per declaration.
7088 If this argument is not set, then tooling, such as the Clang Static Analyzer,
7089 won't be able to reason about the size of the allocation, thus check potential out-of-bounds accesses.
7090 However, such tooling could still warn if the wrong deallocation function
7091 was used for the `ownership_returns` attributed resource.
7092 If forward declarations have this attribute, those must have the same arguments.
7093- Use `ownership_takes` to mark a function as a deallocating function. Takes 2
7094 arguments: the allocation type, and the index of the parameter that is being
7095 deallocated (counting from 1).
7096- Use `ownership_holds` to mark that a function takes over the ownership of a
7097 piece of memory and will free it at some unspecified point in the future. Like
7098 `ownership_takes`, this takes 2 arguments: the allocation type, and the
7099 index of the parameter whose ownership will be taken over (counting from 1).
7100
7101The annotations `ownership_takes` and `ownership_holds` both prevent memory
7102leak reports (concerning the specified parameter); the difference between them
7103is that using taken memory is a use-after-free error, while using held memory
7104is assumed to be legitimate. However, releasing the held memory or passing it
7105to another holding call is reported by the analyzer as an "attempt to release
7106non-owned memory".
7107
7108Example:
7109
7110```c
7111// Denotes that my_malloc will return with a dynamically allocated piece of
7112// memory using malloc().
7113void __attribute((ownership_returns(malloc))) *my_malloc(size_t sz);
7114
7115// 'sz' (parameter 1) is the allocation size.
7116void __attribute((ownership_returns(malloc, 1))) *my_sized_malloc(size_t sz);
7117
7118// Denotes that my_free will deallocate its argument using free().
7119void __attribute((ownership_takes(malloc, 1))) my_free(void *);
7120
7121// Denotes that my_hold will take over the ownership of its argument that was
7122// allocated via malloc().
7123void __attribute((ownership_holds(malloc, 1))) my_hold(void *);
7124```
7125
7126Further reading about dynamic memory modeling in the Clang Static Analyzer is
7127found in these checker docs:
7128{ref}`unix.Malloc <unix-Malloc>`, {ref}`unix.MallocSizeof <unix-MallocSizeof>`,
7129{ref}`unix.MismatchedDeallocator <unix-MismatchedDeallocator>`,
7130{ref}`cplusplus.NewDelete <cplusplus-NewDelete>`,
7131{ref}`cplusplus.NewDeleteLeaks <cplusplus-NewDeleteLeaks>`,
7132{ref}`optin.taint.TaintedAlloc <optin-taint-TaintedAlloc>`.
7133Mind that many more checkers are affected by dynamic memory modeling changes to
7134some extent.
7135
7136Further reading for other annotations:
7137{doc}`Static Analyzer source annotations <analyzer/user-docs/Annotations>`.)reST";
7138
7139static const char AttrDoc_Packed[] = R"reST(No documentation.)reST";
7140
7141static const char AttrDoc_ParamTypestate[] = R"reST(This attribute specifies expectations about function parameters. Calls to an
7142function with annotated parameters will issue a warning if the corresponding
7143argument isn't in the expected state. The attribute is also used to set the
7144initial state of the parameter when analyzing the function's body.)reST";
7145
7146static const char AttrDoc_Pascal[] = R"reST(No documentation.)reST";
7147
7148static const char AttrDoc_PassObjectSize[] = R"reST(:::{Note}
7149The mangling of functions with parameters that are annotated with
7150`pass_object_size` is subject to change. You can get around this by
7151using `__asm__("foo")` to explicitly name your functions, thus preserving
7152your ABI; also, non-overloadable C functions with `pass_object_size` are
7153not mangled.
7154:::
7155
7156The `pass_object_size(Type)` attribute can be placed on function parameters to
7157instruct clang to call `__builtin_object_size(param, Type)` at each callsite
7158of said function, and implicitly pass the result of this call in as an invisible
7159argument of type `size_t` directly after the parameter annotated with
7160`pass_object_size`. Clang will also replace any calls to
7161`__builtin_object_size(param, Type)` in the function by said implicit
7162parameter.
7163
7164Example usage:
7165
7166```c
7167int bzero1(char *const p __attribute__((pass_object_size(0))))
7168 __attribute__((noinline)) {
7169 int i = 0;
7170 for (/**/; i < (int)__builtin_object_size(p, 0); ++i) {
7171 p[i] = 0;
7172 }
7173 return i;
7174}
7175
7176int main() {
7177 char chars[100];
7178 int n = bzero1(&chars[0]);
7179 assert(n == sizeof(chars));
7180 return 0;
7181}
7182```
7183
7184If successfully evaluating `__builtin_object_size(param, Type)` at the
7185callsite is not possible, then the "failed" value is passed in. So, using the
7186definition of `bzero1` from above, the following code would exit cleanly:
7187
7188```c
7189int main2(int argc, char *argv[]) {
7190 int n = bzero1(argv);
7191 assert(n == -1);
7192 return 0;
7193}
7194```
7195
7196`pass_object_size` plays a part in overload resolution. If two overload
7197candidates are otherwise equally good, then the overload with one or more
7198parameters with `pass_object_size` is preferred. This implies that the choice
7199between two identical overloads both with `pass_object_size` on one or more
7200parameters will always be ambiguous; for this reason, having two such overloads
7201is illegal. For example:
7202
7203```c++
7204#define PS(N) __attribute__((pass_object_size(N)))
7205// OK
7206void Foo(char *a, char *b); // Overload A
7207// OK -- overload A has no parameters with pass_object_size.
7208void Foo(char *a PS(0), char *b PS(0)); // Overload B
7209// Error -- Same signature (sans pass_object_size) as overload B, and both
7210// overloads have one or more parameters with the pass_object_size attribute.
7211void Foo(void *a PS(0), void *b);
7212
7213// OK
7214void Bar(void *a PS(0)); // Overload C
7215// OK
7216void Bar(char *c PS(1)); // Overload D
7217
7218void main() {
7219 char known[10], *unknown;
7220 Foo(unknown, unknown); // Calls overload B
7221 Foo(known, unknown); // Calls overload B
7222 Foo(unknown, known); // Calls overload B
7223 Foo(known, known); // Calls overload B
7224
7225 Bar(known); // Calls overload D
7226 Bar(unknown); // Calls overload D
7227}
7228```
7229
7230Currently, `pass_object_size` is a bit restricted in terms of its usage:
7231
7232- Only one use of `pass_object_size` is allowed per parameter.
7233- It is an error to take the address of a function with `pass_object_size` on
7234 any of its parameters. If you wish to do this, you can create an overload
7235 without `pass_object_size` on any parameters.
7236- It is an error to apply the `pass_object_size` attribute to parameters that
7237 are not pointers. Additionally, any parameter that `pass_object_size` is
7238 applied to must be marked `const` at its function's definition.
7239
7240Clang also supports the `pass_dynamic_object_size` attribute, which behaves
7241identically to `pass_object_size`, but evaluates a call to
7242`__builtin_dynamic_object_size` at the callee instead of
7243`__builtin_object_size`. `__builtin_dynamic_object_size` provides some extra
7244runtime checks when the object size can't be determined at compile-time. You can
7245read more about `__builtin_dynamic_object_size` in
7246{ref}`Evaluating Object Size <langext-evaluating-object-size>`.)reST";
7247
7248static const char AttrDoc_PatchableFunctionEntry[] = R"reST(`__attribute__((patchable_function_entry(N,M,Section)))` is used to generate M
7249NOPs before the function entry and N-M NOPs after the function entry, with a record of
7250the entry stored in section `Section`. This attribute takes precedence over the
7251command line option `-fpatchable-function-entry=N,M,Section`. `M` defaults to 0
7252if omitted. `Section` defaults to the `-fpatchable-function-entry` section name if
7253set, or to `__patchable_function_entries` otherwise.
7254
7255This attribute is only supported on
7256aarch64/aarch64-be/loongarch32/loongarch64/riscv32/riscv64/i386/x86-64/ppc/ppc64/ppc64le/s390x targets.
7257For ppc/ppc64 targets, AIX is still not supported.)reST";
7258
7259static const char AttrDoc_Pcs[] = R"reST(On ARM targets, this attribute can be used to select calling conventions
7260similar to `stdcall` on x86. Valid parameter values are "aapcs" and
7261"aapcs-vfp".)reST";
7262
7263static const char AttrDoc_Personality[] = R"reST(`__attribute__((personality(<routine>)))` is used to specify a personality
7264routine that is different from the language that is being used to implement the
7265function. This is a targeted, low-level feature aimed at language runtime
7266implementors who write runtime support code in C/C++ but need that code to
7267participate in a foreign language's exception-handling or unwinding model.
7268
7269A personality routine is a language-specific callback attached to each stack
7270frame that the unwinder invokes to determine whether that frame handles a given
7271exception and what cleanup actions to perform. It effectively colors the
7272language-agnostic unwinding mechanism with language-specific semantics, enabling
7273different languages to coexist on the same call stack while each interpreting
7274exceptions according to their own rules.)reST";
7275
7276static const char AttrDoc_Pointer[] = R"reST(:::{Note}
7277This attribute is experimental and its effect on analysis is subject to change in
7278a future version of clang.
7279:::
7280
7281The attribute `[[gsl::Pointer(T)]]` applies to structs and classes that behave
7282like pointers to an object of type `T`:
7283
7284```
7285class [[gsl::Pointer(int)]] IntPointer {
7286private:
7287 int *valuePointer;
7288public:
7289 IntPointer(const IntOwner&);
7290 int *getInt() { return valuePointer; }
7291};
7292```
7293
7294The argument `T` is optional and is ignored.
7295This attribute may be used by analysis tools and has no effect on code
7296generation. A `void` argument means that the pointer can point to any type.
7297
7298Example:
7299When constructing an instance of a class annotated like this (a Pointer) from
7300an instance of a class annotated with `[[gsl::Owner]]` (an Owner),
7301then the analysis will consider the Pointer to point inside the Owner.
7302When the Owner's lifetime ends, it will consider the Pointer to be dangling.
7303
7304```c++
7305int f() {
7306 IntPointer P(IntOwner{}); // P "points into" a temporary IntOwner object
7307 P.getInt(); // P is dangling
7308}
7309```
7310
7311**Transparent Member Functions**
7312
7313The analysis automatically tracks certain member functions of `[[gsl::Pointer]]` types
7314that provide transparent access to the pointed-to object. These include:
7315
7316- Dereference operators: `operator*`, `operator->`
7317- Data access methods: `data()`, `c_str()`, `get()`
7318- Iterator operations: `begin()`, `end()`, `rbegin()`, `rend()`, `cbegin()`, `cend()`, `crbegin()`, `crend()`, `operator+`, `operator-`, `operator++`, `operator--`
7319
7320When these methods return pointers, view types, or references, the analysis treats them as
7321transparently borrowing from the same object that the pointer itself borrows from,
7322enabling detection of use-after-free through these access patterns:
7323
7324```c++
7325// For example, .data() here returns a borrow to 's' instead of 'v'.
7326const char* f() {
7327 std::string s = "hello";
7328 std::string_view v = s; // warning: address of stack memory returned
7329 return v.data(); // note: returned here
7330}
7331
7332const MyObj& g(MyObj obj) {
7333 View v = obj; // warning: address of stack memory returned
7334 return *v; // note: returned here
7335}
7336```
7337
7338This tracking also applies to range-based for loops, where the `begin()` and `end()`
7339iterators are used to access elements:
7340
7341```c++
7342std::string_view f(std::vector<std::string> vec) {
7343 for (const std::string& s : vec) { // warning: address of stack memory returned
7344 return s; // note: returned here
7345 }
7346}
7347```
7348
7349**Container Template Specialization**
7350
7351If a template class is annotated with `[[gsl::Owner]]`, and the first
7352instantiated template argument is a pointer type (raw pointer, or `[[gsl::Pointer]]`),
7353the analysis will consider the instantiated class as a container of the pointer.
7354When constructing such an object from a GSL owner object, the analysis will
7355assume that the container holds a pointer to the owner object. Consequently,
7356when the owner object is destroyed, the pointer will be considered dangling.
7357
7358```c++
7359int f() {
7360 std::vector<std::string_view> v = {std::string()}; // v holds a dangling pointer.
7361 std::optional<std::string_view> o = std::string(); // o holds a dangling pointer.
7362}
7363```)reST";
7364
7365static const char AttrDoc_PointerAuth[] = R"reST(The `__ptrauth` qualifier allows the programmer to directly control
7366how pointers are signed when they are stored in a particular variable.
7367This can be used to strengthen the default protections of pointer
7368authentication and make it more difficult for an attacker to escalate
7369an ability to alter memory into full control of a process.
7370
7371```c
7372#include <ptrauth.h>
7373
7374typedef void (*my_callback)(const void*);
7375my_callback __ptrauth(ptrauth_key_process_dependent_code, 1, 0xe27a) callback;
7376```
7377
7378The first argument to `__ptrauth` is the name of the signing key.
7379Valid key names for the target are defined in `<ptrauth.h>`.
7380
7381The second argument to `__ptrauth` is a flag (0 or 1) specifying whether
7382the object should use address discrimination.
7383
7384The third argument to `__ptrauth` is a 16-bit non-negative integer which
7385allows additional discrimination between objects.)reST";
7386
7387static const char AttrDoc_PointerFieldProtection[] = R"reST(No documentation.)reST";
7388
7389static const char AttrDoc_PragmaClangBSSSection[] = R"reST()reST";
7390
7391static const char AttrDoc_PragmaClangDataSection[] = R"reST()reST";
7392
7393static const char AttrDoc_PragmaClangRelroSection[] = R"reST()reST";
7394
7395static const char AttrDoc_PragmaClangRodataSection[] = R"reST()reST";
7396
7397static const char AttrDoc_PragmaClangTextSection[] = R"reST()reST";
7398
7399static const char AttrDoc_PreferredName[] = R"reST(The `preferred_name` attribute can be applied to a class template, and
7400specifies a preferred way of naming a specialization of the template. The
7401preferred name will be used whenever the corresponding template specialization
7402would otherwise be printed in a diagnostic or similar context.
7403
7404The preferred name must be a typedef or type alias declaration that refers to a
7405specialization of the class template (not including any type qualifiers). In
7406general this requires the template to be declared at least twice. For example:
7407
7408```c++
7409template<typename T> struct basic_string;
7410using string = basic_string<char>;
7411using wstring = basic_string<wchar_t>;
7412template<typename T> struct [[clang::preferred_name(string),
7413 clang::preferred_name(wstring)]] basic_string {
7414 // ...
7415};
7416```
7417
7418Note that the `preferred_name` attribute will be ignored when the compiler
7419writes a C++20 Module interface now. This is due to a compiler issue
7420(<https://github.com/llvm/llvm-project/issues/56490>) that blocks users to modularize
7421declarations with `preferred_name`. This is intended to be fixed in the future.)reST";
7422
7423static const char AttrDoc_PreferredType[] = R"reST(This attribute allows adjusting the type of a bit-field in debug information.
7424This can be helpful when a bit-field is intended to store an enumeration value,
7425but has to be specified as having the enumeration's underlying type in order to
7426facilitate compiler optimizations or bit-field packing behavior. Normally, the
7427underlying type is what is emitted in debug information, which can make it hard
7428for debuggers to know to map a bit-field's value back to a particular enumeration.
7429
7430```c++
7431enum Colors { Red, Green, Blue };
7432
7433struct S {
7434 [[clang::preferred_type(Colors)]] unsigned ColorVal : 2;
7435 [[clang::preferred_type(bool)]] unsigned UseAlternateColorSpace : 1;
7436} s = { Green, false };
7437```
7438
7439Without the attribute, a debugger is likely to display the value `1` for `ColorVal`
7440and `0` for `UseAlternateColorSpace`. With the attribute, the debugger may now
7441display `Green` and `false` instead.
7442
7443This can be used to map a bit-field to an arbitrary type that isn't integral
7444or an enumeration type. For example:
7445
7446```c++
7447struct A {
7448 short a1;
7449 short a2;
7450};
7451
7452struct B {
7453 [[clang::preferred_type(A)]] unsigned b1 : 32 = 0x000F'000C;
7454};
7455```
7456
7457will associate the type `A` with the `b1` bit-field and is intended to display
7458something like this in the debugger:
7459
7460```text
7461Process 2755547 stopped
7462* thread #1, name = 'test-preferred-', stop reason = step in
7463 frame #0: 0x0000555555555148 test-preferred-type`main at test.cxx:13:14
7464 10 int main()
7465 11 {
7466 12 B b;
7467-> 13 return b.b1;
7468 14 }
7469(lldb) v -T
7470(B) b = {
7471 (A:32) b1 = {
7472 (short) a1 = 12
7473 (short) a2 = 15
7474 }
7475}
7476```
7477
7478Note that debuggers may not be able to handle more complex mappings, and so
7479this usage is debugger-dependent.)reST";
7480
7481static const char AttrDoc_PreserveAll[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
7482a function. The `preserve_all` calling convention attempts to make the code
7483in the caller even less intrusive than the `preserve_most` calling convention.
7484This calling convention also behaves identical to the `C` calling convention
7485on how arguments and return values are passed, but it uses a different set of
7486caller/callee-saved registers. This removes the burden of saving and
7487recovering a large register set before and after the call in the caller. If
7488the arguments are passed in callee-saved registers, then they will be
7489preserved by the callee across the call. This doesn't apply for values
7490returned in callee-saved registers.
7491
7492- On X86-64 the callee preserves all general purpose registers, except for
7493 R11. R11 can be used as a scratch register. Furthermore it also preserves
7494 all floating-point registers (XMMs/YMMs).
7495- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
7496 X16-X18. Furthermore it also preserves lower 128 bits of V8-V31 SIMD - floating
7497 point registers.
7498
7499The idea behind this convention is to support calls to runtime functions
7500that don't need to call out to any other functions.
7501
7502This calling convention, like the `preserve_most` calling convention, will be
7503used by a future version of the Objective-C runtime and should be considered
7504experimental at this time.)reST";
7505
7506static const char AttrDoc_PreserveMost[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
7507a function. The `preserve_most` calling convention attempts to make the code
7508in the caller as unintrusive as possible. This convention behaves identically
7509to the `C` calling convention on how arguments and return values are passed,
7510but it uses a different set of caller/callee-saved registers. This alleviates
7511the burden of saving and recovering a large register set before and after the
7512call in the caller. If the arguments are passed in callee-saved registers,
7513then they will be preserved by the callee across the call. This doesn't
7514apply for values returned in callee-saved registers.
7515
7516- On X86-64 the callee preserves all general purpose registers, except for
7517 R11. R11 can be used as a scratch register. Floating-point registers
7518 (XMMs/YMMs) are not preserved and need to be saved by the caller.
7519- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
7520 X16-X18.
7521
7522The idea behind this convention is to support calls to runtime functions
7523that have a hot path and a cold path. The hot path is usually a small piece
7524of code that doesn't use many registers. The cold path might need to call out to
7525another function and therefore only needs to preserve the caller-saved
7526registers, which haven't already been saved by the caller. The
7527`preserve_most` calling convention is very similar to the `cold` calling
7528convention in terms of caller/callee-saved registers, but they are used for
7529different types of function calls. `coldcc` is for function calls that are
7530rarely executed, whereas `preserve_most` function calls are intended to be
7531on the hot path and definitely executed a lot. Furthermore `preserve_most`
7532doesn't prevent the inliner from inlining the function call.
7533
7534This convention was created to optimize certain runtime calls to the
7535Objective-C runtime, but it is not limited to that runtime; it is also used by
7536other runtimes and libraries, such as the Swift runtime and the Linux kernel.
7537The current implementation only supports X86-64 and AArch64, but the intention
7538is to support more architectures in the future.)reST";
7539
7540static const char AttrDoc_PreserveNone[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of a function.
7541The `preserve_none` calling convention tries to preserve as few general
7542registers as possible. So all general registers are caller saved registers. It
7543also uses more general registers to pass arguments. This attribute doesn't
7544impact floating-point registers. `preserve_none`'s ABI is still unstable, and
7545may be changed in the future.
7546
7547- On X86-64, only RSP and RBP are preserved by the callee.
7548 Registers R12, R13, R14, R15, RDI, RSI, RDX, RCX, R8, R9, R11, and RAX now can
7549 be used to pass function arguments. Floating-point registers (XMMs/YMMs) still
7550 follow the C calling convention.
7551- On AArch64, only LR and FP are preserved by the callee.
7552 Registers X20-X28, X0-X7, and X9-X14 are used to pass function arguments.
7553 X8, X16-X19, SIMD and floating-point registers follow the AAPCS calling
7554 convention. X15 is not available for argument passing on Windows, but is
7555 used to pass arguments on other platforms.)reST";
7556
7557static const char AttrDoc_PtGuardedBy[] = R"reST(No documentation.)reST";
7558
7559static const char AttrDoc_PtGuardedVar[] = R"reST(No documentation.)reST";
7560
7561static const char AttrDoc_Ptr32[] = R"reST(The `__ptr32` qualifier represents a native pointer on a 32-bit system. On a
756264-bit system, a pointer with `__ptr32` is extended to a 64-bit pointer. The
7563`__sptr` and `__uptr` qualifiers can be used to specify whether the pointer
7564is sign extended or zero extended. This qualifier is enabled under
7565`-fms-extensions`.)reST";
7566
7567static const char AttrDoc_Ptr64[] = R"reST(The `__ptr64` qualifier represents a native pointer on a 64-bit system. On a
756832-bit system, a `__ptr64` pointer is truncated to a 32-bit pointer. This
7569qualifier is enabled under `-fms-extensions`.)reST";
7570
7571static const char AttrDoc_Pure[] = R"reST(No documentation.)reST";
7572
7573static const char AttrDoc_RISCVInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt))` attribute on RISCV
7574targets. This attribute may be attached to a function definition and instructs
7575the backend to generate appropriate function entry/exit code so that it can be
7576used directly as an interrupt service routine.
7577
7578Permissible values for this parameter are `machine`, `supervisor`,
7579`rnmi`, `qci-nest`, `qci-nonest`, `SiFive-CLIC-preemptible`, and
7580`SiFive-CLIC-stack-swap`. If there is no parameter, then it defaults to
7581`machine`.
7582
7583The `rnmi` value is used for resumable non-maskable interrupts. It requires the
7584standard Smrnmi extension.
7585
7586The `qci-nest` and `qci-nonest` values require Qualcomm's Xqciint extension
7587and are used for Machine-mode Interrupts and Machine-mode Non-maskable
7588interrupts. These use the following instructions from Xqciint to save and
7589restore interrupt state to the stack -- the `qci-nest` value will use
7590`qc.c.mienter.nest` and the `qci-nonest` value will use `qc.c.mienter` to
7591begin the interrupt handler. Both of these will use `qc.c.mileaveret` to
7592restore the state and return to the previous context.
7593
7594The `SiFive-CLIC-preemptible` and `SiFive-CLIC-stack-swap` values are used
7595for machine-mode interrupts. For `SiFive-CLIC-preemptible` interrupts, the
7596values of `mcause` and `mepc` are saved onto the stack, and interrupts are
7597re-enabled. For `SiFive-CLIC-stack-swap` interrupts, the stack pointer is
7598swapped with `mscratch` before its first use and after its last use.
7599
7600The SiFive CLIC values may be combined with each other and with the `machine`
7601attribute value. Any other combination of different values is not allowed.
7602
7603Repeated interrupt attribute on the same declaration will cause a warning
7604to be emitted. In case of repeated declarations, the last one prevails.
7605
7606References:
7607- [GCC RISC-V Attributes](https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html)
7608- [The RISC-V Instruction Set Manual Volume II: Privileged Architecture Version 1.10](https://docs.riscv.org/reference/isa/v1.10/_attachments/riscv-privileged.pdf)
7609- [Xqci extension v0.13](https://github.com/quic/riscv-unified-db/releases/tag/Xqci-0.13.0)
7610- [SiFive Interrupt Cookbook Version 1.2](https://sifive.cdn.prismic.io/sifive/d1984d2b-c9b9-4c91-8de0-d68a5e64fa0f_sifive-interrupt-cookbook-v1p2.pdf))reST";
7611
7612static const char AttrDoc_RISCVVLSCC[] = R"reST(The `riscv_vls_cc` attribute can be applied to a function. Functions
7613declared with this attribute will utilize the standard fixed-length vector
7614calling convention variant instead of the default calling convention defined by
7615the ABI. This variant aims to pass fixed-length vectors via vector registers,
7616if possible, rather than through general-purpose registers.)reST";
7617
7618static const char AttrDoc_RISCVVectorCC[] = R"reST(The `riscv_vector_cc` attribute can be applied to a function. It preserves 15
7619registers namely, v1-v7 and v24-v31 as callee-saved. Callers thus don't need
7620to save these registers before function calls, and callees only need to save
7621them if they use them.)reST";
7622
7623static const char AttrDoc_RandomizeLayout[] = R"reST(The attribute `randomize_layout`, when attached to a C structure, selects it
7624for structure layout field randomization; a compile-time hardening technique. A
7625"seed" value, is specified via the `-frandomize-layout-seed=` command line flag.
7626For example:
7627
7628```bash
7629SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
7630make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
7631```
7632
7633You can also supply the seed in a file with `-frandomize-layout-seed-file=`.
7634For example:
7635
7636```bash
7637od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
7638make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
7639```
7640
7641The randomization is deterministic based for a given seed, so the entire
7642program should be compiled with the same seed, but keep the seed safe
7643otherwise.
7644
7645The attribute `no_randomize_layout`, when attached to a C structure,
7646instructs the compiler that this structure should not have its field layout
7647randomized.)reST";
7648
7649static const char AttrDoc_ReadOnlyPlacement[] = R"reST(This attribute is attached to a structure, class or union declaration.
7650
7651: When attached to a record declaration/definition, it checks if all instances
7652 of this type can be placed in the read-only data segment of the program. If it
7653 finds an instance that can not be placed in a read-only segment, the compiler
7654 emits a warning at the source location where the type was used.
7655
7656 Examples:
7657 - `struct __attribute__((enforce_read_only_placement)) Foo;`
7658 - `struct __attribute__((enforce_read_only_placement)) Bar { ... };`
7659
7660 Both `Foo` and `Bar` types have the `enforce_read_only_placement` attribute.
7661
7662 The goal of introducing this attribute is to assist developers with writing secure
7663 code. A `const`-qualified global is generally placed in the read-only section
7664 of the memory that has additional run time protection from malicious writes. By
7665 attaching this attribute to a declaration, the developer can express the intent
7666 to place all instances of the annotated type in the read-only program memory.
7667
7668 Note 1: The attribute doesn't guarantee that the object will be placed in the
7669 read-only data segment as it does not instruct the compiler to ensure such
7670 a placement. It emits a warning if something in the code can be proven to prevent
7671 an instance from being placed in the read-only data segment.
7672
7673 Note 2: Currently, clang only checks if all global declarations of a given type `T`
7674 are `const`-qualified. The following conditions would also prevent the data to be
7675 put into read only segment, but the corresponding warnings are not yet implemented.
7676
7677 1. An instance of type `T` is allocated on the heap/stack.
7678 2. Type `T` defines/inherits a mutable field.
7679 3. Type `T` defines/inherits non-constexpr constructor(s) for initialization.
7680 4. A field of type `T` is defined by type `Q`, which does not bear the
7681 `enforce_read_only_placement` attribute.
7682 5. A type `Q` inherits from type `T` and it does not have the
7683 `enforce_read_only_placement` attribute.)reST";
7684
7685static const char AttrDoc_ReentrantCapability[] = R"reST(No documentation.)reST";
7686
7687static const char AttrDoc_RegCall[] = R"reST(On x86 targets, this attribute changes the calling convention to
7688[`__regcall`][__regcall] convention. This convention aims to pass as many arguments
7689as possible in registers. It also tries to utilize registers for the
7690return value whenever it is possible.
7691
7692[__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";
7693
7694static const char AttrDoc_Reinitializes[] = R"reST(The `reinitializes` attribute can be applied to a non-static, non-const C++
7695member function to indicate that this member function reinitializes the entire
7696object to a known state, independent of the previous state of the object.
7697
7698This attribute can be interpreted by static analyzers that warn about uses of an
7699object that has been left in an indeterminate state by a move operation. If a
7700member function marked with the `reinitializes` attribute is called on a
7701moved-from object, the analyzer can conclude that the object is no longer in an
7702indeterminate state.
7703
7704A typical example where this attribute would be used is on functions that clear
7705a container class:
7706
7707```c++
7708template <class T>
7709class Container {
7710public:
7711 ...
7712 [[clang::reinitializes]] void Clear();
7713 ...
7714};
7715```)reST";
7716
7717static const char AttrDoc_ReleaseCapability[] = R"reST(Marks a function as releasing a capability.)reST";
7718
7719static const char AttrDoc_ReleaseHandle[] = R"reST(If a function parameter is annotated with `release_handle(tag)` it is assumed to
7720close the handle. It is also assumed to require an open handle to work with. The
7721attribute requires a string literal argument to identify the handle being released.
7722
7723```c++
7724zx_status_t zx_handle_close(zx_handle_t handle [[clang::release_handle("tag")]]);
7725```)reST";
7726
7727static const char AttrDoc_ReqdWorkGroupSize[] = R"reST(No documentation.)reST";
7728
7729static const char AttrDoc_RequiresCapability[] = R"reST(No documentation.)reST";
7730
7731static const char AttrDoc_Restrict[] = R"reST(The `malloc` attribute has two forms with different functionality. The first
7732is when it is used without arguments, where it marks that a function acts like
7733a system memory allocation function, returning a pointer to allocated storage
7734that does not alias storage from any other object accessible to the caller.
7735
7736The second form is when `malloc` takes one or two arguments. The first
7737argument names a function that should be associated with this function as its
7738deallocation function. When this form is used, it enables the compiler to
7739diagnose when the incorrect deallocation function is used with this variable.
7740However the associated warning, spelled `-Wmismatched-dealloc` in GCC, is not
7741yet implemented in clang.)reST";
7742
7743static const char AttrDoc_Retain[] = R"reST(This attribute, when attached to a function or variable definition, prevents
7744section garbage collection in the linker. It does not prevent other discard
7745mechanisms, such as archive member selection, and COMDAT group resolution.
7746
7747If the compiler does not emit the definition, e.g. because it was not used in
7748the translation unit or the compiler was able to eliminate all of the uses,
7749this attribute has no effect. This attribute is typically combined with the
7750`used` attribute to force the definition to be emitted and preserved into the
7751final linked image.
7752
7753This attribute is only necessary on ELF targets; other targets prevent section
7754garbage collection by the linker when using the `used` attribute alone.
7755Using the attributes together should result in consistent behavior across
7756targets.
7757
7758This attribute requires the linker to support the `SHF_GNU_RETAIN` extension.
7759This support is available in GNU `ld` and `gold` as of binutils 2.36, as
7760well as in `ld.lld` 13.)reST";
7761
7762static const char AttrDoc_ReturnTypestate[] = R"reST(The `return_typestate` attribute can be applied to functions or parameters.
7763When applied to a function the attribute specifies the state of the returned
7764value. The function's body is checked to ensure that it always returns a value
7765in the specified state. On the caller side, values returned by the annotated
7766function are initialized to the given state.
7767
7768When applied to a function parameter it modifies the state of an argument after
7769a call to the function returns. The function's body is checked to ensure that
7770the parameter is in the expected state before returning.)reST";
7771
7772static const char AttrDoc_ReturnsNonNull[] = R"reST(The `returns_nonnull` attribute indicates that a particular function (or
7773Objective-C method) always returns a non-null pointer. For example, a
7774particular system `malloc` might be defined to terminate a process when
7775memory is not available rather than returning a null pointer:
7776
7777```c
7778extern void * malloc (size_t size) __attribute__((returns_nonnull));
7779```
7780
7781The `returns_nonnull` attribute implies that returning a null pointer is
7782undefined behavior, which the optimizer may take advantage of. The `_Nonnull`
7783type qualifier indicates that a pointer cannot be null in a more general manner
7784(because it is part of the type system) and does not imply undefined behavior,
7785making it more widely applicable)reST";
7786
7787static const char AttrDoc_ReturnsTwice[] = R"reST(No documentation.)reST";
7788
7789static const char AttrDoc_RootSignature[] = R"reST(The `RootSignature` attribute applies to HLSL entry functions to define what
7790types of resources are bound to the graphics pipeline.
7791
7792For details about the use and specification of Root Signatures please see here:
7793<https://learn.microsoft.com/en-us/windows/win32/direct3d12/root-signatures>)reST";
7794
7795static const char AttrDoc_SPtr[] = R"reST(The `__sptr` qualifier specifies that a 32-bit pointer should be sign
7796extended when converted to a 64-bit pointer.)reST";
7797
7798static const char AttrDoc_SYCLConstantAddressSpace[] = R"reST(:::{Note}
7799These attributes are intended for use in the implementation of SYCL run-time
7800libraries and should not be used in any other context.
7801Programmers writing code intended to conform to the SYCL specification should
7802use the address space facilities specified in the following sections of the
7803SYCL 2020 specification.
7804
7805* [4.7.2, "Buffers"][SYCL-2020-4.7.2]
7806* [4.7.6, "Accessors"][SYCL-2020-4.7.6]
7807* [4.7.7, "Address space classes"][SYCL-2020-4.7.7]
7808* [F.7, "sycl_khr_static_addrspace_cast"][SYCL-2020-F.7]
7809* [F.8, "sycl_khr_dynamic_addrspace_cast"][SYCL-2020-F.8]
7810:::
7811
7812The SYCL address space attributes listed below correspond to the five address
7813spaces described by
7814[SYCL 2020 section 3.8.2, "SYCL device memory model"][SYCL-2020-3.8.2] and
7815[SYCL 2020 section 4.7.7, "Address space classes"][SYCL-2020-4.7.7].
7816
7817::: {list-table} SYCL address space attributes
7818:header-rows: 1
7819
7820* - Address space attribute
7821 - SYCL address space
7822 - Description
7823* - `[[clang::sycl_global]]`
7824 - global
7825 - A memory region accessible by all work-items executing on a device.
7826* - `[[clang::sycl_local]]`
7827 - local
7828 - A memory region accessible by all work-items of a single work-group.
7829* - `[[clang::sycl_private]]`
7830 - private
7831 - A memory region that is private to a single work-item.
7832* - `[[clang::sycl_generic]]`
7833 - generic
7834 - A virtual memory region from which the global, local, and private memory
7835 regions may all be accessed.
7836* - `[[clang::sycl_constant]]`
7837 - constant
7838 - (*deprecated*) A memory region that holds constant data for an executing
7839 kernel.
7840:::
7841
7842The SYCL address space attributes are type attributes that may be applied to
7843non-function non-reference types to specify an address space qualified type.
7844
7845A type with a SYCL address space qualifier is a distinct type from the
7846otherwise unattributed type. For example, `int *` and `int [[clang::sycl_global]]*`
7847designate distinct pointer types which participate in overload resolution and
7848template specialization.
7849
7850The top-level type of a variable declaration cannot have a SYCL address space
7851qualifier. For example:
7852
7853```c++
7854int [[clang::sycl_global]] gv; // error: the top-level type has an address space qualifier.
7855int [[clang::sycl_global]] *pgi; // ok; the address space qualifier is on the pointee type.
7856```
7857
7858Conversions between SYCL address space attributed types are permitted as
7859follows.
7860
7861- Types attributed with the global, local, or private address space attributes
7862 are implicitly convertible to matching types with the generic address space
7863 attribute.
7864
7865The mapping of SYCL address spaces to physical address spaces is target
7866dependent.
7867
7868For OpenCL device targets, the SYCL address space attributes are aligned with
7869the [OpenCL address space attributes](#opencl-address-spaces) such that, e.g.,
7870`int [[clang::sycl_global]]*` and `int [[clang::opencl_global]]*` specify
7871distinct types both of which map to the same underlying address space.
7872Corresponding SYCL and OpenCL address space attributed types are implicitly
7873convertible; other conversions are permitted as described above; e.g.,
7874`int [[clang::sycl_global]]*` is implicitly convertible to
7875`int [[clang::opencl_generic]]*`.
7876
7877[SYCL-2020-3.8.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_sycl_device_memory_model
7878[SYCL-2020-4.7.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:buffers
7879[SYCL-2020-4.7.6]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:accessors
7880[SYCL-2020-4.7.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_address_space_classes
7881[SYCL-2020-F.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-static-addrspace-cast
7882[SYCL-2020-F.8]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-dynamic-addrspace-cast)reST";
7883
7884static const char AttrDoc_SYCLExternal[] = R"reST(The `sycl_external` attribute indicates that a function defined in another
7885translation unit may be called by a device function defined in the current
7886translation unit or, if defined in the current translation unit, the function
7887may be called by device functions defined in other translation units.
7888The attribute is intended for use in the implementation of the `SYCL_EXTERNAL`
7889macro as specified in section 5.10.1, "SYCL functions and member functions
7890linkage", of the SYCL 2020 specification.
7891
7892The attribute only appertains to functions and only those that meet the
7893following requirements:
7894
7895- Has external linkage
7896- Is not explicitly defined as deleted (the function may be an explicitly
7897 defaulted function that is defined as deleted)
7898
7899The attribute shall be present on the first declaration of a function and
7900may optionally be present on subsequent declarations.
7901
7902SYCL prohibits calls to a variadic function in device functions. Since there is
7903little reason to emit a function that cannot be called, the attribute is ignored,
7904with a warning, when applied to a variadic function.
7905
7906When compiling for a SYCL device target that does not support the generic
7907address space, the function shall not specify a raw pointer or reference type
7908as the return type or as a parameter type.
7909See section 5.10, "SYCL offline linking", of the SYCL 2020 specification.
7910The following examples demonstrate the use of this attribute:
7911
7912```c++
7913[[clang::sycl_external]] void Foo(); // Ok.
7914
7915[[clang::sycl_external]] void Bar() { /* ... */ } // Ok.
7916
7917[[clang::sycl_external]] extern void Baz(); // Ok.
7918
7919[[clang::sycl_external]] static void Quux() { /* ... */ } // error: Quux() has internal linkage.
7920
7921[[clang::sycl_external]] void Corge(int, ...); // warning: attribute ignored; Corge() is variadic.
7922```)reST";
7923
7924static const char AttrDoc_SYCLGenericAddressSpace[] = R"reST(:::{Note}
7925These attributes are intended for use in the implementation of SYCL run-time
7926libraries and should not be used in any other context.
7927Programmers writing code intended to conform to the SYCL specification should
7928use the address space facilities specified in the following sections of the
7929SYCL 2020 specification.
7930
7931* [4.7.2, "Buffers"][SYCL-2020-4.7.2]
7932* [4.7.6, "Accessors"][SYCL-2020-4.7.6]
7933* [4.7.7, "Address space classes"][SYCL-2020-4.7.7]
7934* [F.7, "sycl_khr_static_addrspace_cast"][SYCL-2020-F.7]
7935* [F.8, "sycl_khr_dynamic_addrspace_cast"][SYCL-2020-F.8]
7936:::
7937
7938The SYCL address space attributes listed below correspond to the five address
7939spaces described by
7940[SYCL 2020 section 3.8.2, "SYCL device memory model"][SYCL-2020-3.8.2] and
7941[SYCL 2020 section 4.7.7, "Address space classes"][SYCL-2020-4.7.7].
7942
7943::: {list-table} SYCL address space attributes
7944:header-rows: 1
7945
7946* - Address space attribute
7947 - SYCL address space
7948 - Description
7949* - `[[clang::sycl_global]]`
7950 - global
7951 - A memory region accessible by all work-items executing on a device.
7952* - `[[clang::sycl_local]]`
7953 - local
7954 - A memory region accessible by all work-items of a single work-group.
7955* - `[[clang::sycl_private]]`
7956 - private
7957 - A memory region that is private to a single work-item.
7958* - `[[clang::sycl_generic]]`
7959 - generic
7960 - A virtual memory region from which the global, local, and private memory
7961 regions may all be accessed.
7962* - `[[clang::sycl_constant]]`
7963 - constant
7964 - (*deprecated*) A memory region that holds constant data for an executing
7965 kernel.
7966:::
7967
7968The SYCL address space attributes are type attributes that may be applied to
7969non-function non-reference types to specify an address space qualified type.
7970
7971A type with a SYCL address space qualifier is a distinct type from the
7972otherwise unattributed type. For example, `int *` and `int [[clang::sycl_global]]*`
7973designate distinct pointer types which participate in overload resolution and
7974template specialization.
7975
7976The top-level type of a variable declaration cannot have a SYCL address space
7977qualifier. For example:
7978
7979```c++
7980int [[clang::sycl_global]] gv; // error: the top-level type has an address space qualifier.
7981int [[clang::sycl_global]] *pgi; // ok; the address space qualifier is on the pointee type.
7982```
7983
7984Conversions between SYCL address space attributed types are permitted as
7985follows.
7986
7987- Types attributed with the global, local, or private address space attributes
7988 are implicitly convertible to matching types with the generic address space
7989 attribute.
7990
7991The mapping of SYCL address spaces to physical address spaces is target
7992dependent.
7993
7994For OpenCL device targets, the SYCL address space attributes are aligned with
7995the [OpenCL address space attributes](#opencl-address-spaces) such that, e.g.,
7996`int [[clang::sycl_global]]*` and `int [[clang::opencl_global]]*` specify
7997distinct types both of which map to the same underlying address space.
7998Corresponding SYCL and OpenCL address space attributed types are implicitly
7999convertible; other conversions are permitted as described above; e.g.,
8000`int [[clang::sycl_global]]*` is implicitly convertible to
8001`int [[clang::opencl_generic]]*`.
8002
8003[SYCL-2020-3.8.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_sycl_device_memory_model
8004[SYCL-2020-4.7.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:buffers
8005[SYCL-2020-4.7.6]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:accessors
8006[SYCL-2020-4.7.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_address_space_classes
8007[SYCL-2020-F.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-static-addrspace-cast
8008[SYCL-2020-F.8]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-dynamic-addrspace-cast)reST";
8009
8010static const char AttrDoc_SYCLGlobalAddressSpace[] = R"reST(:::{Note}
8011These attributes are intended for use in the implementation of SYCL run-time
8012libraries and should not be used in any other context.
8013Programmers writing code intended to conform to the SYCL specification should
8014use the address space facilities specified in the following sections of the
8015SYCL 2020 specification.
8016
8017* [4.7.2, "Buffers"][SYCL-2020-4.7.2]
8018* [4.7.6, "Accessors"][SYCL-2020-4.7.6]
8019* [4.7.7, "Address space classes"][SYCL-2020-4.7.7]
8020* [F.7, "sycl_khr_static_addrspace_cast"][SYCL-2020-F.7]
8021* [F.8, "sycl_khr_dynamic_addrspace_cast"][SYCL-2020-F.8]
8022:::
8023
8024The SYCL address space attributes listed below correspond to the five address
8025spaces described by
8026[SYCL 2020 section 3.8.2, "SYCL device memory model"][SYCL-2020-3.8.2] and
8027[SYCL 2020 section 4.7.7, "Address space classes"][SYCL-2020-4.7.7].
8028
8029::: {list-table} SYCL address space attributes
8030:header-rows: 1
8031
8032* - Address space attribute
8033 - SYCL address space
8034 - Description
8035* - `[[clang::sycl_global]]`
8036 - global
8037 - A memory region accessible by all work-items executing on a device.
8038* - `[[clang::sycl_local]]`
8039 - local
8040 - A memory region accessible by all work-items of a single work-group.
8041* - `[[clang::sycl_private]]`
8042 - private
8043 - A memory region that is private to a single work-item.
8044* - `[[clang::sycl_generic]]`
8045 - generic
8046 - A virtual memory region from which the global, local, and private memory
8047 regions may all be accessed.
8048* - `[[clang::sycl_constant]]`
8049 - constant
8050 - (*deprecated*) A memory region that holds constant data for an executing
8051 kernel.
8052:::
8053
8054The SYCL address space attributes are type attributes that may be applied to
8055non-function non-reference types to specify an address space qualified type.
8056
8057A type with a SYCL address space qualifier is a distinct type from the
8058otherwise unattributed type. For example, `int *` and `int [[clang::sycl_global]]*`
8059designate distinct pointer types which participate in overload resolution and
8060template specialization.
8061
8062The top-level type of a variable declaration cannot have a SYCL address space
8063qualifier. For example:
8064
8065```c++
8066int [[clang::sycl_global]] gv; // error: the top-level type has an address space qualifier.
8067int [[clang::sycl_global]] *pgi; // ok; the address space qualifier is on the pointee type.
8068```
8069
8070Conversions between SYCL address space attributed types are permitted as
8071follows.
8072
8073- Types attributed with the global, local, or private address space attributes
8074 are implicitly convertible to matching types with the generic address space
8075 attribute.
8076
8077The mapping of SYCL address spaces to physical address spaces is target
8078dependent.
8079
8080For OpenCL device targets, the SYCL address space attributes are aligned with
8081the [OpenCL address space attributes](#opencl-address-spaces) such that, e.g.,
8082`int [[clang::sycl_global]]*` and `int [[clang::opencl_global]]*` specify
8083distinct types both of which map to the same underlying address space.
8084Corresponding SYCL and OpenCL address space attributed types are implicitly
8085convertible; other conversions are permitted as described above; e.g.,
8086`int [[clang::sycl_global]]*` is implicitly convertible to
8087`int [[clang::opencl_generic]]*`.
8088
8089[SYCL-2020-3.8.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_sycl_device_memory_model
8090[SYCL-2020-4.7.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:buffers
8091[SYCL-2020-4.7.6]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:accessors
8092[SYCL-2020-4.7.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_address_space_classes
8093[SYCL-2020-F.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-static-addrspace-cast
8094[SYCL-2020-F.8]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-dynamic-addrspace-cast)reST";
8095
8096static const char AttrDoc_SYCLKernel[] = R"reST(The `sycl_kernel` attribute specifies that a function template will be used
8097to outline device code and to generate an OpenCL kernel.
8098Here is a code example of the SYCL program, which demonstrates the compiler's
8099outlining job:
8100
8101```c++
8102int foo(int x) { return ++x; }
8103
8104using namespace cl::sycl;
8105queue Q;
8106buffer<int, 1> a(range<1>{1024});
8107Q.submit([&](handler& cgh) {
8108 auto A = a.get_access<access::mode::write>(cgh);
8109 cgh.parallel_for<init_a>(range<1>{1024}, [=](id<1> index) {
8110 A[index] = index[0] + foo(42);
8111 });
8112}
8113```
8114
8115A C++ function object passed to the `parallel_for` is called a "SYCL kernel".
8116A SYCL kernel defines the entry point to the "device part" of the code. The
8117compiler will emit all symbols accessible from a "kernel". In this code
8118example, the compiler will emit "foo" function. More details about the
8119compilation of functions for the device part can be found in the SYCL 1.2.1
8120specification Section 6.4.
8121To show to the compiler entry point to the "device part" of the code, the SYCL
8122runtime can use the `sycl_kernel` attribute in the following way:
8123
8124```c++
8125namespace cl {
8126namespace sycl {
8127class handler {
8128 template <typename KernelName, typename KernelType/*, ...*/>
8129 __attribute__((sycl_kernel)) void sycl_kernel_function(KernelType KernelFuncObj) {
8130 // ...
8131 KernelFuncObj();
8132 }
8133
8134 template <typename KernelName, typename KernelType, int Dims>
8135 void parallel_for(range<Dims> NumWorkItems, KernelType KernelFunc) {
8136#ifdef __SYCL_DEVICE_ONLY__
8137 sycl_kernel_function<KernelName, KernelType, Dims>(KernelFunc);
8138#else
8139 // Host implementation
8140#endif
8141 }
8142};
8143} // namespace sycl
8144} // namespace cl
8145```
8146
8147The compiler will also generate an OpenCL kernel using the function marked with
8148the `sycl_kernel` attribute.
8149Here is the list of SYCL device compiler expectations with regard to the
8150function marked with the `sycl_kernel` attribute:
8151
8152- The function must be a template with at least two type template parameters.
8153 The compiler generates an OpenCL kernel and uses the first template parameter
8154 as a unique name for the generated OpenCL kernel. The host application uses
8155 this unique name to invoke the OpenCL kernel generated for the SYCL kernel
8156 specialized by this name and second template parameter `KernelType` (which
8157 might be an unnamed function object type).
8158- The function must have at least one parameter. The first parameter is
8159 required to be a function object type (named or unnamed i.e. lambda). The
8160 compiler uses function object type fields to generate OpenCL kernel
8161 parameters.
8162- The function must return void. The compiler reuses the body of marked functions to
8163 generate the OpenCL kernel body, and the OpenCL kernel must return `void`.
8164
8165The SYCL kernel in the previous code sample meets these expectations.)reST";
8166
8167static const char AttrDoc_SYCLKernelEntryPoint[] = R"reST(The `sycl_kernel_entry_point` attribute facilitates the launch of a SYCL
8168kernel and the generation of an offload kernel entry point, sometimes called
8169a SYCL kernel caller function, suitable for invoking a SYCL kernel on an
8170offload device. The attribute is intended for use in the implementation of
8171SYCL kernel invocation functions like the `single_task` and `parallel_for`
8172member functions of the `sycl::handler` class specified in section 4.9.4,
8173"Command group `handler` class", of the SYCL 2020 specification.
8174
8175The attribute requires a single type argument that meets the requirements for
8176a SYCL kernel name as described in section 5.2, "Naming of kernels", of the
8177SYCL 2020 specification. A unique kernel name type is required for each
8178function declared with the attribute. The attribute may not first appear on a
8179declaration that follows a definition of the function.
8180
8181The attribute only appertains to functions and only those that meet the
8182following requirements.
8183
8184- Has a non-deduced `void` return type.
8185- Is not a constructor or destructor.
8186- Is not a non-static member function with an explicit object parameter.
8187- Is not a C variadic function.
8188- Is not a coroutine.
8189- Is not defined as deleted or as defaulted.
8190- Is not defined with a function try block.
8191- Is not declared with the `constexpr` or `consteval` specifiers.
8192- Is not declared with the `[[noreturn]]` attribute.
8193
8194Use in the implementation of a SYCL kernel invocation function might look as
8195follows.
8196
8197```c++
8198namespace sycl {
8199class handler {
8200 template<typename KernelName, typename... Ts>
8201 void sycl_kernel_launch(const char* kernelSymbol, Ts&&... kernelArgs) {
8202 // This code will run on the host and is responsible for calling functions
8203 // appropriate for the desired offload backend (OpenCL, CUDA, HIP,
8204 // Level Zero, etc...) to copy the kernel arguments denoted by kernelArgs
8205 // to a device and to schedule an invocation of the offload kernel entry
8206 // point denoted by kernelSymbol with the copied arguments.
8207 }
8208
8209 template<typename KernelName, typename KernelType>
8210 [[ clang::sycl_kernel_entry_point(KernelName) ]]
8211 void kernel_entry_point(KernelType kernelFunc) {
8212 // This code will run on the device. The call to kernelFunc() invokes
8213 // the SYCL kernel.
8214 kernelFunc();
8215 }
8216
8217public:
8218 template<typename KernelName, typename KernelType>
8219 void single_task(const KernelType& kernelFunc) {
8220 // This code will run on the host. kernel_entry_point() is called to
8221 // trigger generation of an offload kernel entry point and to schedule
8222 // an invocation of it on a device with kernelFunc (a SYCL kernel object)
8223 // passed as a kernel argument. This call will result in an implicit call
8224 // to sycl_kernel_launch() with the symbol name for the generated offload
8225 // kernel entry point passed as the first function argument followed by
8226 // kernelFunc.
8227 kernel_entry_point<KernelName>(kernelFunc);
8228 }
8229};
8230} // namespace sycl
8231```
8232
8233A SYCL kernel object is a callable object of class type that is constructed on
8234a host, often via a lambda expression, and then passed to a SYCL kernel
8235invocation function to be executed on an offload device. The `kernelFunc`
8236parameters in the example code above correspond to SYCL kernel objects.
8237
8238A SYCL kernel object type is required to satisfy the device copyability
8239requirements specified in section 3.13.1, "Device copyable", of the SYCL 2020
8240specification. Additionally, any data members of the kernel object type are
8241required to satisfy section 4.12.4, "Rules for parameter passing to kernels".
8242For most types, these rules require that the type is trivially copyable.
8243However, the SYCL specification mandates that certain special SYCL types, such
8244as `sycl::accessor` and `sycl::stream`, be device copyable even if they are
8245not trivially copyable. These types require special handling because they cannot
8246necessarily be copied to device memory as if by `memcpy()`.
8247
8248The SYCL kernel object and its data members constitute the parameters of an
8249offload kernel. An offload kernel consists of an offload entry point function
8250and the set of all functions and variables that are directly or indirectly used
8251by the entry point function.
8252
8253A SYCL kernel invocation function is responsible for performing the following
8254tasks (likely with the help of an offload backend like OpenCL):
8255
82561. Identifying the offload kernel entry point to be used for the SYCL kernel.
82572. Validating that the SYCL kernel object type and its data members meet the
8258 SYCL device copyability and kernel parameter requirements noted above.
82593. Copying the SYCL kernel object and any other kernel arguments to device
8260 memory including any special handling required for SYCL special types.
82614. Initiating execution of the offload kernel entry point.
8262
8263The offload kernel entry point for a SYCL kernel performs the following tasks:
8264
82651. Calling the `operator()` member function of the SYCL kernel object.
8266
8267The `sycl_kernel_entry_point` attribute facilitates or automates these tasks
8268by providing generation of an offload kernel entry point with a unique symbol
8269name, type checking of kernel argument requirements, and initiation of kernel
8270execution via synthesized calls to a `sycl_kernel_launch` template.
8271
8272A function declared with the `sycl_kernel_entry_point` attribute specifies
8273the parameters and body of an offload entry point function. Consider the
8274following call to the `single_task()` SYCL kernel invocation function assuming
8275an implementation similar to the one shown above.
8276
8277```c++
8278struct S { int i; };
8279void f(sycl::handler &handler, sycl::stream &sout, S s) {
8280 handler.single_task<struct KN>([=] {
8281 sout << "The value of s.i is " << s.i << "\n";
8282 });
8283}
8284```
8285
8286The SYCL kernel object is the result of the lambda expression. The call to
8287`kernel_entry_point()` via the call to `single_task()` triggers the
8288generation of an offload kernel entry point function that looks approximately
8289as follows.
8290
8291```c++
8292void sycl-kernel-caller-for-KN(kernel-type kernelFunc) {
8293 kernelFunc();
8294}
8295```
8296
8297There are a few items worthy of note:
8298
82991. `sycl-kernel-caller-for-KN` is an exposition only name; the actual name
8300 generated for an entry point is an implementation detail and subject to
8301 change. However, the name will incorporate the SYCL kernel name, `KN`,
8302 that was passed as the `KernelName` template parameter to
8303 `single_task()` and eventually provided as the argument to the
8304 `sycl_kernel_entry_point` attribute in order to ensure that a unique
8305 name is generated for each entry point. There is a one-to-one correspondence
8306 between SYCL kernel names and offload kernel entry points.
83072. The SYCL kernel is a lambda closure type and therefore has no name;
8308 `kernel-type` is substituted above and corresponds to the `KernelType`
8309 template parameter deduced in the call to `single_task()`.
83103. The parameter and the call to `kernelFunc()` in the function body
8311 correspond to the definition of `kernel_entry_point()` as called by
8312 `single_task()`.
83134. The parameter is type checked for conformance with the SYCL device
8314 copyability and kernel parameter requirements.
8315
8316Within `single_task()`, the call to `kernel_entry_point()` is effectively
8317replaced with a synthesized call to a `sycl_kernel_launch` template that
8318looks approximately as follows.
8319
8320```c++
8321sycl_kernel_launch<KN>("sycl-kernel-caller-for-KN", kernelFunc);
8322```
8323
8324There are a few items worthy of note:
8325
83261. Lookup for the `sycl_kernel_launch` template is performed as if from the
8327 body of the (possibly instantiated) definition of `kernel_entry_point()`.
8328 If name lookup or overload resolution fails, the program is ill-formed.
8329 If the selected overload is a non-static member function, then `this` is
8330 passed as the implicit object parameter.
83312. Function arguments passed to `sycl_kernel_launch()` are passed
8332 as if by `std::move(x)`.
83333. The `sycl_kernel_launch` template is expected to be provided by the SYCL
8334 library implementation. It is responsible for copying the kernel arguments
8335 to device memory and for scheduling execution of the generated offload
8336 kernel entry point identified by the symbol name passed as the first
8337 function argument. `sycl-kernel-caller-for-KN` is substituted above for
8338 the actual symbol name that would be generated for the offload kernel entry
8339 point.
8340
8341It is not necessary for a function declared with the `sycl_kernel_entry_point`
8342attribute to be called for the offload kernel entry point to be emitted. For
8343inline functions and function templates, any ODR-use will suffice. For other
8344functions, an ODR-use is not required; the offload kernel entry point will be
8345emitted if the function is defined. In any case, a call to the function is
8346required for the synthesized call to `sycl_kernel_launch()` to occur.
8347
8348A function declared with the `sycl_kernel_entry_point` attribute may include
8349an exception specification. If a non-throwing exception specification is
8350present, an exception propagating from the implicit call to the
8351`sycl_kernel_launch` template will result in a call to `std::terminate()`.
8352Otherwise, such an exception will propagate normally.
8353
8354Functions declared with the `sycl_kernel_entry_point` attribute are not
8355limited to the simple example shown above. They may have additional template
8356parameters, declare additional function parameters, and have complex control
8357flow in the function body. The function must abide by the language feature
8358restrictions described in section 5.4, "Language restrictions for device
8359functions" in the SYCL 2020 specification. If the function is a non-static
8360member function, `this` shall not be used in a potentially evaluated
8361expression.)reST";
8362
8363static const char AttrDoc_SYCLLocalAddressSpace[] = R"reST(:::{Note}
8364These attributes are intended for use in the implementation of SYCL run-time
8365libraries and should not be used in any other context.
8366Programmers writing code intended to conform to the SYCL specification should
8367use the address space facilities specified in the following sections of the
8368SYCL 2020 specification.
8369
8370* [4.7.2, "Buffers"][SYCL-2020-4.7.2]
8371* [4.7.6, "Accessors"][SYCL-2020-4.7.6]
8372* [4.7.7, "Address space classes"][SYCL-2020-4.7.7]
8373* [F.7, "sycl_khr_static_addrspace_cast"][SYCL-2020-F.7]
8374* [F.8, "sycl_khr_dynamic_addrspace_cast"][SYCL-2020-F.8]
8375:::
8376
8377The SYCL address space attributes listed below correspond to the five address
8378spaces described by
8379[SYCL 2020 section 3.8.2, "SYCL device memory model"][SYCL-2020-3.8.2] and
8380[SYCL 2020 section 4.7.7, "Address space classes"][SYCL-2020-4.7.7].
8381
8382::: {list-table} SYCL address space attributes
8383:header-rows: 1
8384
8385* - Address space attribute
8386 - SYCL address space
8387 - Description
8388* - `[[clang::sycl_global]]`
8389 - global
8390 - A memory region accessible by all work-items executing on a device.
8391* - `[[clang::sycl_local]]`
8392 - local
8393 - A memory region accessible by all work-items of a single work-group.
8394* - `[[clang::sycl_private]]`
8395 - private
8396 - A memory region that is private to a single work-item.
8397* - `[[clang::sycl_generic]]`
8398 - generic
8399 - A virtual memory region from which the global, local, and private memory
8400 regions may all be accessed.
8401* - `[[clang::sycl_constant]]`
8402 - constant
8403 - (*deprecated*) A memory region that holds constant data for an executing
8404 kernel.
8405:::
8406
8407The SYCL address space attributes are type attributes that may be applied to
8408non-function non-reference types to specify an address space qualified type.
8409
8410A type with a SYCL address space qualifier is a distinct type from the
8411otherwise unattributed type. For example, `int *` and `int [[clang::sycl_global]]*`
8412designate distinct pointer types which participate in overload resolution and
8413template specialization.
8414
8415The top-level type of a variable declaration cannot have a SYCL address space
8416qualifier. For example:
8417
8418```c++
8419int [[clang::sycl_global]] gv; // error: the top-level type has an address space qualifier.
8420int [[clang::sycl_global]] *pgi; // ok; the address space qualifier is on the pointee type.
8421```
8422
8423Conversions between SYCL address space attributed types are permitted as
8424follows.
8425
8426- Types attributed with the global, local, or private address space attributes
8427 are implicitly convertible to matching types with the generic address space
8428 attribute.
8429
8430The mapping of SYCL address spaces to physical address spaces is target
8431dependent.
8432
8433For OpenCL device targets, the SYCL address space attributes are aligned with
8434the [OpenCL address space attributes](#opencl-address-spaces) such that, e.g.,
8435`int [[clang::sycl_global]]*` and `int [[clang::opencl_global]]*` specify
8436distinct types both of which map to the same underlying address space.
8437Corresponding SYCL and OpenCL address space attributed types are implicitly
8438convertible; other conversions are permitted as described above; e.g.,
8439`int [[clang::sycl_global]]*` is implicitly convertible to
8440`int [[clang::opencl_generic]]*`.
8441
8442[SYCL-2020-3.8.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_sycl_device_memory_model
8443[SYCL-2020-4.7.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:buffers
8444[SYCL-2020-4.7.6]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:accessors
8445[SYCL-2020-4.7.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_address_space_classes
8446[SYCL-2020-F.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-static-addrspace-cast
8447[SYCL-2020-F.8]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-dynamic-addrspace-cast)reST";
8448
8449static const char AttrDoc_SYCLPrivateAddressSpace[] = R"reST(:::{Note}
8450These attributes are intended for use in the implementation of SYCL run-time
8451libraries and should not be used in any other context.
8452Programmers writing code intended to conform to the SYCL specification should
8453use the address space facilities specified in the following sections of the
8454SYCL 2020 specification.
8455
8456* [4.7.2, "Buffers"][SYCL-2020-4.7.2]
8457* [4.7.6, "Accessors"][SYCL-2020-4.7.6]
8458* [4.7.7, "Address space classes"][SYCL-2020-4.7.7]
8459* [F.7, "sycl_khr_static_addrspace_cast"][SYCL-2020-F.7]
8460* [F.8, "sycl_khr_dynamic_addrspace_cast"][SYCL-2020-F.8]
8461:::
8462
8463The SYCL address space attributes listed below correspond to the five address
8464spaces described by
8465[SYCL 2020 section 3.8.2, "SYCL device memory model"][SYCL-2020-3.8.2] and
8466[SYCL 2020 section 4.7.7, "Address space classes"][SYCL-2020-4.7.7].
8467
8468::: {list-table} SYCL address space attributes
8469:header-rows: 1
8470
8471* - Address space attribute
8472 - SYCL address space
8473 - Description
8474* - `[[clang::sycl_global]]`
8475 - global
8476 - A memory region accessible by all work-items executing on a device.
8477* - `[[clang::sycl_local]]`
8478 - local
8479 - A memory region accessible by all work-items of a single work-group.
8480* - `[[clang::sycl_private]]`
8481 - private
8482 - A memory region that is private to a single work-item.
8483* - `[[clang::sycl_generic]]`
8484 - generic
8485 - A virtual memory region from which the global, local, and private memory
8486 regions may all be accessed.
8487* - `[[clang::sycl_constant]]`
8488 - constant
8489 - (*deprecated*) A memory region that holds constant data for an executing
8490 kernel.
8491:::
8492
8493The SYCL address space attributes are type attributes that may be applied to
8494non-function non-reference types to specify an address space qualified type.
8495
8496A type with a SYCL address space qualifier is a distinct type from the
8497otherwise unattributed type. For example, `int *` and `int [[clang::sycl_global]]*`
8498designate distinct pointer types which participate in overload resolution and
8499template specialization.
8500
8501The top-level type of a variable declaration cannot have a SYCL address space
8502qualifier. For example:
8503
8504```c++
8505int [[clang::sycl_global]] gv; // error: the top-level type has an address space qualifier.
8506int [[clang::sycl_global]] *pgi; // ok; the address space qualifier is on the pointee type.
8507```
8508
8509Conversions between SYCL address space attributed types are permitted as
8510follows.
8511
8512- Types attributed with the global, local, or private address space attributes
8513 are implicitly convertible to matching types with the generic address space
8514 attribute.
8515
8516The mapping of SYCL address spaces to physical address spaces is target
8517dependent.
8518
8519For OpenCL device targets, the SYCL address space attributes are aligned with
8520the [OpenCL address space attributes](#opencl-address-spaces) such that, e.g.,
8521`int [[clang::sycl_global]]*` and `int [[clang::opencl_global]]*` specify
8522distinct types both of which map to the same underlying address space.
8523Corresponding SYCL and OpenCL address space attributed types are implicitly
8524convertible; other conversions are permitted as described above; e.g.,
8525`int [[clang::sycl_global]]*` is implicitly convertible to
8526`int [[clang::opencl_generic]]*`.
8527
8528[SYCL-2020-3.8.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_sycl_device_memory_model
8529[SYCL-2020-4.7.2]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:buffers
8530[SYCL-2020-4.7.6]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:accessors
8531[SYCL-2020-4.7.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_address_space_classes
8532[SYCL-2020-F.7]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-static-addrspace-cast
8533[SYCL-2020-F.8]: https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-dynamic-addrspace-cast)reST";
8534
8535static const char AttrDoc_SYCLSpecialClass[] = R"reST(SYCL defines some special classes (accessor, sampler, and stream) which require
8536specific handling during the generation of the SPIR entry point.
8537The `__attribute__((sycl_special_class))` attribute is used in SYCL
8538headers to indicate that a class or a struct needs a specific handling when
8539it is passed from host to device.
8540Special classes will have a mandatory `__init` method and an optional
8541`__finalize` method (the `__finalize` method is used only with the
8542`stream` type). Kernel parameters types are extract from the `__init` method
8543parameters. The kernel function arguments list is derived from the
8544arguments of the `__init` method. The arguments of the `__init` method are
8545copied into the kernel function argument list and the `__init` and
8546`__finalize` methods are called at the beginning and the end of the kernel,
8547respectively.
8548The `__init` and `__finalize` methods must be defined inside the
8549special class.
8550Please note that this is an attribute that is used as an internal
8551implementation detail and not intended to be used by external users.
8552
8553The syntax of the attribute is as follows:
8554
8555```text
8556class __attribute__((sycl_special_class)) accessor {};
8557class [[clang::sycl_special_class]] accessor {};
8558```
8559
8560This is a code example that illustrates the use of the attribute:
8561
8562```c++
8563class __attribute__((sycl_special_class)) SpecialType {
8564 int F1;
8565 int F2;
8566 void __init(int f1) {
8567 F1 = f1;
8568 F2 = f1;
8569 }
8570 void __finalize() {}
8571public:
8572 SpecialType() = default;
8573 int getF2() const { return F2; }
8574};
8575
8576int main () {
8577 SpecialType T;
8578 cgh.single_task([=] {
8579 T.getF2();
8580 });
8581}
8582```
8583
8584This would trigger the following kernel entry point in the AST:
8585
8586```c++
8587void __sycl_kernel(int f1) {
8588 SpecialType T;
8589 T.__init(f1);
8590 ...
8591 T.__finalize()
8592}
8593```)reST";
8594
8595static const char AttrDoc_ScopedLockable[] = R"reST(No documentation.)reST";
8596
8597static const char AttrDoc_Section[] = R"reST(The `section` attribute allows you to specify a specific section a
8598global variable or function should be in after translation.)reST";
8599
8600static const char AttrDoc_SelectAny[] = R"reST(This attribute appertains to a global symbol, causing it to have a weak
8601definition ([linkonce](https://llvm.org/docs/LangRef.html#linkage-types)),
8602allowing the linker to select any definition.
8603
8604For more information see
8605[gcc documentation](https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html)
8606or [msvc documentation](https://docs.microsoft.com/pl-pl/cpp/cpp/selectany).)reST";
8607
8608static const char AttrDoc_Sentinel[] = R"reST(The `sentinel` attribute can be applied to variadic functions and pointers to
8609variadic functions, to diagnose each function call that does not pass a
8610sentinel value (a null pointer constant) as the last argument to the function
8611call. The attribute accepts two optional arguments: the first argument is the
8612position of the expected sentinel value, starting from the last parameter. The
8613second argument describes whether the last fixed parameter is treated as a
8614valid sentinel value when set to `1`.
8615All arguments described above default to `0` when elided.
8616The attribute is also supported with blocks and in Objective-C.
8617
8618```c
8619void foo(const char*, ...) __attribute__((sentinel));
8620void bar(int, ...) __attribute__((sentinel(1)));
8621void baz(const char*, const char*, ...) __attribute__((sentinel(0, 1)));
8622
8623void example() {
8624 foo("Example", (void*)0);
8625 foo("Another", "example", NULL);
8626 foo("Missing", "sentinel"); // Not OK
8627
8628 bar(1, 2, NULL, 3); // OK: sentinel value at the 2nd to last position
8629 bar(1, 2, 3, nullptr, 4); // OK: `nullptr` is valid in C23
8630 bar(1, 2, 3, 4, NULL); // Not OK
8631
8632 baz("Test", "with", "multiple", "args", NULL);
8633 baz("One", NULL); // OK: last fixed parameter is a valid sentinel
8634
8635 void (*ptr) (int arg, ...) __attribute__ ((__sentinel__));
8636 ptr(1, 2, 3, NULL);
8637}
8638```
8639
8640```c++
8641struct Ty {
8642 int value;
8643
8644 template<typename T>
8645 auto&& foo(T&& val, ...) __attribute__((sentinel(1))) {
8646 return std::forward<T>(val);
8647 }
8648
8649 template<class Self>
8650 auto&& bar(this Self&& self, ...) __attribute__((sentinel(1))) {
8651 return std::forward<Self>(self).value;
8652 }
8653};
8654
8655void example2() {
8656 auto sty = Ty{};
8657 sty.foo(1, nullptr, 3);
8658 sty.bar(1, nullptr, 3);
8659
8660 auto lmbd = [](int a, ...) __attribute__((sentinel)) {};
8661 lmbd(1, 2, nullptr);
8662}
8663```)reST";
8664
8665static const char AttrDoc_SetTypestate[] = R"reST(Annotate methods that transition an object into a new state with
8666`__attribute__((set_typestate(new_state)))`. The new state must be
8667unconsumed, consumed, or unknown.)reST";
8668
8669static const char AttrDoc_SizedBy[] = R"reST(The `sized_by` attribute is applied to a pointer to indicate that the pointer
8670points to memory containing at least the number of *bytes* given by the
8671attribute's argument. It is closely related to `counted_by`; the difference is
8672that `counted_by` counts the number of *elements* of the pointee type, whereas
8673`sized_by` counts the number of *bytes*. This makes `sized_by` the natural
8674choice for `void *` and other byte buffers.
8675
8676This attribute is used by {doc}`-fbounds-safety <BoundsSafety>` to propagate
8677bounds information on API surfaces without any ABI changes. This attribute is
8678also used to improve the results of the array bound sanitizer and the
8679`__builtin_dynamic_object_size` builtin.
8680
8681The argument is an expression of integer type, following the same rules as the
8682argument of `counted_by`. Unlike `counted_by`, `sized_by` cannot be
8683applied to a C99 flexible array member; it applies to pointers only. For
8684example:
8685
8686```c
8687struct object {
8688 unsigned long size;
8689 void *data __attribute__((sized_by(size)));
8690};
8691```
8692
8693A pointer annotated with `sized_by` must have a size of zero when it is null.
8694This requirement is currently only enforced when compiling with
8695{doc}`-fbounds-safety <BoundsSafety>` (see {ref}`Current status of
8696-fbounds-safety support in upstream Clang <bounds-safety-current-upstream-status>`). Use
8697`sized_by_or_null` for a pointer that may be null while carrying a nonzero
8698size.
8699
8700#### Keeping pointer and size in sync
8701
8702The `sized_by` attribute establishes a relationship between the annotated
8703pointer and its size: the pointer must point to at least `size` bytes.
8704Assigning to only one of them can break this relationship.
8705Without {doc}`-fbounds-safety <BoundsSafety>`, it is the programmer's
8706responsibility to ensure the pointer and size remain in sync. With
8707`-fbounds-safety` it is automatically enforced. For example:
8708
8709```c
8710struct buffer {
8711 uint8_t *buf __attribute__((sized_by(size)));
8712 size_t size;
8713};
8714
8715void grow(struct buffer *b, size_t new_size) {
8716 // b->buf isn't updated. The underlying memory pointed to by b->buf might be
8717 // smaller than new_size which would contradict the sized_by attribute.
8718 // Compile error with -fbounds-safety but allowed without -fbounds-safety.
8719 b->size = new_size;
8720}
8721```
8722
8723Updating both together - so that `buf` points to `size` bytes - keeps
8724the attribute true. For example:
8725
8726```c
8727void grow(struct buffer *b, size_t new_size) {
8728 // Allowed by -fbounds-safety
8729 uint8_t *new_buf = malloc(new_size);
8730 // -fbounds-safety enforces that the `new_buf` points to at least `new_size`
8731 // bytes at runtime. Without -fbounds-safety nothing enforces this.
8732 b->buf = new_buf;
8733 b->size = new_size;
8734}
8735```
8736
8737#### Incomplete and variable-length pointees
8738
8739`sized_by` is typically applied to `void *` or a pointer to a byte-sized
8740type, but it may be used with any pointee type. Two situations call for this,
8741both of which rule out counting fixed-size elements:
8742
8743First, the pointee type may be incomplete, such as an opaque type. Its element
8744size is then unavailable, so `counted_by` cannot be used, whereas `sized_by`
8745bounds the memory in bytes and imposes no completeness requirement.
8746
8747Second, the buffer may hold variable-length elements, so there is no fixed
8748element size to count, even though the total byte size is well defined. For
8749example, a buffer might pack together several structures that each end in a
8750flexible array member of differing length:
8751
8752```c
8753struct var_len {
8754 int fam_size;
8755 char data[] __attribute__((counted_by(fam_size)));
8756};
8757
8758struct buffer_view {
8759 int byte_size;
8760 struct var_len *buf __attribute__((sized_by(byte_size)));
8761};
8762```
8763
8764Here `counted_by` cannot be applied to `buf` because its pointee is a
8765variable-length structure, but `sized_by` bounds the whole region in bytes;
8766the region is traversed by advancing a byte offset rather than by indexing
8767elements.)reST";
8768
8769static const char AttrDoc_SizedByOrNull[] = R"reST(The `sized_by_or_null` attribute is applied to a pointer to indicate that, if
8770the pointer is non-null, it points to memory containing at least the number of
8771*bytes* given by the attribute's argument. If the pointer is null, the value of
8772the argument is ignored and the pointer points to zero bytes.
8773
8774The `sized_by_or_null` attribute is identical to `sized_by` except in how
8775it treats null pointers. Whereas `sized_by` requires a null pointer to have a
8776size of zero, `sized_by_or_null` allows the pointer to be null regardless of
8777the value of the size. This supports the common idiom where a pointer is either
8778null or points to memory containing at least the given number of bytes.
8779
8780Currently only {doc}`-fbounds-safety <BoundsSafety>` makes use of the
8781distinction between `sized_by_or_null` and `sized_by` (see
8782{ref}`Current status of -fbounds-safety support in upstream Clang
8783<bounds-safety-current-upstream-status>`).)reST";
8784
8785static const char AttrDoc_SpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
8786that [Speculative Load Hardening][slh]
8787should be enabled for the function body. This can also be applied to a method
8788in Objective C. This attribute will take precedence over the command line flag
8789in the case where {option}`-mno-speculative-load-hardening` is specified.
8790
8791[slh]: https://llvm.org/docs/SpeculativeLoadHardening.html
8792
8793Speculative Load Hardening is a best-effort mitigation against
8794information leak attacks that make use of control flow
8795miss-speculation - specifically miss-speculation of whether a branch
8796is taken or not. Typically vulnerabilities enabling such attacks are
8797classified as "Spectre variant #1". Notably, this does not attempt to
8798mitigate against miss-speculation of branch target, classified as
8799"Spectre variant #2" vulnerabilities.
8800
8801When inlining, the attribute is sticky. Inlining a function that
8802carries this attribute will cause the caller to gain the
8803attribute. This is intended to provide a maximally conservative model
8804where the code in a function annotated with this attribute will always
8805(even after inlining) end up hardened.)reST";
8806
8807static const char AttrDoc_StackProtectorIgnore[] = R"reST(The `stack_protector_ignore` attribute skips analysis of the given local
8808variable when determining if a function should use a stack protector.
8809
8810The `-fstack-protector` option uses a heuristic to only add stack protectors
8811to functions which contain variables or buffers over some size threshold. This
8812attribute overrides that heuristic for the attached variable, opting
8813them out. If this results in no variables or buffers remaining over the stack
8814protector threshold, then the function will no longer use a stack protector.)reST";
8815
8816static const char AttrDoc_StandaloneDebug[] = R"reST(The `standalone_debug` attribute causes debug info to be emitted for a record
8817type regardless of the debug info optimizations that are enabled with
8818-fno-standalone-debug. This attribute only has an effect when debug info
8819optimizations are enabled (e.g. with -fno-standalone-debug), and is C++-only.)reST";
8820
8821static const char AttrDoc_StdCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
8822function to clear parameters off of the stack on return. This convention does
8823not support variadic calls or unprototyped functions in C, and has no effect on
8824x86_64 targets. This calling convention is used widely by the Windows API and
8825COM applications. See the documentation for [`__stdcall`][__stdcall] on MSDN.
8826
8827[__stdcall]: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx)reST";
8828
8829static const char AttrDoc_StrictFP[] = R"reST()reST";
8830
8831static const char AttrDoc_StrictGuardStackCheck[] = R"reST(Clang supports the Microsoft style `__declspec((strict_gs_check))` attribute
8832which upgrades the stack protector check from `-fstack-protector` to
8833`-fstack-protector-strong`.
8834
8835For example, it upgrades the stack protector for the function `foo` to
8836`-fstack-protector-strong` but function `bar` will still be built with the
8837stack protector with the `-fstack-protector` option.
8838
8839```c
8840__declspec((strict_gs_check))
8841int foo(int x); // stack protection will be upgraded for foo.
8842
8843int bar(int y); // bar can be built with the standard stack protector checks.
8844```)reST";
8845
8846static const char AttrDoc_Suppress[] = R"reST(The `suppress` attribute suppresses unwanted warnings coming from static
8847analysis tools such as the Clang Static Analyzer. The tool will not report
8848any issues in source code annotated with the attribute.
8849
8850The attribute cannot be used to suppress traditional Clang warnings, because
8851many such warnings are emitted before the attribute is fully parsed.
8852Consider using `#pragma clang diagnostic` to control such diagnostics,
8853as described in
8854{ref}`Controlling Diagnostics via Pragmas <pragma-gcc-diagnostic>`.
8855
8856The `suppress` attribute can be placed on an individual statement in order to
8857suppress warnings about undesirable behavior occurring at that statement:
8858
8859```c++
8860int foo() {
8861 int *x = nullptr;
8862 ...
8863 [[clang::suppress]]
8864 return *x; // null pointer dereference warning suppressed here
8865}
8866```
8867
8868Putting the attribute on a compound statement suppresses all warnings in scope:
8869
8870```c++
8871int foo() {
8872 [[clang::suppress]] {
8873 int *x = nullptr;
8874 ...
8875 return *x; // warnings suppressed in the entire scope
8876 }
8877}
8878```
8879
8880The attribute can also be placed on entire declarations of functions, classes,
8881variables, member variables, and so on, to suppress warnings related
8882to the declarations themselves. When used this way, the attribute additionally
8883suppresses all warnings in the lexical scope of the declaration:
8884
8885```c++
8886class [[clang::suppress]] C {
8887 int foo() {
8888 int *x = nullptr;
8889 ...
8890 return *x; // warnings suppressed in the entire class scope
8891 }
8892
8893 int bar();
8894};
8895
8896int C::bar() {
8897 int *x = nullptr;
8898 ...
8899 return *x; // warning NOT suppressed! - not lexically nested in 'class C{}'
8900}
8901```
8902
8903Some static analysis warnings are accompanied by one or more notes, and the
8904line of code against which the warning is emitted isn't necessarily the best
8905for suppression purposes. In such cases the tools are allowed to implement
8906additional ways to suppress specific warnings based on the attribute attached
8907to a note location.
8908
8909For example, the Clang Static Analyzer suppresses memory leak warnings when
8910the suppression attribute is placed at the allocation site (highlited by
8911a "note: memory is allocated"), which may be different from the line of code
8912at which the program "loses track" of the pointer (where the warning
8913is ultimately emitted):
8914
8915```c
8916int bar1(bool coin_flip) {
8917 __attribute__((suppress))
8918 int *result = (int *)malloc(sizeof(int));
8919 if (coin_flip)
8920 return 1; // warning about this leak path is suppressed
8921
8922 return *result; // warning about this leak path is also suppressed
8923}
8924
8925int bar2(bool coin_flip) {
8926 int *result = (int *)malloc(sizeof(int));
8927 if (coin_flip)
8928 return 1; // leak warning on this path NOT suppressed
8929
8930 __attribute__((suppress))
8931 return *result; // leak warning is suppressed only on this path
8932}
8933```
8934
8935When written as `[[gsl::suppress]]`, this attribute suppresses specific
8936clang-tidy diagnostics for rules of the [C++ Core Guidelines][c++ core guidelines] in a portable
8937way. The attribute can be attached to declarations, statements, and at
8938namespace scope.
8939
8940```c++
8941[[gsl::suppress("Rh-public")]]
8942void f_() {
8943 int *p;
8944 [[gsl::suppress("type")]] {
8945 p = reinterpret_cast<int*>(7);
8946 }
8947}
8948namespace N {
8949 [[clang::suppress("type", "bounds")]];
8950 ...
8951}
8952```
8953
8954[c++ core guidelines]: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement)reST";
8955
8956static const char AttrDoc_SwiftAsync[] = R"reST(The `swift_async` attribute specifies if and how a particular function or
8957Objective-C method is imported into a swift async method. For instance:
8958
8959```objc
8960@interface MyClass : NSObject
8961-(void)notActuallyAsync:(int)p1 withCompletionHandler:(void (^)())handler
8962 __attribute__((swift_async(none)));
8963
8964-(void)actuallyAsync:(int)p1 callThisAsync:(void (^)())fun
8965 __attribute__((swift_async(swift_private, 1)));
8966@end
8967```
8968
8969Here, `notActuallyAsync:withCompletionHandler` would have been imported as
8970`async` (because it's last parameter's selector piece is
8971`withCompletionHandler`) if not for the `swift_async(none)` attribute.
8972Conversely, `actuallyAsync:callThisAsync` wouldn't have been imported as
8973`async` if not for the `swift_async` attribute because it doesn't match the
8974naming convention.
8975
8976When using `swift_async` to enable importing, the first argument to the
8977attribute is either `swift_private` or `not_swift_private` to indicate
8978whether the function/method is private to the current framework, and the second
8979argument is the index of the completion handler parameter.)reST";
8980
8981static const char AttrDoc_SwiftAsyncCall[] = R"reST(The `swiftasynccall` attribute indicates that a function is
8982compatible with the low-level conventions of Swift async functions,
8983provided it declares the right formal arguments.
8984
8985In most respects, this is similar to the `swiftcall` attribute, except for
8986the following:
8987
8988- A parameter may be marked `swift_async_context`, `swift_context`
8989 or `swift_indirect_result` (with the same restrictions on parameter
8990 ordering as `swiftcall`) but the parameter attribute
8991 `swift_error_result` is not permitted.
8992- A `swiftasynccall` function must have return type `void`.
8993- Within a `swiftasynccall` function, a call to a `swiftasynccall`
8994 function that is the immediate operand of a `return` statement is
8995 guaranteed to be performed as a tail call. This syntax is allowed even
8996 in C as an extension (a call to a void-returning function cannot be a
8997 return operand in standard C). If something in the calling function would
8998 semantically be performed after a guaranteed tail call, such as the
8999 non-trivial destruction of a local variable or temporary,
9000 then the program is ill-formed.
9001
9002Query for this attribute with `__has_attribute(swiftasynccall)`. Query if
9003the target supports the calling convention with
9004`__has_extension(swiftasynccc)`.
9005
9006Since this attribute follows the Swift async calling convention, it is
9007considered ABI-unstable except on targets where the Swift project
9008has declared ABI stability. Users are responsible for ensuring that
9009calls and definitions of functions with this attribute are compiled
9010with compatible compilers. Note that different operating systems
9011on the same architecture may use different ABIs and therefore may
9012have different standards for ABI stability.)reST";
9013
9014static const char AttrDoc_SwiftAsyncContext[] = R"reST(The `swift_async_context` attribute marks a parameter of a `swiftasynccall`
9015function as having the special asynchronous context-parameter ABI treatment.
9016
9017If the function is not `swiftasynccall`, this attribute only generates
9018extended frame information.
9019
9020A context parameter must have pointer or reference type.)reST";
9021
9022static const char AttrDoc_SwiftAsyncError[] = R"reST(The `swift_async_error` attribute specifies how an error state will be
9023represented in a swift async method. It's a bit analogous to the `swift_error`
9024attribute for the generated async method. The `swift_async_error` attribute
9025can indicate a variety of different ways of representing an error.
9026
9027- `__attribute__((swift_async_error(zero_argument, N)))`, specifies that the
9028 async method is considered to have failed if the Nth argument to the
9029 completion handler is zero.
9030- `__attribute__((swift_async_error(nonzero_argument, N)))`, specifies that
9031 the async method is considered to have failed if the Nth argument to the
9032 completion handler is non-zero.
9033- `__attribute__((swift_async_error(nonnull_error)))`, specifies that the
9034 async method is considered to have failed if the `NSError *` argument to the
9035 completion handler is non-null.
9036- `__attribute__((swift_async_error(none)))`, specifies that the async method
9037 cannot fail.
9038
9039For instance:
9040
9041```objc
9042@interface MyClass : NSObject
9043-(void)asyncMethod:(void (^)(char, int, float))handler
9044 __attribute__((swift_async(swift_private, 1)))
9045 __attribute__((swift_async_error(zero_argument, 2)));
9046@end
9047```
9048
9049Here, the `swift_async` attribute specifies that `handler` is the completion
9050handler for this method, and the `swift_async_error` attribute specifies that
9051the `int` parameter is the one that represents the error.)reST";
9052
9053static const char AttrDoc_SwiftAsyncName[] = R"reST(The `swift_async_name` attribute provides the name of the `async` overload for
9054the given declaration in Swift. If this attribute is absent, the name is
9055transformed according to the algorithm built into the Swift compiler.
9056
9057The argument is a string literal that contains the Swift name of the function or
9058method. The name may be a compound Swift name. The function or method with such
9059an attribute must have more than zero parameters, as its last parameter is
9060assumed to be a callback that's eliminated in the Swift `async` name.
9061
9062```objc
9063@interface URL
9064+ (void) loadContentsFrom:(URL *)url callback:(void (^)(NSData *))data __attribute__((__swift_async_name__("URL.loadContentsFrom(_:)")))
9065@end
9066```)reST";
9067
9068static const char AttrDoc_SwiftAttr[] = R"reST(The `swift_attr` provides a Swift-specific annotation for the declaration
9069or type to which the attribute appertains to. It can be used on any declaration
9070or type in Clang. This kind of annotation is ignored by Clang as it doesn't have any
9071semantic meaning in languages supported by Clang. The Swift compiler can
9072interpret these annotations according to its own rules when importing C or
9073Objective-C declarations.)reST";
9074
9075static const char AttrDoc_SwiftBridge[] = R"reST(The `swift_bridge` attribute indicates that the declaration to which the
9076attribute appertains is bridged to the named Swift type.
9077
9078```objc
9079__attribute__((__objc_root__))
9080@interface Base
9081- (instancetype)init;
9082@end
9083
9084__attribute__((__swift_bridge__("BridgedI")))
9085@interface I : Base
9086@end
9087```
9088
9089In this example, the Objective-C interface `I` will be made available to Swift
9090with the name `BridgedI`. It would be possible for the compiler to refer to
9091`I` still in order to bridge the type back to Objective-C.)reST";
9092
9093static const char AttrDoc_SwiftBridgedTypedef[] = R"reST(The `swift_bridged_typedef` attribute indicates that when the typedef to which
9094the attribute appertains is imported into Swift, it should refer to the bridged
9095Swift type (e.g. Swift's `String`) rather than the Objective-C type as written
9096(e.g. `NSString`).
9097
9098```objc
9099@interface NSString;
9100typedef NSString *AliasedString __attribute__((__swift_bridged_typedef__));
9101
9102extern void acceptsAliasedString(AliasedString _Nonnull parameter);
9103```
9104
9105In this case, the function `acceptsAliasedString` will be imported into Swift
9106as a function which accepts a `String` type parameter.)reST";
9107
9108static const char AttrDoc_SwiftCall[] = R"reST(The `swiftcall` attribute indicates that a function should be called
9109using the Swift calling convention for a function or function pointer.
9110
9111The lowering for the Swift calling convention, as described by the Swift
9112ABI documentation, occurs in multiple phases. The first, "high-level"
9113phase breaks down the formal parameters and results into innately direct
9114and indirect components, adds implicit parameters for the generic
9115signature, and assigns the context and error ABI treatments to parameters
9116where applicable. The second phase breaks down the direct parameters
9117and results from the first phase and assigns them to registers or the
9118stack. The `swiftcall` convention only handles this second phase of
9119lowering; the C function type must accurately reflect the results
9120of the first phase, as follows:
9121
9122- Results classified as indirect by high-level lowering should be
9123 represented as parameters with the `swift_indirect_result` attribute.
9124
9125- Results classified as direct by high-level lowering should be represented
9126 as follows:
9127
9128 - First, remove any empty direct results.
9129 - If there are no direct results, the C result type should be `void`.
9130 - If there is one direct result, the C result type should be a type with
9131 the exact layout of that result type.
9132 - If there are a multiple direct results, the C result type should be
9133 a struct type with the exact layout of a tuple of those results.
9134
9135- Parameters classified as indirect by high-level lowering should be
9136 represented as parameters of pointer type.
9137
9138- Parameters classified as direct by high-level lowering should be
9139 omitted if they are empty types; otherwise, they should be represented
9140 as a parameter type with a layout exactly matching the layout of the
9141 Swift parameter type.
9142
9143- The context parameter, if present, should be represented as a trailing
9144 parameter with the `swift_context` attribute.
9145
9146- The error result parameter, if present, should be represented as a
9147 trailing parameter (always following a context parameter) with the
9148 `swift_error_result` attribute.
9149
9150`swiftcall` does not support variadic arguments or unprototyped functions.
9151
9152The parameter ABI treatment attributes are aspects of the function type.
9153A function type which applies an ABI treatment attribute to a
9154parameter is a different type from an otherwise-identical function type
9155that does not. A single parameter may not have multiple ABI treatment
9156attributes.
9157
9158Support for this feature is target-dependent, although it should be
9159supported on every target that Swift supports. Query for this attribute
9160with `__has_attribute(swiftcall)`. Query if the target supports the
9161calling convention with `__has_extension(swiftcc)`. This implies
9162support for the `swift_context`, `swift_error_result`, and
9163`swift_indirect_result` attributes.
9164
9165Since this attribute follows the Swift calling convention, it is
9166considered ABI-unstable except on targets where the Swift project
9167has declared ABI stability. Users are responsible for ensuring that
9168calls and definitions of functions with this attribute are compiled
9169with compatible compilers. Note that different operating systems
9170on the same architecture may use different ABIs and therefore may
9171have different standards for ABI stability.)reST";
9172
9173static const char AttrDoc_SwiftContext[] = R"reST(The `swift_context` attribute marks a parameter of a `swiftcall`
9174or `swiftasynccall` function as having the special context-parameter
9175ABI treatment.
9176
9177This treatment generally passes the context value in a special register
9178which is normally callee-preserved.
9179
9180A `swift_context` parameter must either be the last parameter or must be
9181followed by a `swift_error_result` parameter (which itself must always be
9182the last parameter).
9183
9184A context parameter must have pointer or reference type.)reST";
9185
9186static const char AttrDoc_SwiftError[] = R"reST(The `swift_error` attribute controls whether a particular function (or
9187Objective-C method) is imported into Swift as a throwing function, and if so,
9188which dynamic convention it uses.
9189
9190All of these conventions except `none` require the function to have an error
9191parameter. Currently, the error parameter is always the last parameter of type
9192`NSError**` or `CFErrorRef*`. Swift will remove the error parameter from
9193the imported API. When calling the API, Swift will always pass a valid address
9194initialized to a null pointer.
9195
9196- `swift_error(none)` means that the function should not be imported as
9197 throwing. The error parameter and result type will be imported normally.
9198- `swift_error(null_result)` means that calls to the function should be
9199 considered to have thrown if they return a null value. The return type must be
9200 a pointer type, and it will be imported into Swift with a non-optional type.
9201 This is the default error convention for Objective-C methods that return
9202 pointers.
9203- `swift_error(zero_result)` means that calls to the function should be
9204 considered to have thrown if they return a zero result. The return type must be
9205 an integral type. If the return type would have been imported as `Bool`, it
9206 is instead imported as `Void`. This is the default error convention for
9207 Objective-C methods that return a type that would be imported as `Bool`.
9208- `swift_error(nonzero_result)` means that calls to the function should be
9209 considered to have thrown if they return a non-zero result. The return type must
9210 be an integral type. If the return type would have been imported as `Bool`,
9211 it is instead imported as `Void`.
9212- `swift_error(nonnull_error)` means that calls to the function should be
9213 considered to have thrown if they leave a non-null error in the error parameter.
9214 The return type is left unmodified.)reST";
9215
9216static const char AttrDoc_SwiftErrorResult[] = R"reST(The `swift_error_result` attribute marks a parameter of a `swiftcall`
9217function as having the special error-result ABI treatment.
9218
9219This treatment generally passes the underlying error value in and out of
9220the function through a special register which is normally callee-preserved.
9221This is modeled in C by pretending that the register is addressable memory:
9222
9223- The caller appears to pass the address of a variable of pointer type.
9224 The current value of this variable is copied into the register before
9225 the call; if the call returns normally, the value is copied back into the
9226 variable.
9227- The callee appears to receive the address of a variable. This address
9228 is actually a hidden location in its own stack, initialized with the
9229 value of the register upon entry. When the function returns normally,
9230 the value in that hidden location is written back to the register.
9231
9232A `swift_error_result` parameter must be the last parameter, and it must be
9233preceded by a `swift_context` parameter.
9234
9235A `swift_error_result` parameter must have type `T**` or `T*&` for some
9236type T. Note that no qualifiers are permitted on the intermediate level.
9237
9238It is undefined behavior if the caller does not pass a pointer or
9239reference to a valid object.
9240
9241The standard convention is that the error value itself (that is, the
9242value stored in the apparent argument) will be null upon function entry,
9243but this is not enforced by the ABI.)reST";
9244
9245static const char AttrDoc_SwiftImportAsNonGeneric[] = R"reST()reST";
9246
9247static const char AttrDoc_SwiftImportPropertyAsAccessors[] = R"reST()reST";
9248
9249static const char AttrDoc_SwiftIndirectResult[] = R"reST(The `swift_indirect_result` attribute marks a parameter of a `swiftcall`
9250or `swiftasynccall` function as having the special indirect-result ABI
9251treatment.
9252
9253This treatment gives the parameter the target's normal indirect-result
9254ABI treatment, which may involve passing it differently from an ordinary
9255parameter. However, only the first indirect result will receive this
9256treatment. Furthermore, low-level lowering may decide that a direct result
9257must be returned indirectly; if so, this will take priority over the
9258`swift_indirect_result` parameters.
9259
9260A `swift_indirect_result` parameter must either be the first parameter or
9261follow another `swift_indirect_result` parameter.
9262
9263A `swift_indirect_result` parameter must have type `T*` or `T&` for
9264some object type `T`. If `T` is a complete type at the point of
9265definition of a function, it is undefined behavior if the argument
9266value does not point to storage of adequate size and alignment for a
9267value of type `T`.
9268
9269Making indirect results explicit in the signature allows C functions to
9270directly construct objects into them without relying on language
9271optimizations like C++'s named return value optimization (NRVO).)reST";
9272
9273static const char AttrDoc_SwiftName[] = R"reST(The `swift_name` attribute provides the name of the declaration in Swift. If
9274this attribute is absent, the name is transformed according to the algorithm
9275built into the Swift compiler.
9276
9277The argument is a string literal that contains the Swift name of the function,
9278variable, or type. When renaming a function, the name may be a compound Swift
9279name. For a type, enum constant, property, or variable declaration, the name
9280must be a simple or qualified identifier.
9281
9282```objc
9283@interface URL
9284- (void) initWithString:(NSString *)s __attribute__((__swift_name__("URL.init(_:)")))
9285@end
9286
9287void __attribute__((__swift_name__("squareRoot()"))) sqrt(double v) {
9288}
9289```)reST";
9290
9291static const char AttrDoc_SwiftNewType[] = R"reST(The `swift_newtype` attribute indicates that the typedef to which the
9292attribute appertains is imported as a new Swift type of the typedef's name.
9293Previously, the attribute was spelt `swift_wrapper`. While the behaviour of
9294the attribute is identical with either spelling, `swift_wrapper` is
9295deprecated, only exists for compatibility purposes, and should not be used in
9296new code.
9297
9298- `swift_newtype(struct)` means that a Swift struct will be created for this
9299 typedef.
9300
9301- `swift_newtype(enum)` means that a Swift enum will be created for this
9302 typedef.
9303
9304 ```c
9305 // Import UIFontTextStyle as an enum type, with enumerated values being
9306 // constants.
9307 typedef NSString * UIFontTextStyle __attribute__((__swift_newtype__(enum)));
9308
9309 // Import UIFontDescriptorFeatureKey as a structure type, with enumerated
9310 // values being members of the type structure.
9311 typedef NSString * UIFontDescriptorFeatureKey __attribute__((__swift_newtype__(struct)));
9312 ```)reST";
9313
9314static const char AttrDoc_SwiftNullability[] = R"reST()reST";
9315
9316static const char AttrDoc_SwiftObjCMembers[] = R"reST(This attribute indicates that Swift subclasses and members of Swift extensions
9317of this class will be implicitly marked with the `@objcMembers` Swift
9318attribute, exposing them back to Objective-C.)reST";
9319
9320static const char AttrDoc_SwiftPrivate[] = R"reST(Declarations marked with the `swift_private` attribute are hidden from the
9321framework client but are still made available for use within the framework or
9322Swift SDK overlay.
9323
9324The purpose of this attribute is to permit a more idomatic implementation of
9325declarations in Swift while hiding the non-idiomatic one.)reST";
9326
9327static const char AttrDoc_SwiftType[] = R"reST()reST";
9328
9329static const char AttrDoc_SwiftVersionedAddition[] = R"reST()reST";
9330
9331static const char AttrDoc_SwiftVersionedRemoval[] = R"reST()reST";
9332
9333static const char AttrDoc_SwiftVersionedSlice[] = R"reST()reST";
9334
9335static const char AttrDoc_SysVABI[] = R"reST(On Windows x86_64 targets, this attribute changes the calling convention of a
9336function to match the default convention used on Sys V targets such as Linux,
9337Mac, and BSD. This attribute has no effect on other targets.)reST";
9338
9339static const char AttrDoc_TLSModel[] = R"reST(The `tls_model` attribute allows you to specify which thread-local storage
9340model to use. It accepts the following strings:
9341
9342- global-dynamic
9343- local-dynamic
9344- initial-exec
9345- local-exec
9346
9347TLS models are mutually exclusive.)reST";
9348
9349static const char AttrDoc_Target[] = R"reST(Clang supports the GNU style `__attribute__((target("OPTIONS")))` attribute.
9350This attribute may be attached to a function definition and instructs
9351the backend to use different code generation options than were passed on the
9352command line.
9353
9354The current set of options correspond to the existing "subtarget features" for
9355the target with or without a "-mno-" in front corresponding to the absence
9356of the feature, as well as `arch="CPU"` which will change the default "CPU"
9357for the function.
9358
9359For X86, the attribute also allows `tune="CPU"` to optimize the generated
9360code for the given CPU without changing the available instructions.
9361
9362For AArch64, `arch="Arch"` will set the architecture, similar to the -march
9363command line options. `cpu="CPU"` can be used to select a specific cpu,
9364as per the `-mcpu` option, similarly for `tune=`. The attribute also allows the
9365`branch-protection=<args>` option, where the permissible arguments and their
9366effect on code generation are the same as for the command-line option
9367`-mbranch-protection`.
9368
9369Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
9370"avx", "xop" and largely correspond to the machine specific options handled by
9371the front end.
9372
9373Note that this attribute does not apply transitively to nested functions such
9374as blocks or C++ lambdas.
9375
9376Additionally, this attribute supports function multiversioning for ELF based
9377x86/x86-64 targets, which can be used to create multiple implementations of the
9378same function that will be resolved at runtime based on the priority of their
9379`target` attribute strings. A function is considered a multiversioned function
9380if either two declarations of the function have different `target` attribute
9381strings, or if it has a `target` attribute string of `default`. For
9382example:
9383
9384```c++
9385__attribute__((target("arch=atom")))
9386void foo() {} // will be called on 'atom' processors.
9387__attribute__((target("default")))
9388void foo() {} // will be called on any other processors.
9389```
9390
9391All multiversioned functions must contain a `default` (fallback)
9392implementation, otherwise usages of the function are considered invalid.
9393Additionally, a function may not become multiversioned after its first use.)reST";
9394
9395static const char AttrDoc_TargetClones[] = R"reST(Clang supports the `target_clones("OPTIONS")` attribute. This attribute may be
9396attached to a function declaration and causes function multiversioning, where
9397multiple versions of the function will be emitted with different code
9398generation options. Additionally, these versions will be resolved at runtime
9399based on the priority of their attribute options. All `target_clone` functions
9400are considered multiversioned functions.
9401
9402For AArch64 target:
9403The attribute contains comma-separated strings of target features joined by "+"
9404sign. For example:
9405
9406```c++
9407__attribute__((target_clones("sha2+memtag", "fcma+sve2-pmull128")))
9408void foo() {}
9409```
9410
9411For every multiversioned function a `default` (fallback) implementation
9412always generated if not specified directly.
9413
9414For x86/x86-64 targets:
9415All multiversioned functions must contain a `default` (fallback)
9416implementation, otherwise usages of the function are considered invalid.
9417Additionally, a function may not become multiversioned after its first use.
9418
9419The options to `target_clones` can either be a target-specific architecture
9420(specified as `arch=CPU`), or one of a list of subtarget features.
9421
9422Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
9423"avx", "xop" and largely correspond to the machine specific options handled by
9424the front end.
9425
9426The versions can either be listed as a comma-separated sequence of string
9427literals or as a single string literal containing a comma-separated list of
9428versions. For compatibility with GCC, the two formats can be mixed. For
9429example, the following will emit 4 versions of the function:
9430
9431```c++
9432__attribute__((target_clones("arch=atom,avx2","arch=ivybridge","default")))
9433void foo() {}
9434```
9435
9436For targets that support the GNU indirect function (IFUNC) feature, dispatch
9437is performed by emitting an indirect function that is resolved to the appropriate
9438target clone at load time. The indirect function is given the name the
9439multiversioned function would have if it had been declared without the attribute.
9440For backward compatibility with earlier Clang releases, a function alias with an
9441`.ifunc` suffix is also emitted. The `.ifunc` suffixed symbol is a deprecated
9442feature and support for it may be removed in the future.
9443
9444For PowerPC targets, `target_clones` is supported on AIX only. The attribute
9445contains comma-separated strings of one of:
9446(a) `default`, (b) `cpu=CPU`, (c) `FEATURE` or `no-FEATURE`.
9447The minimum CPU supported is `pwr7` (long spelling such as `power7` is accepted).
9448The list of target features is a subset of what's allowed on `target`, limited
9449to what is detectable at runtime using `__builtin_cpu_supports`. IFUNC is supported
9450on AIX in Clang, so dispatch is implemented similar to other targets using IFUNC.
9451An FMV function that is only declared in a translation unit is treated as a
9452non-FMV. The resolver and the function clones are given internal linkage.)reST";
9453
9454static const char AttrDoc_TargetVersion[] = R"reST(For AArch64 target clang supports function multiversioning by
9455`__attribute__((target_version("OPTIONS")))` attribute. When applied to a
9456function it instructs compiler to emit multiple function versions based on
9457`target_version` attribute strings, which resolved at runtime depend on their
9458priority and target features availability. One of the versions is always
9459(implicitly or explicitly) the `default` (fallback). Attribute strings can
9460contain dependent features names joined by the "+" sign.
9461
9462For targets that support the GNU indirect function (IFUNC) feature, dispatch
9463is performed by emitting an indirect function that is resolved to the appropriate
9464target clone at load time. The indirect function is given the name the
9465multiversioned function would have if it had been declared without the attribute.
9466For backward compatibility with earlier Clang releases, a function alias with an
9467`.ifunc` suffix is also emitted. The `.ifunc` suffixed symbol is a deprecated
9468feature and support for it may be removed in the future.)reST";
9469
9470static const char AttrDoc_TestTypestate[] = R"reST(Use `__attribute__((test_typestate(tested_state)))` to indicate that a method
9471returns true if the object is in the specified state..)reST";
9472
9473static const char AttrDoc_ThisCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
9474function to use ECX for the first parameter (typically the implicit `this`
9475parameter of C++ methods) and clear parameters off of the stack on return. This
9476convention does not support variadic calls or unprototyped functions in C, and
9477has no effect on x86_64 targets. See the documentation for [`__thiscall`][__thiscall] on
9478MSDN.
9479
9480[__thiscall]: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx)reST";
9481
9482static const char AttrDoc_Thread[] = R"reST(The `__declspec(thread)` attribute declares a variable with thread local
9483storage. It is available under the `-fms-extensions` flag for MSVC
9484compatibility. See the documentation for [`__declspec(thread)`][__declspec(thread)] on MSDN.
9485
9486In Clang, `__declspec(thread)` is generally equivalent in functionality to the
9487GNU `__thread` keyword. The variable must not have a destructor and must have
9488a constant initializer, if any. The attribute only applies to variables
9489declared with static storage duration, such as globals, class static data
9490members, and static locals.
9491
9492[__declspec(thread)]: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx)reST";
9493
9494static const char AttrDoc_TransparentUnion[] = R"reST(This attribute can be applied to a union to change the behavior of calls to
9495functions that have an argument with a transparent union type. The compiler
9496behavior is changed in the following manner:
9497
9498- A value whose type is any member of the transparent union can be passed as an
9499 argument without the need to cast that value.
9500- The argument is passed to the function using the calling convention of the
9501 first member of the transparent union. Consequently, all the members of the
9502 transparent union should have the same calling convention as its first member.
9503
9504Transparent unions are not supported in C++.)reST";
9505
9506static const char AttrDoc_TrivialABI[] = R"reST(The `trivial_abi` attribute can be applied to a C++ class, struct, or union.
9507It instructs the compiler to pass and return the type using the C ABI for the
9508underlying type when the type would otherwise be considered non-trivial for the
9509purpose of calls.
9510A class annotated with `trivial_abi` can have non-trivial destructors or
9511copy/move constructors without automatically becoming non-trivial for the
9512purposes of calls. For example:
9513
9514```c++
9515// A is trivial for the purposes of calls because `trivial_abi` makes the
9516// user-provided special functions trivial.
9517struct __attribute__((trivial_abi)) A {
9518 ~A();
9519 A(const A &);
9520 A(A &&);
9521 int x;
9522};
9523
9524// B's destructor and copy/move constructor are considered trivial for the
9525// purpose of calls because A is trivial.
9526struct B {
9527 A a;
9528};
9529```
9530
9531If a type is trivial for the purposes of calls, has a non-trivial destructor,
9532and is passed as an argument by value, the convention is that the callee will
9533destroy the object before returning. The lifetime of the copy of the parameter
9534in the caller ends without a destructor call when the call begins.
9535
9536If a type is trivial for the purpose of calls, it is assumed to be trivially
9537relocatable for the purpose of `__is_trivially_relocatable` and
9538`__builtin_is_cpp_trivially_relocatable`.
9539When a type marked with `[[trivial_abi]]` is used as a function argument,
9540the compiler may omit the call to the copy constructor.
9541Thus, side effects of the copy constructor are potentially not performed.
9542For example, objects that contain pointers to themselves or otherwise depend
9543on their address (or the address or their subobjects) should not be declared
9544`[[trivial_abi]]`.
9545
9546Attribute `trivial_abi` has no effect in the following cases:
9547
9548- The class directly declares a virtual base or virtual methods.
9549
9550- Copy constructors and move constructors of the class are all deleted.
9551
9552- The class has a base class that is non-trivial for the purposes of calls.
9553
9554- The class has a non-static data member whose type is non-trivial for the
9555 purposes of calls, which includes:
9556
9557 - classes that are non-trivial for the purposes of calls
9558 - `__weak`-qualified types in Objective-C++
9559 - arrays of any of the above)reST";
9560
9561static const char AttrDoc_TryAcquireCapability[] = R"reST(Marks a function that attempts to acquire a capability. This function may fail to
9562actually acquire the capability; they accept a Boolean value determining
9563whether acquiring the capability means success (true), or failing to acquire
9564the capability means success (false).)reST";
9565
9566static const char AttrDoc_TypeNonNull[] = R"reST(The `_Nonnull` nullability qualifier indicates that null is not a meaningful
9567value for a value of the `_Nonnull` pointer type. For example, given a
9568declaration such as:
9569
9570```c
9571int fetch(int * _Nonnull ptr);
9572```
9573
9574a caller of `fetch` should not provide a null value, and the compiler will
9575produce a warning if it sees a literal null value passed to `fetch`. Note
9576that, unlike the declaration attribute `nonnull`, the presence of
9577`_Nonnull` does not imply that passing null is undefined behavior: `fetch`
9578is free to consider null undefined behavior or (perhaps for
9579backward-compatibility reasons) defensively handle null.)reST";
9580
9581static const char AttrDoc_TypeNullUnspecified[] = R"reST(The `_Null_unspecified` nullability qualifier indicates that neither the
9582`_Nonnull` nor `_Nullable` qualifiers make sense for a particular pointer
9583type. It is used primarily to indicate that the role of null with specific
9584pointers in a nullability-annotated header is unclear, e.g., due to
9585overly-complex implementations or historical factors with a long-lived API.)reST";
9586
9587static const char AttrDoc_TypeNullable[] = R"reST(The `_Nullable` nullability qualifier indicates that a value of the
9588`_Nullable` pointer type can be null. For example, given:
9589
9590```c
9591int fetch_or_zero(int * _Nullable ptr);
9592```
9593
9594a caller of `fetch_or_zero` can provide null.
9595
9596The `_Nullable` attribute on classes indicates that the given class can
9597represent null values, and so the `_Nullable`, `_Nonnull` etc qualifiers
9598make sense for this type. For example:
9599
9600```c
9601class _Nullable ArenaPointer { ... };
9602
9603ArenaPointer _Nonnull x = ...;
9604ArenaPointer _Nullable y = nullptr;
9605```)reST";
9606
9607static const char AttrDoc_TypeNullableResult[] = R"reST(The `_Nullable_result` nullability qualifier means that a value of the
9608`_Nullable_result` pointer can be `nil`, just like `_Nullable`. Where this
9609attribute differs from `_Nullable` is when it's used on a parameter to a
9610completion handler in a Swift async method. For instance, here:
9611
9612```objc
9613-(void)fetchSomeDataWithID:(int)identifier
9614 completionHandler:(void (^)(Data *_Nullable_result result, NSError *error))completionHandler;
9615```
9616
9617This method asynchronously calls `completionHandler` when the data is
9618available, or calls it with an error. `_Nullable_result` indicates to the
9619Swift importer that this is the uncommon case where `result` can get `nil`
9620even if no error has occurred, and will therefore import it as a Swift optional
9621type. Otherwise, if `result` was annotated with `_Nullable`, the Swift
9622importer will assume that `result` will always be non-nil unless an error
9623occurred.)reST";
9624
9625static const char AttrDoc_TypeTagForDatatype[] = R"reST(When declaring a variable, use
9626`__attribute__((type_tag_for_datatype(kind, type)))` to create a type tag that
9627is tied to the `type` argument given to the attribute.
9628
9629In the attribute prototype above:
9630: - `kind` is an identifier that should be used when annotating all applicable
9631 type tags.
9632 - `type` indicates the name of the type.
9633
9634Clang supports annotating type tags of two forms.
9635
9636- **Type tag that is a reference to a declared identifier.**
9637 Use `__attribute__((type_tag_for_datatype(kind, type)))` when declaring that
9638 identifier:
9639
9640 ```c++
9641 typedef int MPI_Datatype;
9642 extern struct mpi_datatype mpi_datatype_int
9643 __attribute__(( type_tag_for_datatype(mpi,int) ));
9644 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
9645 // &mpi_datatype_int is a type tag. It is tied to type "int".
9646 ```
9647
9648- **Type tag that is an integral literal.**
9649 Declare a `static const` variable with an initializer value and attach
9650 `__attribute__((type_tag_for_datatype(kind, type)))` on that declaration:
9651
9652 ```c++
9653 typedef int MPI_Datatype;
9654 static const MPI_Datatype mpi_datatype_int
9655 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42;
9656 #define MPI_INT ((MPI_Datatype) 42)
9657 // The number 42 is a type tag. It is tied to type "int".
9658 ```
9659
9660The `type_tag_for_datatype` attribute also accepts an optional third argument
9661that determines how the type of the function argument specified by either
9662`arg_idx` or `ptr_idx` is compared against the type associated with the type
9663tag. (Recall that for the `argument_with_type_tag` attribute, the type of the
9664function argument specified by `arg_idx` is compared against the type
9665associated with the type tag. Also recall that for the `pointer_with_type_tag`
9666attribute, the pointee type of the function argument specified by `ptr_idx` is
9667compared against the type associated with the type tag.) There are two supported
9668values for this optional third argument:
9669
9670- `layout_compatible` will cause types to be compared according to
9671 layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the
9672 layout-compatibility rules for two standard-layout struct types and for two
9673 standard-layout union types). This is useful when creating a type tag
9674 associated with a struct or union type. For example:
9675
9676 ```c++
9677 /* In mpi.h */
9678 typedef int MPI_Datatype;
9679 struct internal_mpi_double_int { double d; int i; };
9680 extern struct mpi_datatype mpi_datatype_double_int
9681 __attribute__(( type_tag_for_datatype(mpi,
9682 struct internal_mpi_double_int, layout_compatible) ));
9683
9684 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
9685
9686 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
9687 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
9688
9689 /* In user code */
9690 struct my_pair { double a; int b; };
9691 struct my_pair *buffer;
9692 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the
9693 // layout of my_pair is
9694 // compatible with that of
9695 // internal_mpi_double_int
9696
9697 struct my_int_pair { int a; int b; }
9698 struct my_int_pair *buffer2;
9699 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the
9700 // layout of my_int_pair
9701 // does not match that of
9702 // internal_mpi_double_int
9703 ```
9704
9705- `must_be_null` specifies that the function argument specified by either
9706 `arg_idx` (for the `argument_with_type_tag` attribute) or `ptr_idx` (for
9707 the `pointer_with_type_tag` attribute) should be a null pointer constant.
9708 The second argument to the `type_tag_for_datatype` attribute is ignored. For
9709 example:
9710
9711 ```c++
9712 /* In mpi.h */
9713 typedef int MPI_Datatype;
9714 extern struct mpi_datatype mpi_datatype_null
9715 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
9716
9717 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
9718 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
9719 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
9720
9721 /* In user code */
9722 struct my_pair { double a; int b; };
9723 struct my_pair *buffer;
9724 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
9725 // was specified but buffer
9726 // is not a null pointer
9727 ```)reST";
9728
9729static const char AttrDoc_TypeVisibility[] = R"reST(The `type_visibility` attribute allows the visibility of a type and its vague
9730linkage objects (vtable, typeinfo, typeinfo name) to be controlled separately from
9731the visibility of functions and data members of the type.
9732
9733For example, this can be used to give default visibility to the typeinfo and the vtable
9734of a type while still keeping hidden visibility on its member functions and static data
9735members.
9736
9737This attribute can only be applied to types and namespaces.
9738
9739If both `visibility` and `type_visibility` are applied to a type or a namespace, the
9740visibility specified with the `type_visibility` attribute overrides the visibility
9741provided with the regular `visibility` attribute.)reST";
9742
9743static const char AttrDoc_UPtr[] = R"reST(The `__uptr` qualifier specifies that a 32-bit pointer should be zero
9744extended when converted to a 64-bit pointer.)reST";
9745
9746static const char AttrDoc_Unavailable[] = R"reST(No documentation.)reST";
9747
9748static const char AttrDoc_Uninitialized[] = R"reST(The command-line parameter `-ftrivial-auto-var-init=*` can be used to
9749initialize trivial automatic stack variables. By default, trivial automatic
9750stack variables are uninitialized. This attribute is used to override the
9751command-line parameter, forcing variables to remain uninitialized. It has no
9752semantic meaning in that using uninitialized values is undefined behavior,
9753it rather documents the programmer's intent.)reST";
9754
9755static const char AttrDoc_Unlikely[] = R"reST(The `likely` and `unlikely` attributes are used as compiler hints.
9756The attributes are used to aid the compiler to determine which branch is
9757likely or unlikely to be taken. This is done by marking the branch substatement
9758with one of the two attributes.
9759
9760It isn't allowed to annotate a single statement with both `likely` and
9761`unlikely`. Annotating the `true` and `false` branch of an `if`
9762statement with the same likelihood attribute will result in a diagnostic and
9763the attributes are ignored on both branches.
9764
9765In a `switch` statement it's allowed to annotate multiple `case` labels
9766or the `default` label with the same likelihood attribute. This makes
9767\* all labels without an attribute have a neutral likelihood,
9768\* all labels marked `[[likely]]` have an equally positive likelihood, and
9769\* all labels marked `[[unlikely]]` have an equally negative likelihood.
9770The neutral likelihood is the more likely of path execution than the negative
9771likelihood. The positive likelihood is the more likely of path of execution
9772than the neutral likelihood.
9773
9774These attributes have no effect on the generated code when using
9775PGO (Profile-Guided Optimization) or at optimization level 0.
9776
9777In Clang, the attributes will be ignored if they're not placed on
9778\* the `case` or `default` label of a `switch` statement,
9779\* or on the substatement of an `if` or `else` statement,
9780\* or on the substatement of an `for` or `while` statement.
9781The C++ Standard recommends to honor them on every statement in the
9782path of execution, but that can be confusing:
9783
9784```c++
9785if (b) {
9786 [[unlikely]] --b; // Per the standard this is in the path of
9787 // execution, so this branch should be considered
9788 // unlikely. However, Clang ignores the attribute
9789 // here since it is not on the substatement.
9790}
9791
9792if (b) {
9793 --b;
9794 if(b)
9795 return;
9796 [[unlikely]] --b; // Not in the path of execution,
9797} // the branch has no likelihood information.
9798
9799if (b) {
9800 --b;
9801 foo(b);
9802 // Whether or not the next statement is in the path of execution depends
9803 // on the declaration of foo():
9804 // In the path of execution: void foo(int);
9805 // Not in the path of execution: [[noreturn]] void foo(int);
9806 // This means the likelihood of the branch depends on the declaration
9807 // of foo().
9808 [[unlikely]] --b;
9809}
9810```
9811
9812Below are some example usages of the likelihood attributes and their effects:
9813
9814```c++
9815if (b) [[likely]] { // Placement on the first statement in the branch.
9816 // The compiler will optimize to execute the code here.
9817} else {
9818}
9819
9820if (b)
9821 [[unlikely]] b++; // Placement on the first statement in the branch.
9822else {
9823 // The compiler will optimize to execute the code here.
9824}
9825
9826if (b) {
9827 [[unlikely]] b++; // Placement on the second statement in the branch.
9828} // The attribute will be ignored.
9829
9830if (b) [[likely]] {
9831 [[unlikely]] b++; // No contradiction since the second attribute
9832} // is ignored.
9833
9834if (b)
9835 ;
9836else [[likely]] {
9837 // The compiler will optimize to execute the code here.
9838}
9839
9840if (b)
9841 ;
9842else
9843 // The compiler will optimize to execute the next statement.
9844 [[likely]] b = f();
9845
9846if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
9847else [[likely]]; // and the attributes are ignored.
9848
9849if (b)
9850 [[likely]] int i = 5; // Issues a diagnostic since the attribute
9851 // isn't allowed on a declaration.
9852
9853switch (i) {
9854 [[likely]] case 1: // This value is likely
9855 ...
9856 break;
9857
9858 [[unlikely]] case 2: // This value is unlikely
9859 ...
9860 [[fallthrough]];
9861
9862 case 3: // No likelihood attribute
9863 ...
9864 [[likely]] break; // No effect
9865
9866 case 4: [[likely]] { // attribute on substatement has no effect
9867 ...
9868 break;
9869 }
9870
9871 [[unlikely]] default: // All other values are unlikely
9872 ...
9873 break;
9874}
9875
9876switch (i) {
9877 [[likely]] case 0: // This value and code path is likely
9878 ...
9879 [[fallthrough]];
9880
9881 case 1: // No likelihood attribute, code path is neutral
9882 break; // falling through has no effect on the likelihood
9883
9884 case 2: // No likelihood attribute, code path is neutral
9885 [[fallthrough]];
9886
9887 [[unlikely]] default: // This value and code path are both unlikely
9888 break;
9889}
9890
9891for(int i = 0; i != size; ++i) [[likely]] {
9892 ... // The loop is the likely path of execution
9893}
9894
9895for(const auto &E : Elements) [[likely]] {
9896 ... // The loop is the likely path of execution
9897}
9898
9899while(i != size) [[unlikely]] {
9900 ... // The loop is the unlikely path of execution
9901} // The generated code will optimize to skip the loop body
9902
9903while(true) [[unlikely]] {
9904 ... // The attribute has no effect
9905} // Clang elides the comparison and generates an infinite
9906 // loop
9907```)reST";
9908
9909static const char AttrDoc_UnsafeBufferUsage[] = R"reST(The attribute `[[clang::unsafe_buffer_usage]]` should be placed on functions
9910that need to be avoided as they are prone to buffer overflows or unsafe buffer
9911struct fields. It is designed to work together with the off-by-default compiler
9912warning `-Wunsafe-buffer-usage` to help codebases transition away from raw pointer
9913based buffer management, in favor of safer abstractions such as C++20 `std::span`.
9914The attribute causes `-Wunsafe-buffer-usage` to warn on every use of the function or
9915the field it is attached to, and it may also lead to emission of automatic fix-it
9916hints which would help the user replace the use of unsafe functions(/fields) with safe
9917alternatives, though the attribute can be used even when the fix can't be automated.
9918
9919- Attribute attached to functions: The attribute suppresses all
9920 `-Wunsafe-buffer-usage` warnings within the function it is attached to, as the
9921 function is now classified as unsafe. The attribute should be used carefully, as it
9922 will silence all unsafe operation warnings inside the function; including any new
9923 unsafe operations introduced in the future.
9924
9925 The attribute is warranted even if the only way a function can overflow
9926 the buffer is by violating the function's preconditions. For example, it
9927 would make sense to put the attribute on function `foo()` below because
9928 passing an incorrect size parameter would cause a buffer overflow:
9929
9930 ```c++
9931 [[clang::unsafe_buffer_usage]]
9932 void foo(int *buf, size_t size) {
9933 for (size_t i = 0; i < size; ++i) {
9934 buf[i] = i;
9935 }
9936 }
9937 ```
9938
9939 The attribute is NOT warranted when the function uses safe abstractions,
9940 assuming that these abstractions weren't misused outside the function.
9941 For example, function `bar()` below doesn't need the attribute,
9942 because assuming that the container `buf` is well-formed (has size that
9943 fits the original buffer it refers to), overflow cannot occur:
9944
9945 ```c++
9946 void bar(std::span<int> buf) {
9947 for (size_t i = 0; i < buf.size(); ++i) {
9948 buf[i] = i;
9949 }
9950 }
9951 ```
9952
9953 In this case function `bar()` enables the user to keep the buffer
9954 "containerized" in a span for as long as possible. On the other hand,
9955 Function `foo()` in the previous example may have internal
9956 consistency, but by accepting a raw buffer it requires the user to unwrap
9957 their span, which is undesirable according to the programming model
9958 behind `-Wunsafe-buffer-usage`.
9959
9960 The attribute is warranted when a function accepts a raw buffer only to
9961 immediately put it into a span:
9962
9963 ```c++
9964 [[clang::unsafe_buffer_usage]]
9965 void baz(int *buf, size_t size) {
9966 std::span<int> sp{ buf, size };
9967 for (size_t i = 0; i < sp.size(); ++i) {
9968 sp[i] = i;
9969 }
9970 }
9971 ```
9972
9973 In this case `baz()` does not contain any unsafe operations, but the awkward
9974 parameter type causes the caller to unwrap the span unnecessarily.
9975 Note that regardless of the attribute, code inside `baz()` isn't flagged
9976 by `-Wunsafe-buffer-usage` as unsafe. It is definitely undesirable,
9977 but if `baz()` is on an API surface, there is no way to improve it
9978 to make it as safe as `bar()` without breaking the source and binary
9979 compatibility with existing users of the function. In such cases
9980 the proper solution would be to create a different function (possibly
9981 an overload of `baz()`) that accepts a safe container like `bar()`,
9982 and then use the attribute on the original `baz()` to help the users
9983 update their code to use the new function.
9984
9985- Attribute attached to fields: The attribute should only be attached to
9986 struct fields, if the fields can not be updated to a safe type with bounds
9987 check, such as `std::span`. In other words, the buffers prone to unsafe accesses
9988 should always be updated to use safe containers/views and attaching the attribute
9989 must be last resort when such an update is infeasible.
9990
9991 The attribute can be placed on individual fields or a set of them as shown below.
9992
9993 ```c++
9994 struct A {
9995 [[clang::unsafe_buffer_usage]]
9996 int *ptr1;
9997
9998 [[clang::unsafe_buffer_usage]]
9999 int *ptr2, buf[10];
10000
10001 [[clang::unsafe_buffer_usage]]
10002 size_t sz;
10003 };
10004 ```
10005
10006 Here, every read/write to the fields `ptr1`, `ptr2`, `buf` and `sz` will trigger a warning
10007 that the field has been explicitly marked as unsafe due to unsafe-buffer operations.
10008
10009- Attribute attached to container constructors and factory functions: The
10010 spellings `[[clang::unsafe_buffer_usage_in_container]]` and
10011 `[[clang::unsafe_buffer_usage("container")]]` are equivalent and can be
10012 placed on two-parameter constructors and factory functions of container or
10013 view types (such as custom span types taking a `(pointer, size)` or
10014 `(begin, end)` pair) to opt them in to `-Wunsafe-buffer-usage-in-container`.
10015
10016 Unlike the general `[[clang::unsafe_buffer_usage]]` attribute, which warns on
10017 every call, this form suppresses the warning when the argument pair is
10018 provably safe -- for example, when constructing from `c.data(), c.size()` or
10019 `c.begin(), c.end()` on the same container object `c`, a constant-sized array
10020 with a matching bound, `&var, 1`, or a `0` size:
10021
10022 ```c++
10023 template <typename T>
10024 class CustomSpan {
10025 public:
10026 [[clang::unsafe_buffer_usage_in_container]]
10027 CustomSpan(T *ptr, size_t size);
10028
10029 template <typename It>
10030 [[clang::unsafe_buffer_usage("container")]]
10031 CustomSpan(It first, It last);
10032 };
10033
10034 template <typename T>
10035 [[clang::unsafe_buffer_usage("container")]]
10036 CustomSpan<T> MakeCustomSpan(T *ptr, size_t size);
10037
10038 void example(int *p, size_t n, MyVector<int> &v) {
10039 CustomSpan<int> s1(p, n); // warning: decoupled pointer and size
10040 auto s2 = MakeCustomSpan(p, n); // warning: decoupled pointer and size
10041 CustomSpan<int> s3(v.data(), v.size()); // no warning
10042 CustomSpan<int> s4(v.begin(), v.end()); // no warning
10043 auto s5 = MakeCustomSpan(v.data(), v.size()); // no warning
10044 }
10045 ```)reST";
10046
10047static const char AttrDoc_Unused[] = R"reST(When passing the `-Wunused` flag to Clang, entities that are unused by the
10048program may be diagnosed. The `[[maybe_unused]]` (or
10049`__attribute__((unused))`) attribute can be used to silence such diagnostics
10050when the entity cannot be removed. For instance, a local variable may exist
10051solely for use in an `assert()` statement, which makes the local variable
10052unused when `NDEBUG` is defined.
10053
10054The attribute may be applied to the declaration of a class, a typedef, a
10055variable, a function or method, a function parameter, an enumeration, an
10056enumerator, a non-static data member, or a label.
10057
10058```c++
10059#include <cassert>
10060
10061[[maybe_unused]] void f([[maybe_unused]] bool thing1,
10062 [[maybe_unused]] bool thing2) {
10063 [[maybe_unused]] bool b = thing1 && thing2;
10064 assert(b);
10065}
10066```)reST";
10067
10068static const char AttrDoc_UseHandle[] = R"reST(A function taking a handle by value might close the handle. If a function
10069parameter is annotated with `use_handle(tag)` it is assumed to not to change
10070the state of the handle. It is also assumed to require an open handle to work with.
10071The attribute requires a string literal argument to identify the handle being used.
10072
10073```c++
10074zx_status_t zx_port_wait(zx_handle_t handle [[clang::use_handle("zircon")]],
10075 zx_time_t deadline,
10076 zx_port_packet_t* packet);
10077```)reST";
10078
10079static const char AttrDoc_Used[] = R"reST(This attribute, when attached to a function or variable definition, indicates
10080that there may be references to the entity which are not apparent in the source
10081code. For example, it may be referenced from inline `asm`, or it may be
10082found through a dynamic symbol or section lookup.
10083
10084The compiler must emit the definition even if it appears to be unused, and it
10085must not apply optimizations which depend on fully understanding how the entity
10086is used.
10087
10088Whether this attribute has any effect on the linker depends on the target and
10089the linker. Most linkers support the feature of section garbage collection
10090(`--gc-sections`), also known as "dead stripping" (`ld64 -dead_strip`) or
10091discarding unreferenced sections (`link.exe /OPT:REF`). On COFF and Mach-O
10092targets (Windows and Apple platforms), the `used` attribute prevents symbols
10093from being removed by linker section GC. On ELF targets, it has no effect on its
10094own, and the linker may remove the definition if it is not otherwise referenced.
10095This linker GC can be avoided by also adding the `retain` attribute. Note
10096that `retain` requires special support from the linker; see that attribute's
10097documentation for further information.)reST";
10098
10099static const char AttrDoc_UsingIfExists[] = R"reST(The `using_if_exists` attribute applies to a using-declaration. It allows
10100programmers to import a declaration that potentially does not exist, instead
10101deferring any errors to the point of use. For instance:
10102
10103```c++
10104namespace empty_namespace {};
10105__attribute__((using_if_exists))
10106using empty_namespace::does_not_exist; // no error!
10107
10108does_not_exist x; // error: use of unresolved 'using_if_exists'
10109```
10110
10111The C++ spelling of the attribute (`[[clang::using_if_exists]]`) is also
10112supported as a clang extension, since ISO C++ doesn't support attributes in this
10113position. If the entity referred to by the using-declaration is found by name
10114lookup, the attribute has no effect. This attribute is useful for libraries
10115(primarily, libc++) that wish to redeclare a set of declarations in another
10116namespace, when the availability of those declarations is difficult or
10117impossible to detect at compile time with the preprocessor.)reST";
10118
10119static const char AttrDoc_Uuid[] = R"reST(No documentation.)reST";
10120
10121static const char AttrDoc_VTablePointerAuthentication[] = R"reST(No documentation.)reST";
10122
10123static const char AttrDoc_VecReturn[] = R"reST(No documentation.)reST";
10124
10125static const char AttrDoc_VecTypeHint[] = R"reST(No documentation.)reST";
10126
10127static const char AttrDoc_VectorCall[] = R"reST(On 32-bit x86 *and* x86_64 targets, this attribute changes the calling
10128convention of a function to pass vector parameters in SSE registers.
10129
10130On 32-bit x86 targets, this calling convention is similar to `__fastcall`.
10131The first two integer parameters are passed in ECX and EDX. Subsequent integer
10132parameters are passed in memory, and callee clears the stack. On x86_64
10133targets, the callee does *not* clear the stack, and integer parameters are
10134passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling
10135convention.
10136
10137On both 32-bit x86 and x86_64 targets, vector and floating point arguments are
10138passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are
10139passed in sequential SSE registers if enough are available. If AVX is enabled,
10140256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that
10141cannot be passed in registers for any reason is passed by reference, which
10142allows the caller to align the parameter memory.
10143
10144See the documentation for [`__vectorcall`][__vectorcall] on MSDN for more details.
10145
10146[__vectorcall]: http://msdn.microsoft.com/en-us/library/dn375768.aspx)reST";
10147
10148static const char AttrDoc_Visibility[] = R"reST(No documentation.)reST";
10149
10150static const char AttrDoc_WarnUnused[] = R"reST(The `warn_unused` attribute can be placed on the declaration of a structure or union type.
10151When 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.
10152Those constructor or destructor invocations are not considered a use if the type is declared with the `warn_unused` attribute.
10153The variable is considered used if it is named outside of its declaration.
10154
10155This 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.
10156
10157```c++
10158struct [[gnu::warn_unused]] S {
10159 S();
10160 ~S();
10161};
10162
10163struct T {
10164 T();
10165 ~T();
10166 };
10167
10168 int func() {
10169 S s1; // -Wunused-variable warning
10170 S s2; // No -Wunused-variable warning because of the member access expression below
10171 S s3; // No -Wunused-variable warning because of the sizeof operand below
10172 T t; // No -Wunused-variable warning
10173
10174 s2.~S();
10175 return sizeof(s3);
10176 }
10177```)reST";
10178
10179static const char AttrDoc_WarnUnusedResult[] = R"reST(Clang supports the ability to diagnose when the results of a function call
10180expression are discarded under suspicious circumstances. A diagnostic is
10181generated when a function or its return type is marked with `[[nodiscard]]`
10182(or `__attribute__((warn_unused_result))`) and the function call appears as a
10183potentially-evaluated discarded-value expression that is not explicitly cast to
10184`void`.
10185
10186A string literal may optionally be provided to the attribute, which will be
10187reproduced in any resulting diagnostics. Redeclarations using different forms
10188of the attribute (with or without the string literal or with different string
10189literal contents) are allowed. If there are redeclarations of the entity with
10190differing string literals, it is unspecified which one will be used by Clang
10191in any resulting diagnostics.
10192
10193```c++
10194struct [[nodiscard]] error_info { /*...*/ };
10195error_info enable_missile_safety_mode();
10196
10197void launch_missiles();
10198void test_missiles() {
10199 enable_missile_safety_mode(); // diagnoses
10200 launch_missiles();
10201}
10202error_info &foo();
10203void f() { foo(); } // Does not diagnose, error_info is a reference.
10204```
10205
10206Additionally, discarded temporaries resulting from a call to a constructor
10207marked with `[[nodiscard]]` or a constructor of a type marked
10208`[[nodiscard]]` will also diagnose. This also applies to type conversions that
10209use the annotated `[[nodiscard]]` constructor or result in an annotated type.
10210
10211```c++
10212struct [[nodiscard]] marked_type {/*..*/ };
10213struct marked_ctor {
10214 [[nodiscard]] marked_ctor();
10215 marked_ctor(int);
10216};
10217
10218struct S {
10219 operator marked_type() const;
10220 [[nodiscard]] operator int() const;
10221};
10222
10223void usages() {
10224 marked_type(); // diagnoses.
10225 marked_ctor(); // diagnoses.
10226 marked_ctor(3); // Does not diagnose, int constructor isn't marked nodiscard.
10227
10228 S s;
10229 static_cast<marked_type>(s); // diagnoses
10230 (int)s; // diagnoses
10231}
10232```)reST";
10233
10234static const char AttrDoc_Weak[] = R"reST(In supported output formats the `weak` attribute can be used to
10235specify that a variable or function should be emitted as a symbol with
10236`weak` (if a definition) or `extern_weak` (if a declaration of an
10237external symbol) [linkage](https://llvm.org/docs/LangRef.html#linkage-types).
10238
10239If there is a non-weak definition of the symbol the linker will select
10240that over the weak. They must have same type and alignment (variables
10241must also have the same size), but may have a different value.
10242
10243If there are multiple weak definitions of same symbol, but no non-weak
10244definition, they should have same type, size, alignment and value, the
10245linker will select one of them (see also [selectany] attribute).
10246
10247If the `weak` attribute is applied to a `const` qualified variable
10248definition that variable is no longer consider a compiletime constant
10249as its value can change during linking (or dynamic linking). This
10250means that it can e.g no longer be part of an initializer expression.
10251
10252```c
10253const int ANSWER __attribute__ ((weak)) = 42;
10254
10255/* This function may be replaced link-time */
10256__attribute__ ((weak)) void debug_log(const char *msg)
10257{
10258 fprintf(stderr, "DEBUG: %s\n", msg);
10259}
10260
10261int main(int argc, const char **argv)
10262{
10263 debug_log ("Starting up...");
10264
10265 /* This may print something else than "6 * 7 = 42",
10266 if there is a non-weak definition of "ANSWER" in
10267 an object linked in */
10268 printf("6 * 7 = %d\n", ANSWER);
10269
10270 return 0;
10271 }
10272```
10273
10274If an external declaration is marked weak and that symbol does not
10275exist during linking (possibly dynamic) the address of the symbol will
10276evaluate to NULL.
10277
10278```c
10279void may_not_exist(void) __attribute__ ((weak));
10280
10281int main(int argc, const char **argv)
10282{
10283 if (may_not_exist) {
10284 may_not_exist();
10285 } else {
10286 printf("Function did not exist\n");
10287 }
10288 return 0;
10289}
10290```)reST";
10291
10292static const char AttrDoc_WeakImport[] = R"reST(No documentation.)reST";
10293
10294static const char AttrDoc_WeakRef[] = R"reST(No documentation.)reST";
10295
10296static const char AttrDoc_WebAssemblyExportName[] = R"reST(Clang supports the `__attribute__((export_name(<name>)))`
10297attribute for the WebAssembly target. This attribute may be attached to a
10298function declaration, where it modifies how the symbol is to be exported
10299from the linked WebAssembly.
10300
10301WebAssembly functions are exported via string name. By default when a symbol
10302is exported, the export name for C/C++ symbols are the same as their C/C++
10303symbol names. This attribute can be used to override the default behavior, and
10304request a specific string name be used instead.)reST";
10305
10306static const char AttrDoc_WebAssemblyFuncref[] = R"reST(Clang supports the `__attribute__((export_name(<name>)))`
10307attribute for the WebAssembly target. This attribute may be attached to a
10308function declaration, where it modifies how the symbol is to be exported
10309from the linked WebAssembly.
10310
10311WebAssembly functions are exported via string name. By default when a symbol
10312is exported, the export name for C/C++ symbols are the same as their C/C++
10313symbol names. This attribute can be used to override the default behavior, and
10314request a specific string name be used instead.)reST";
10315
10316static const char AttrDoc_WebAssemblyImportModule[] = R"reST(Clang supports the `__attribute__((import_module(<module_name>)))`
10317attribute for the WebAssembly target. This attribute may be attached to a
10318function declaration, where it modifies how the symbol is to be imported
10319within the WebAssembly linking environment.
10320
10321WebAssembly imports use a two-level namespace scheme, consisting of a module
10322name, which typically identifies a module from which to import, and a field
10323name, which typically identifies a field from that module to import. By
10324default, module names for C/C++ symbols are assigned automatically by the
10325linker. This attribute can be used to override the default behavior, and
10326request a specific module name be used instead.)reST";
10327
10328static const char AttrDoc_WebAssemblyImportName[] = R"reST(Clang supports the `__attribute__((import_name(<name>)))`
10329attribute for the WebAssembly target. This attribute may be attached to a
10330function declaration, where it modifies how the symbol is to be imported
10331within the WebAssembly linking environment.
10332
10333WebAssembly imports use a two-level namespace scheme, consisting of a module
10334name, which typically identifies a module from which to import, and a field
10335name, which typically identifies a field from that module to import. By
10336default, field names for C/C++ symbols are the same as their C/C++ symbol
10337names. This attribute can be used to override the default behavior, and
10338request a specific field name be used instead.)reST";
10339
10340static const char AttrDoc_WorkGroupSizeHint[] = R"reST(No documentation.)reST";
10341
10342static const char AttrDoc_X86ForceAlignArgPointer[] = R"reST(Use this attribute to force stack alignment.
10343
10344Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions
10345(like 'movaps') that work with the stack require operands to be 16-byte aligned.
10346This attribute realigns the stack in the function prologue to make sure the
10347stack can be used with SSE instructions.
10348
10349Note that the x86_64 ABI forces 16-byte stack alignment at the call site.
10350Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in
10351rare cases where the caller does not align the stack properly (e.g. flow
10352jumps from i386 arch code).
10353
10354```c
10355__attribute__ ((force_align_arg_pointer))
10356void f () {
10357 ...
10358}
10359```)reST";
10360
10361static const char AttrDoc_XRayInstrument[] = R"reST(`__attribute__((xray_always_instrument))` or
10362`[[clang::xray_always_instrument]]` is used to mark member functions (in C++),
10363methods (in Objective C), and free functions (in C, C++, and Objective C) to be
10364instrumented with XRay. This will cause the function to always have space at
10365the beginning and exit points to allow for runtime patching.
10366
10367Conversely, `__attribute__((xray_never_instrument))` or
10368`[[clang::xray_never_instrument]]` will inhibit the insertion of these
10369instrumentation points.
10370
10371If a function has neither of these attributes, they become subject to the XRay
10372heuristics used to determine whether a function should be instrumented or
10373otherwise.
10374
10375`__attribute__((xray_log_args(N)))` or `[[clang::xray_log_args(N)]]` is
10376used to preserve N function arguments for the logging function. Currently,
10377only N==1 is supported.)reST";
10378
10379static const char AttrDoc_XRayLogArgs[] = R"reST(`__attribute__((xray_always_instrument))` or
10380`[[clang::xray_always_instrument]]` is used to mark member functions (in C++),
10381methods (in Objective C), and free functions (in C, C++, and Objective C) to be
10382instrumented with XRay. This will cause the function to always have space at
10383the beginning and exit points to allow for runtime patching.
10384
10385Conversely, `__attribute__((xray_never_instrument))` or
10386`[[clang::xray_never_instrument]]` will inhibit the insertion of these
10387instrumentation points.
10388
10389If a function has neither of these attributes, they become subject to the XRay
10390heuristics used to determine whether a function should be instrumented or
10391otherwise.
10392
10393`__attribute__((xray_log_args(N)))` or `[[clang::xray_log_args(N)]]` is
10394used to preserve N function arguments for the logging function. Currently,
10395only N==1 is supported.)reST";
10396
10397static const char AttrDoc_ZeroCallUsedRegs[] = R"reST(This attribute, when attached to a function, causes the compiler to zero a
10398subset of all call-used registers before the function returns. It's used to
10399increase program security by either mitigating [Return-Oriented Programming][return-oriented programming]
10400(ROP) attacks or preventing information leakage through registers.
10401
10402The term "call-used" means registers which are not guaranteed to be preserved
10403unchanged for the caller by the current calling convention. This could also be
10404described as "caller-saved" or "not callee-saved".
10405
10406The `choice` parameters gives the programmer flexibility to choose the subset
10407of the call-used registers to be zeroed:
10408
10409- `skip` doesn't zero any call-used registers. This choice overrides any
10410 command-line arguments.
10411- `used` only zeros call-used registers used in the function. By `used`, we
10412 mean a register whose contents have been set or referenced in the function.
10413- `used-gpr` only zeros call-used GPR registers used in the function.
10414- `used-arg` only zeros call-used registers used to pass arguments to the
10415 function.
10416- `used-gpr-arg` only zeros call-used GPR registers used to pass arguments to
10417 the function.
10418- `all` zeros all call-used registers.
10419- `all-gpr` zeros all call-used GPR registers.
10420- `all-arg` zeros all call-used registers used to pass arguments to the
10421 function.
10422- `all-gpr-arg` zeros all call-used GPR registers used to pass arguments to
10423 the function.
10424
10425The default for the attribute is controlled by the `-fzero-call-used-regs`
10426flag.
10427
10428[return-oriented programming]: https://en.wikipedia.org/wiki/Return-oriented_programming)reST";
10429