| 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 | |
| 11 | static const char AttrDoc_AArch64SVEPcs[] = R"reST(On AArch64 targets, this attribute changes the calling convention of a |
| 12 | function to preserve additional Scalable Vector registers and Scalable |
| 13 | Predicate registers relative to the default calling convention used for |
| 14 | AArch64. |
| 15 | |
| 16 | This means it is more efficient to call such functions from code that performs |
| 17 | extensive scalable vector and scalable predicate calculations, because fewer |
| 18 | live SVE registers need to be saved. This property makes it well-suited for SVE |
| 19 | math library functions, which are typically leaf functions that require a small |
| 20 | number of registers. |
| 21 | |
| 22 | However, using this attribute also means that it is more expensive to call |
| 23 | a function that adheres to the default calling convention from within such |
| 24 | a function. Therefore, it is recommended that this attribute is only used |
| 25 | for leaf functions. |
| 26 | |
| 27 | For more information, see the documentation for `aarch64_sve_pcs` in the |
| 28 | ARM 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 | |
| 32 | static const char AttrDoc_AArch64VectorPcs[] = R"reST(On AArch64 targets, this attribute changes the calling convention of a |
| 33 | function to preserve additional floating-point and Advanced SIMD registers |
| 34 | relative to the default calling convention used for AArch64. |
| 35 | |
| 36 | This means it is more efficient to call such functions from code that performs |
| 37 | extensive floating-point and vector calculations, because fewer live SIMD and FP |
| 38 | registers need to be saved. This property makes it well-suited for e.g. |
| 39 | floating-point or vector math library functions, which are typically leaf |
| 40 | functions that require a small number of registers. |
| 41 | |
| 42 | However, using this attribute also means that it is more expensive to call |
| 43 | a function that adheres to the default calling convention from within such |
| 44 | a function. Therefore, it is recommended that this attribute is only used |
| 45 | for leaf functions. |
| 46 | |
| 47 | For more information, see the documentation for [aarch64_vector_pcs][aarch64_vector_pcs] on |
| 48 | the 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 | |
| 52 | static const char AttrDoc_AMDGPUAvailableVisible[] = R"reST(This attribute controls availability and visibility as described in the [AMDGPU |
| 53 | Memory Model](https://llvm.org/docs/AMDGPUMemoryModel.html). When placed on |
| 54 | an atomic expression or fence, the resulting atomic or fence instruction carries |
| 55 | the corresponding *AV Metadata*. |
| 56 | |
| 57 | The attribute takes a string literal as an argument, which currently has only |
| 58 | one 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 | |
| 72 | static const char AttrDoc_AMDGPUFlatWorkGroupSize[] = R"reST(The flat work-group size is the number of work-items in the work-group size |
| 73 | specified when the kernel is dispatched. It is the product of the sizes of the |
| 74 | x, y, and z dimension of the work-group. |
| 75 | |
| 76 | Clang supports the |
| 77 | `__attribute__((amdgpu_flat_work_group_size(<min>, <max>)))` attribute for the |
| 78 | AMDGPU target. This attribute may be attached to a kernel function definition |
| 79 | and is an optimization hint. |
| 80 | |
| 81 | `<min>` parameter specifies the minimum flat work-group size, and `<max>` |
| 82 | parameter 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` |
| 84 | as `<min>, <max>` implies the default behavior (`128, 256`). |
| 85 | |
| 86 | If specified, the AMDGPU target backend might be able to produce better machine |
| 87 | code for barriers and perform scratch promotion by estimating available group |
| 88 | segment size. |
| 89 | |
| 90 | An 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 | |
| 95 | static const char AttrDoc_AMDGPUMaxNumWorkGroups[] = R"reST(This attribute specifies the max number of work groups when the kernel |
| 96 | is dispatched. |
| 97 | |
| 98 | Clang 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 |
| 101 | AMDGPU target. This attribute may be attached to HIP or OpenCL kernel function |
| 102 | definitions and is an optimization hint. |
| 103 | |
| 104 | The `<x>` parameter specifies the maximum number of work groups in the x dimension. |
| 105 | Similarly `<y>` and `<z>` are for the y and z dimensions respectively. |
| 106 | Each of the three values must be greater than 0 when provided. The `<x>` parameter |
| 107 | is required, while `<y>` and `<z>` are optional with default value of 1. |
| 108 | |
| 109 | If specified, the AMDGPU target backend might be able to produce better machine |
| 110 | code. |
| 111 | |
| 112 | An 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 | |
| 117 | static const char AttrDoc_AMDGPUNamedBarrierWrapper[] = R"reST()reST" ; |
| 118 | |
| 119 | static const char AttrDoc_AMDGPUNumSGPR[] = R"reST(:::{warning} |
| 120 | These attributes are deprecated. Use the `amdgpu_waves_per_eu` attribute to |
| 121 | control SGPR and VGPR usage instead. |
| 122 | ::: |
| 123 | |
| 124 | Clang supports the `__attribute__((amdgpu_num_sgpr(<num_sgpr>)))` and |
| 125 | `__attribute__((amdgpu_num_vgpr(<num_vgpr>)))` attributes for the AMDGPU |
| 126 | target. These attributes may be attached to a kernel function definition and are |
| 127 | an optimization hint. |
| 128 | |
| 129 | If these attributes are specified, then the AMDGPU target backend will attempt |
| 130 | to limit the number of SGPRs and/or VGPRs used to the specified value(s). The |
| 131 | number of used SGPRs and/or VGPRs may further be rounded up to satisfy the |
| 132 | allocation requirements or constraints of the subtarget. Passing `0` as |
| 133 | `num_sgpr` and/or `num_vgpr` implies the default behavior (no limits). |
| 134 | |
| 135 | These attributes can be used to test the AMDGPU target backend. It is |
| 136 | recommended that the `amdgpu_waves_per_eu` attribute be used to control |
| 137 | resources such as SGPRs and VGPRs since it is aware of the limits for different |
| 138 | subtargets. |
| 139 | |
| 140 | An 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 | |
| 147 | static const char AttrDoc_AMDGPUNumVGPR[] = R"reST(:::{warning} |
| 148 | These attributes are deprecated. Use the `amdgpu_waves_per_eu` attribute to |
| 149 | control SGPR and VGPR usage instead. |
| 150 | ::: |
| 151 | |
| 152 | Clang supports the `__attribute__((amdgpu_num_sgpr(<num_sgpr>)))` and |
| 153 | `__attribute__((amdgpu_num_vgpr(<num_vgpr>)))` attributes for the AMDGPU |
| 154 | target. These attributes may be attached to a kernel function definition and are |
| 155 | an optimization hint. |
| 156 | |
| 157 | If these attributes are specified, then the AMDGPU target backend will attempt |
| 158 | to limit the number of SGPRs and/or VGPRs used to the specified value(s). The |
| 159 | number of used SGPRs and/or VGPRs may further be rounded up to satisfy the |
| 160 | allocation requirements or constraints of the subtarget. Passing `0` as |
| 161 | `num_sgpr` and/or `num_vgpr` implies the default behavior (no limits). |
| 162 | |
| 163 | These attributes can be used to test the AMDGPU target backend. It is |
| 164 | recommended that the `amdgpu_waves_per_eu` attribute be used to control |
| 165 | resources such as SGPRs and VGPRs since it is aware of the limits for different |
| 166 | subtargets. |
| 167 | |
| 168 | An 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 | |
| 175 | static const char AttrDoc_AMDGPUWavesPerEU[] = R"reST(A compute unit (CU) is responsible for executing the wavefronts of a work-group. |
| 176 | It is composed of one or more execution units (EU), which are responsible for |
| 177 | executing the wavefronts. An EU can have enough resources to maintain the state |
| 178 | of more than one executing wavefront. This allows an EU to hide latency by |
| 179 | switching between wavefronts in a similar way to symmetric multithreading on a |
| 180 | CPU. In order to allow the state for multiple wavefronts to fit on an EU, the |
| 181 | resources used by a single wavefront have to be limited. For example, the number |
| 182 | of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding, |
| 183 | but can result in having to spill some register state to memory. |
| 184 | |
| 185 | Clang supports the `__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))` |
| 186 | attribute for the AMDGPU target. This attribute may be attached to a kernel |
| 187 | function 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 |
| 191 | per EU (must be greater than `<min>` if specified). If `<max>` is omitted, |
| 192 | then there is no restriction on the maximum number of waves per EU other than |
| 193 | the 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 | |
| 196 | If specified, this attribute allows an advanced developer to tune the number of |
| 197 | wavefronts that are capable of fitting within the resources of an EU. The AMDGPU |
| 198 | target backend can use this information to limit resources, such as number of |
| 199 | SGPRs, number of VGPRs, size of available group and private memory segments, in |
| 200 | such 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 |
| 202 | more wavefronts can hide memory latency but limits available registers which |
| 203 | can result in spilling. Requesting fewer wavefronts can help reduce cache |
| 204 | thrashing, but can reduce memory latency hiding. |
| 205 | |
| 206 | This attribute controls the machine code generated by the AMDGPU target backend |
| 207 | to ensure it is capable of meeting the requested values. However, when the |
| 208 | kernel is executed, there may be other reasons that prevent meeting the request, |
| 209 | for example, there may be wavefronts from other kernels executing on the EU. |
| 210 | |
| 211 | An 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 | |
| 216 | The AMDGPU target backend will emit a warning whenever it is unable to |
| 217 | create machine code that meets the request.)reST" ; |
| 218 | |
| 219 | static const char AttrDoc_ARMInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt("TYPE")))` attribute on |
| 220 | ARM targets. This attribute may be attached to a function definition and |
| 221 | instructs the backend to generate appropriate function entry/exit code so that |
| 222 | it can be used directly as an interrupt service routine. |
| 223 | |
| 224 | The parameter passed to the interrupt attribute is optional, but if |
| 225 | provided it must be a string literal with one of the following values: "IRQ", |
| 226 | "FIQ", "SWI", "ABORT", "UNDEF". |
| 227 | |
| 228 | The 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 | |
| 258 | static const char AttrDoc_ARMInterruptSaveFP[] = R"reST(Clang supports the GNU style `__attribute__((interrupt_save_fp("TYPE")))` |
| 259 | on ARM targets. This attribute behaves the same way as the ARM interrupt |
| 260 | attribute, except the general purpose floating point registers are also saved, |
| 261 | along with FPEXC and FPSCR. Note, even on M-class CPUs, where the floating |
| 262 | point context can be automatically saved depending on the FPCCR, the general |
| 263 | purpose floating point registers will be saved.)reST" ; |
| 264 | |
| 265 | static const char AttrDoc_ARMSaveFP[] = R"reST()reST" ; |
| 266 | |
| 267 | static const char AttrDoc_AVRInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt))` attribute on |
| 268 | AVR targets. This attribute may be attached to a function definition and instructs |
| 269 | the backend to generate appropriate function entry/exit code so that it can be used |
| 270 | directly as an interrupt service routine. |
| 271 | |
| 272 | On the AVR, the hardware globally disables interrupts when an interrupt is executed. |
| 273 | The first instruction of an interrupt handler declared with this attribute is a SEI |
| 274 | instruction to re-enable interrupts. See also the signal attribute that |
| 275 | does not insert a SEI instruction.)reST" ; |
| 276 | |
| 277 | static const char AttrDoc_AVRSignal[] = R"reST(Clang supports the GNU style `__attribute__((signal))` attribute on |
| 278 | AVR targets. This attribute may be attached to a function definition and instructs |
| 279 | the backend to generate appropriate function entry/exit code so that it can be used |
| 280 | directly as an interrupt service routine. |
| 281 | |
| 282 | Interrupt handler functions defined with the signal attribute do not re-enable interrupts.)reST" ; |
| 283 | |
| 284 | static const char AttrDoc_AbiTag[] = R"reST(The `abi_tag` attribute can be applied to a function, variable, class or |
| 285 | inline namespace declaration to modify the mangled name of the entity. It gives |
| 286 | the ability to distinguish between different versions of the same entity but |
| 287 | with different ABI versions supported. For example, a newer version of a class |
| 288 | could have a different set of data members and thus have a different size. Using |
| 289 | the `abi_tag` attribute, it is possible to have different mangled names for |
| 290 | a global variable of the class type. Therefore, the old code could keep using |
| 291 | the old mangled name and the new code will use the new mangled name with tags.)reST" ; |
| 292 | |
| 293 | static const char AttrDoc_AcquireCapability[] = R"reST(Marks a function as acquiring a capability.)reST" ; |
| 294 | |
| 295 | static const char AttrDoc_AcquireHandle[] = R"reST(If this annotation is on a function or a function type it is assumed to return |
| 296 | a new handle. In case this annotation is on an output parameter, |
| 297 | the function is assumed to fill the corresponding argument with a new |
| 298 | handle. The attribute requires a string literal argument which used to |
| 299 | identify the handle with later uses of `use_handle` or |
| 300 | `release_handle`. |
| 301 | |
| 302 | ```c++ |
| 303 | // Output arguments from Zircon. |
| 304 | zx_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, ... ); |
| 311 | int open(const char *path, int oflag, ... ) __attribute__((acquire_handle("tag"))); |
| 312 | ```)reST" ; |
| 313 | |
| 314 | static const char AttrDoc_AcquiredAfter[] = R"reST(No documentation.)reST" ; |
| 315 | |
| 316 | static const char AttrDoc_AcquiredBefore[] = R"reST(No documentation.)reST" ; |
| 317 | |
| 318 | static const char AttrDoc_AddressSpace[] = R"reST(:::{Note} |
| 319 | This attribute is mainly intended to be used by target headers |
| 320 | provided by the toolchain. End users should prefer the documented, named |
| 321 | address space annotations for their platform, such as the |
| 322 | [OpenCL address spaces], `__global__`, `__local__`, or something else. |
| 323 | ::: |
| 324 | |
| 325 | The `address_space` attribute functions as a type qualifier that allows the |
| 326 | programmer to specify the address space for a pointer or reference type. |
| 327 | Qualified pointer types are considered distinct types for the purposes of |
| 328 | overload resolution. The attribute takes a single, non-negative integer |
| 329 | constant expression identifying the address space. For example: |
| 330 | |
| 331 | ```c |
| 332 | int * __attribute__((address_space(1))) ptr; |
| 333 | |
| 334 | void foo(__attribute__((address_space(2))) float *buf); |
| 335 | ``` |
| 336 | |
| 337 | Only one address space qualifier may be applied to a given pointer or reference |
| 338 | type. Where address spaces are allowed (e.g., variables, parameters, return |
| 339 | types) and what values are valid depends on the target and language mode. |
| 340 | |
| 341 | The meaning of each value is defined by the target; multiple address spaces are |
| 342 | used in environments such as OpenCL, CUDA, HIP, and other GPU programming |
| 343 | models to distinguish global, local, constant, and private memory. See for |
| 344 | example the address spaces defined in the [NVPTX Usage Guide][nvptx usage guide] and the |
| 345 | [AMDGPU Usage Guide][amdgpu usage guide]. |
| 346 | |
| 347 | Address spaces may partially overlap or be entirely distinct. The compiler may |
| 348 | reject attempts to convert between distinct, incompatible address spaces. |
| 349 | Pointer width may vary between different address spaces, so some explicit casts |
| 350 | may truncate. |
| 351 | |
| 352 | For more information, refer to [ISO TR18037][iso tr18037], which covers embedded C language |
| 353 | extensions. Section 5 covers named address spaces. |
| 354 | |
| 355 | [amdgpu usage guide]: https://llvm.org/docs/AMDGPUUsage.html#address-spaces |
| 356 | [iso tr18037]: https://standards.iso.org/ittf/PubliclyAvailableStandards/c051126_ISO_IEC_TR_18037_2008.zip |
| 357 | [nvptx usage guide]: https://llvm.org/docs/NVPTXUsage.html#address-spaces)reST" ; |
| 358 | |
| 359 | static const char AttrDoc_Alias[] = R"reST(No documentation.)reST" ; |
| 360 | |
| 361 | static const char AttrDoc_AlignMac68k[] = R"reST()reST" ; |
| 362 | |
| 363 | static const char AttrDoc_AlignNatural[] = R"reST()reST" ; |
| 364 | |
| 365 | static const char AttrDoc_AlignValue[] = R"reST(The align_value attribute can be added to the typedef of a pointer type or the |
| 366 | declaration of a variable of pointer or reference type. It specifies that the |
| 367 | pointer will point to, or the reference will bind to, only objects with at |
| 368 | least the provided alignment. This alignment value must be some positive power |
| 369 | of 2. |
| 370 | |
| 371 | ```c |
| 372 | typedef double * aligned_double_ptr __attribute__((align_value(64))); |
| 373 | void foo(double & x __attribute__((align_value(128))), |
| 374 | aligned_double_ptr y) { ... } |
| 375 | ``` |
| 376 | |
| 377 | If the pointer value does not have the specified alignment at runtime, the |
| 378 | behavior of the program is undefined.)reST" ; |
| 379 | |
| 380 | static const char AttrDoc_Aligned[] = R"reST(No documentation.)reST" ; |
| 381 | |
| 382 | static const char AttrDoc_AllocAlign[] = R"reST(Use `__attribute__((alloc_align(<parameter-index>)))` on a declaration with a |
| 383 | function prototype to specify that the prototype's return value (which must be a |
| 384 | pointer type) is at least as aligned as the value of the indicated parameter. |
| 385 | This includes functions, Objective-C methods, blocks, and declarations of |
| 386 | function pointer, member function pointer, function reference, and block pointer |
| 387 | types. The attribute can also be applied to typedef or type alias declarations |
| 388 | whose underlying type has a function prototype. |
| 389 | |
| 390 | The parameter is given by its index in the list of formal parameters; the first |
| 391 | parameter has index 1 unless the function is a C++ non-static member function, |
| 392 | in which case the first parameter has index 2 to account for the implicit `this` |
| 393 | parameter. |
| 394 | |
| 395 | ```c++ |
| 396 | // The returned pointer has the alignment specified by the first parameter. |
| 397 | void *a(size_t align) __attribute__((alloc_align(1))); |
| 398 | |
| 399 | // The function pointer's returned pointer has the alignment specified by |
| 400 | // the first parameter of the pointed-to function. |
| 401 | void *(*allocator)(size_t align) __attribute__((alloc_align(1))); |
| 402 | |
| 403 | // The returned pointer has the alignment specified by the second parameter. |
| 404 | void *b(void *v, size_t align) __attribute__((alloc_align(2))); |
| 405 | |
| 406 | // The returned pointer has the alignment specified by the second visible |
| 407 | // parameter, however it must be adjusted for the implicit 'this' parameter. |
| 408 | void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3))); |
| 409 | ``` |
| 410 | |
| 411 | Note that this attribute merely informs the compiler that a function always |
| 412 | returns a sufficiently aligned pointer. It does not cause the compiler to |
| 413 | emit code to enforce that alignment. The behavior is undefined if the returned |
| 414 | pointer is not sufficiently aligned.)reST" ; |
| 415 | |
| 416 | static const char AttrDoc_AllocSize[] = R"reST(The `alloc_size` attribute can be placed on functions that return pointers in |
| 417 | order to hint to the compiler how many bytes of memory will be available at the |
| 418 | returned pointer. `alloc_size` takes one or two arguments. |
| 419 | |
| 420 | - `alloc_size(N)` implies that argument number N equals the number of |
| 421 | available bytes at the returned pointer. |
| 422 | - `alloc_size(N, M)` implies that the product of argument number N and |
| 423 | argument number M equals the number of available bytes at the returned |
| 424 | pointer. |
| 425 | |
| 426 | Argument numbers are 1-based. |
| 427 | |
| 428 | An example of how to use `alloc_size` |
| 429 | |
| 430 | ```c |
| 431 | void *my_malloc(int a) __attribute__((alloc_size(1))); |
| 432 | void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2))); |
| 433 | |
| 434 | int main() { |
| 435 | void *const p = my_malloc(100); |
| 436 | assert(__builtin_object_size(p, 0) == 100); |
| 437 | void *const a = my_calloc(20, 5); |
| 438 | assert(__builtin_object_size(a, 0) == 100); |
| 439 | } |
| 440 | ``` |
| 441 | |
| 442 | When `-Walloc-size` is enabled, this attribute allows the compiler to |
| 443 | diagnose cases when the allocated memory is insufficient for the size of the |
| 444 | type the returned pointer is cast to. |
| 445 | |
| 446 | ```c |
| 447 | void *my_malloc(int a) __attribute__((alloc_size(1))); |
| 448 | void consumer_func(int *); |
| 449 | |
| 450 | int main() { |
| 451 | int *ptr = my_malloc(sizeof(int)); // no warning |
| 452 | int *w = my_malloc(1); // warning: allocation of insufficient size '1' for type 'int' with size '4' |
| 453 | consumer_func(my_malloc(1)); // warning: allocation of insufficient size '1' for type 'int' with size '4' |
| 454 | } |
| 455 | ``` |
| 456 | |
| 457 | :::{Note} |
| 458 | This attribute works differently in clang than it does in GCC. |
| 459 | Specifically, clang will only trace `const` pointers (as above); we give up |
| 460 | on pointers that are not marked as `const`. In the vast majority of cases, |
| 461 | this is unimportant, because LLVM has support for the `alloc_size` |
| 462 | attribute. However, this may cause mildly unintuitive behavior when used with |
| 463 | other attributes, such as `enable_if`. |
| 464 | :::)reST" ; |
| 465 | |
| 466 | static const char AttrDoc_Allocating[] = R"reST(Declares that a function potentially allocates heap memory, and prevents any potential inference |
| 467 | of `nonallocating` by the compiler.)reST" ; |
| 468 | |
| 469 | static const char AttrDoc_AlwaysDestroy[] = R"reST(The `always_destroy` attribute specifies that a variable with static or thread |
| 470 | storage duration should have its exit-time destructor run. This attribute is the |
| 471 | default unless clang was invoked with -fno-c++-static-destructors. |
| 472 | |
| 473 | If a variable is explicitly declared with this attribute, Clang will silence |
| 474 | otherwise applicable `-Wexit-time-destructors` warnings.)reST" ; |
| 475 | |
| 476 | static const char AttrDoc_AlwaysInline[] = R"reST(Inlining heuristics are disabled and inlining is always attempted regardless of |
| 477 | optimization level. |
| 478 | |
| 479 | `[[clang::always_inline]]` spelling can be used as a statement attribute; other |
| 480 | spellings of the attribute are not supported on statements. If a statement is |
| 481 | marked `[[clang::always_inline]]` and contains calls, the compiler attempts |
| 482 | to inline those calls. |
| 483 | |
| 484 | ```c |
| 485 | int example(void) { |
| 486 | int i; |
| 487 | [[clang::always_inline]] foo(); // attempts to inline foo |
| 488 | [[clang::always_inline]] i = bar(); // attempts to inline bar |
| 489 | [[clang::always_inline]] return f(42, baz(bar())); // attempts to inline everything |
| 490 | } |
| 491 | ``` |
| 492 | |
| 493 | A declaration statement, which is a statement, is not a statement that can have an |
| 494 | attribute associated with it (the attribute applies to the declaration, not the |
| 495 | statement in that case). So this use case will not work: |
| 496 | |
| 497 | ```c |
| 498 | int example(void) { |
| 499 | [[clang::always_inline]] int i = bar(); |
| 500 | return i; |
| 501 | } |
| 502 | ``` |
| 503 | |
| 504 | This attribute does not guarantee that inline substitution actually occurs. |
| 505 | |
| 506 | \<ins>Note: applying this attribute to a coroutine at the `-O0` optimization level |
| 507 | has no effect; other optimization levels may only partially inline and result in a |
| 508 | diagnostic.\</ins> |
| 509 | |
| 510 | See also [the Microsoft Docs on Inline Functions][the microsoft docs on inline functions], [the GCC Common Function |
| 511 | Attribute docs][the gcc common function attribute docs], and [the GCC Inline docs][the gcc inline docs]. |
| 512 | |
| 513 | [the gcc common function attribute docs]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html |
| 514 | [the gcc inline docs]: https://gcc.gnu.org/onlinedocs/gcc/Inline.html |
| 515 | [the microsoft docs on inline functions]: https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp)reST" ; |
| 516 | |
| 517 | static const char AttrDoc_AnalyzerNoReturn[] = R"reST(No documentation.)reST" ; |
| 518 | |
| 519 | static const char AttrDoc_Annotate[] = R"reST(The `annotate` attribute is used to add annotations to declarations or statements, |
| 520 | typically for use by static analysis tools that are not integrated into the |
| 521 | core Clang compiler (e.g., Clang-Tidy checks or out-of-tree Clang-based tools). |
| 522 | It is a counterpart to the `annotate_type` attribute, which serves the same |
| 523 | purpose, but for types. |
| 524 | |
| 525 | The attribute takes a mandatory string literal argument specifying the |
| 526 | annotation category and an arbitrary number of optional arguments that provide |
| 527 | additional information specific to the annotation category. The optional |
| 528 | arguments must be constant expressions of arbitrary type. |
| 529 | |
| 530 | For example: |
| 531 | |
| 532 | ```c++ |
| 533 | [[clang::annotate("category1", "foo", 1)]] void func(int val [[clang::annotate("category2")]]) { |
| 534 | [[clang::annotate("category3")]] if (val) { |
| 535 | |
| 536 | } |
| 537 | } |
| 538 | ```)reST" ; |
| 539 | |
| 540 | static const char AttrDoc_AnnotateType[] = R"reST(This attribute is used to add annotations to types, typically for use by static |
| 541 | analysis tools that are not integrated into the core Clang compiler (e.g., |
| 542 | Clang-Tidy checks or out-of-tree Clang-based tools). It is a counterpart to the |
| 543 | `annotate` attribute, which serves the same purpose, but for declarations. |
| 544 | |
| 545 | The attribute takes a mandatory string literal argument specifying the |
| 546 | annotation category and an arbitrary number of optional arguments that provide |
| 547 | additional information specific to the annotation category. The optional |
| 548 | arguments must be constant expressions of arbitrary type. |
| 549 | |
| 550 | For example: |
| 551 | |
| 552 | ```c++ |
| 553 | int* [[clang::annotate_type("category1", "foo", 1)]] f(int[[clang::annotate_type("category2")]] *); |
| 554 | ``` |
| 555 | |
| 556 | The attribute does not have any effect on the semantics of the type system, |
| 557 | neither type checking rules, nor runtime semantics. In particular: |
| 558 | |
| 559 | - `std::is_same<T, T [[clang::annotate_type("foo")]]>` is true for all types |
| 560 | `T`. |
| 561 | - It is not permissible for overloaded functions or template specializations |
| 562 | to differ merely by an `annotate_type` attribute. |
| 563 | - The presence of an `annotate_type` attribute will not affect name |
| 564 | mangling.)reST" ; |
| 565 | |
| 566 | static const char AttrDoc_AnyX86Interrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt))` attribute on X86 |
| 567 | targets. This attribute may be attached to a function definition and instructs |
| 568 | the backend to generate appropriate function entry/exit code so that it can be |
| 569 | used directly as an interrupt service routine. |
| 570 | |
| 571 | Interrupt handlers have access to the stack frame pushed onto the stack by the processor, |
| 572 | and return using the `IRET` instruction. All registers in an interrupt handler are callee-saved. |
| 573 | Exception handlers also have access to the error code pushed onto the stack by the processor, |
| 574 | when applicable. |
| 575 | |
| 576 | An interrupt handler must take the following arguments: |
| 577 | |
| 578 | ```c |
| 579 | __attribute__ ((interrupt)) |
| 580 | void f (struct stack_frame *frame) { |
| 581 | ... |
| 582 | } |
| 583 | ``` |
| 584 | |
| 585 | Where `struct stack_frame` is a suitable struct matching the stack frame pushed |
| 586 | by the processor. |
| 587 | |
| 588 | An exception handler must take the following arguments: |
| 589 | |
| 590 | ```c |
| 591 | __attribute__ ((interrupt)) |
| 592 | void g (struct stack_frame *frame, unsigned long code) { |
| 593 | ... |
| 594 | } |
| 595 | ``` |
| 596 | |
| 597 | On 32-bit targets, the `code` argument should be of type `unsigned int`. |
| 598 | |
| 599 | Exception handlers should only be used when an error code is pushed by the processor. |
| 600 | Using the incorrect handler type will crash the system. |
| 601 | |
| 602 | Interrupt and exception handlers cannot be called by other functions and must have return type `void`. |
| 603 | |
| 604 | Interrupt and exception handlers should only call functions with the 'no_caller_saved_registers' |
| 605 | attribute, or should be compiled with the '-mgeneral-regs-only' flag to avoid saving unused |
| 606 | non-GPR registers.)reST" ; |
| 607 | |
| 608 | static const char AttrDoc_AnyX86NoCallerSavedRegisters[] = R"reST(Use this attribute to indicate that the specified function has no |
| 609 | caller-saved registers. That is, all registers are callee-saved except for |
| 610 | registers used for passing parameters to the function or returning parameters |
| 611 | from the function. |
| 612 | The compiler saves and restores any modified registers that were not used for |
| 613 | passing or returning arguments to the function. |
| 614 | |
| 615 | The user can call functions specified with the 'no_caller_saved_registers' |
| 616 | attribute from an interrupt handler without saving and restoring all |
| 617 | call-clobbered registers. |
| 618 | |
| 619 | Functions specified with the 'no_caller_saved_registers' attribute should only |
| 620 | call other functions with the 'no_caller_saved_registers' attribute, or should be |
| 621 | compiled with the '-mgeneral-regs-only' flag to avoid saving unused non-GPR registers. |
| 622 | |
| 623 | Note that 'no_caller_saved_registers' attribute is not a calling convention. |
| 624 | In fact, it only overrides the decision of which registers should be saved by |
| 625 | the caller, but not how the parameters are passed from the caller to the callee. |
| 626 | |
| 627 | For example: |
| 628 | |
| 629 | ```c |
| 630 | __attribute__ ((no_caller_saved_registers, fastcall)) |
| 631 | void f (int arg1, int arg2) { |
| 632 | ... |
| 633 | } |
| 634 | ``` |
| 635 | |
| 636 | In this case parameters 'arg1' and 'arg2' will be passed in registers. |
| 637 | In this case, on 32-bit x86 targets, the function 'f' will use ECX and EDX as |
| 638 | register parameters. However, it will not assume any scratch registers and |
| 639 | should save and restore any modified registers except for ECX and EDX.)reST" ; |
| 640 | |
| 641 | static const char AttrDoc_AnyX86NoCfCheck[] = R"reST(Jump Oriented Programming attacks rely on tampering with addresses used by |
| 642 | indirect call / jmp, e.g. redirect control-flow to non-programmer |
| 643 | intended bytes in the binary. |
| 644 | X86 Supports Indirect Branch Tracking (IBT) as part of Control-Flow |
| 645 | Enforcement Technology (CET). IBT instruments ENDBR instructions used to |
| 646 | specify valid targets of indirect call / jmp. |
| 647 | The `nocf_check` attribute has two roles: |
| 648 | 1\. Appertains to a function - do not add ENDBR instruction at the beginning of |
| 649 | the function. |
| 650 | 2\. Appertains to a function pointer - do not track the target function of this |
| 651 | pointer (by adding nocf_check prefix to the indirect-call instruction).)reST" ; |
| 652 | |
| 653 | static const char AttrDoc_ArcWeakrefUnavailable[] = R"reST(No documentation.)reST" ; |
| 654 | |
| 655 | static const char AttrDoc_ArgumentWithTypeTag[] = R"reST(Use `__attribute__((argument_with_type_tag(arg_kind, arg_idx, |
| 656 | type_tag_idx)))` on a function declaration to specify that the function |
| 657 | accepts a type tag that determines the type of some other argument. |
| 658 | |
| 659 | This attribute is primarily useful for checking arguments of variadic functions |
| 660 | (`pointer_with_type_tag` can be used in most non-variadic cases). |
| 661 | |
| 662 | In the attribute prototype above: |
| 663 | : - `arg_kind` is an identifier that should be used when annotating all |
| 664 | applicable type tags. |
| 665 | - `arg_idx` provides the position of a function argument. The expected type of |
| 666 | this function argument will be determined by the function argument specified |
| 667 | by `type_tag_idx`. In the code example below, "3" means that the type of the |
| 668 | function's third argument will be determined by `type_tag_idx`. |
| 669 | - `type_tag_idx` provides the position of a function argument. This function |
| 670 | argument will be a type tag. The type tag will determine the expected type of |
| 671 | the argument specified by `arg_idx`. In the code example below, "2" means |
| 672 | that the type tag associated with the function's second argument should agree |
| 673 | with the type of the argument specified by `arg_idx`. |
| 674 | |
| 675 | For example: |
| 676 | |
| 677 | ```c++ |
| 678 | int fcntl(int fd, int cmd, ...) |
| 679 | __attribute__(( argument_with_type_tag(fcntl,3,2) )); |
| 680 | // The function's second argument will be a type tag; this type tag will |
| 681 | // determine the expected type of the function's third argument. |
| 682 | ```)reST" ; |
| 683 | |
| 684 | static const char AttrDoc_ArmAgnostic[] = R"reST(The `__arm_agnostic` keyword applies to prototyped function types and |
| 685 | affects the function's calling convention for a given state S. This |
| 686 | attribute allows the user to describe a function that preserves S, without |
| 687 | requiring the function to share S with its callers and without making |
| 688 | the assumption that S exists. |
| 689 | |
| 690 | If a function has the `__arm_agnostic(S)` attribute and calls a function |
| 691 | without this attribute, then the function's object code will contain code |
| 692 | to preserve state S. Otherwise, the function's object code will be the same |
| 693 | as if it did not have the attribute. |
| 694 | |
| 695 | The attribute takes string arguments to describe state S. The supported |
| 696 | states are: |
| 697 | |
| 698 | - `"sme_za_state"` for state enabled by PSTATE.ZA, such as ZA and ZT0. |
| 699 | |
| 700 | The attribute `__arm_agnostic("sme_za_state")` cannot be used in conjunction |
| 701 | with `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` or |
| 702 | `__arm_preserves(S)` where state S describes state enabled by PSTATE.ZA, |
| 703 | such as "za" or "zt0".)reST" ; |
| 704 | |
| 705 | static const char AttrDoc_ArmBuiltinAlias[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics. |
| 706 | It allows the intrinsic functions to |
| 707 | be declared using the names defined in ACLE, and still be recognized |
| 708 | as clang builtins equivalent to the underlying name. For example, |
| 709 | `arm_mve.h` declares the function `vaddq_u32` with |
| 710 | `__attribute__((__clang_arm_mve_alias(__builtin_arm_mve_vaddq_u32)))`, |
| 711 | and similarly, one of the type-overloaded declarations of `vaddq` |
| 712 | will have the same attribute. This ensures that both functions are |
| 713 | recognized as that clang builtin, and in the latter case, the choice |
| 714 | of which builtin to identify the function as can be deferred until |
| 715 | after overload resolution. |
| 716 | |
| 717 | This attribute can only be used to set up the aliases for certain Arm |
| 718 | intrinsic functions; it is intended for use only inside `arm_*.h` |
| 719 | and is not a general mechanism for declaring arbitrary aliases for |
| 720 | clang builtin functions. |
| 721 | |
| 722 | In order to avoid duplicating the attribute definitions for similar |
| 723 | purpose for other architecture, there is a general form for the |
| 724 | attribute `clang_builtin_alias`.)reST" ; |
| 725 | |
| 726 | static const char AttrDoc_ArmIn[] = R"reST(The `__arm_in` keyword applies to prototyped function types and specifies |
| 727 | that the function shares a given state S with its caller. For `__arm_in`, the |
| 728 | function takes the state S as input and returns with the state S unchanged. |
| 729 | |
| 730 | The attribute takes string arguments to instruct the compiler which state |
| 731 | is shared. The supported states for S are: |
| 732 | |
| 733 | - `"za"` for Matrix Storage (requires SME) |
| 734 | |
| 735 | The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and |
| 736 | `__arm_preserves(S)` are all mutually exclusive for the same state S.)reST" ; |
| 737 | |
| 738 | static const char AttrDoc_ArmInOut[] = R"reST(The `__arm_inout` keyword applies to prototyped function types and specifies |
| 739 | that the function shares a given state S with its caller. For `__arm_inout`, |
| 740 | the function takes the state S as input and returns new state for S. |
| 741 | |
| 742 | The attribute takes string arguments to instruct the compiler which state |
| 743 | is shared. The supported states for S are: |
| 744 | |
| 745 | - `"za"` for Matrix Storage (requires SME) |
| 746 | |
| 747 | The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and |
| 748 | `__arm_preserves(S)` are all mutually exclusive for the same state S.)reST" ; |
| 749 | |
| 750 | static const char AttrDoc_ArmLocallyStreaming[] = R"reST(The `__arm_locally_streaming` keyword applies to function declarations |
| 751 | and specifies that all the statements in the function are executed in |
| 752 | streaming mode. This means that: |
| 753 | |
| 754 | - the function requires that the target processor implements the Scalable Matrix |
| 755 | Extension (SME). |
| 756 | - the program automatically puts the machine into streaming mode before |
| 757 | executing the statements and automatically restores the previous mode |
| 758 | afterwards. |
| 759 | |
| 760 | Clang manages PSTATE.SM automatically; it is not the source code's |
| 761 | responsibility to do this. For example, Clang will emit code to enable |
| 762 | streaming mode at the start of the function, and disable streaming mode |
| 763 | at the end of the function.)reST" ; |
| 764 | |
| 765 | static const char AttrDoc_ArmMveStrictPolymorphism[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics for the Arm |
| 766 | MVE instruction set. It is used to define the vector types used by the MVE |
| 767 | intrinsics. |
| 768 | |
| 769 | Its effect is to modify the behavior of a vector type with respect to function |
| 770 | overloading. If a candidate function for overload resolution has a parameter |
| 771 | type with this attribute, then the selection of that candidate function will be |
| 772 | disallowed if the actual argument can only be converted via a lax vector |
| 773 | conversion. The aim is to prevent spurious ambiguity in ARM MVE polymorphic |
| 774 | intrinsics. |
| 775 | |
| 776 | ```c++ |
| 777 | void overloaded(uint16x8_t vector, uint16_t scalar); |
| 778 | void overloaded(int32x4_t vector, int32_t scalar); |
| 779 | uint16x8_t myVector; |
| 780 | uint16_t myScalar; |
| 781 | |
| 782 | // myScalar is promoted to int32_t as a side effect of the addition, |
| 783 | // so if lax vector conversions are considered for myVector, then |
| 784 | // the two overloads are equally good (one argument conversion |
| 785 | // each). But if the vector has the __clang_arm_mve_strict_polymorphism |
| 786 | // attribute, only the uint16x8_t,uint16_t overload will match. |
| 787 | overloaded(myVector, myScalar + 1); |
| 788 | ``` |
| 789 | |
| 790 | However, this attribute does not prohibit lax vector conversions in contexts |
| 791 | other than overloading. |
| 792 | |
| 793 | ```c++ |
| 794 | uint16x8_t function(); |
| 795 | |
| 796 | // This is still permitted with lax vector conversion enabled, even |
| 797 | // if the vector types have __clang_arm_mve_strict_polymorphism |
| 798 | int32x4_t result = function(); |
| 799 | ```)reST" ; |
| 800 | |
| 801 | static const char AttrDoc_ArmNew[] = R"reST(The `__arm_new` keyword applies to function declarations and specifies |
| 802 | that the function will create a new scope for state S. |
| 803 | |
| 804 | The attribute takes string arguments to instruct the compiler for which state |
| 805 | to create new scope. The supported states for S are: |
| 806 | |
| 807 | - `"za"` for Matrix Storage (requires SME) |
| 808 | |
| 809 | For state `"za"`, this means that: |
| 810 | |
| 811 | - the function requires that the target processor implements the Scalable Matrix |
| 812 | Extension (SME). |
| 813 | - the function will commit any lazily saved ZA data. |
| 814 | - the function will create a new ZA context and enable PSTATE.ZA. |
| 815 | - the function will disable PSTATE.ZA (by setting it to 0) before returning. |
| 816 | |
| 817 | For `__arm_new("za")` functions Clang will set up the ZA context automatically |
| 818 | on entry to the function and disable it before returning. For example, if ZA is |
| 819 | in a dormant state Clang will generate the code to commit a lazy-save and set up |
| 820 | a new ZA state before executing user code.)reST" ; |
| 821 | |
| 822 | static const char AttrDoc_ArmOut[] = R"reST(The `__arm_out` keyword applies to prototyped function types and specifies |
| 823 | that the function shares a given state S with its caller. For `__arm_out`, |
| 824 | the function ignores the incoming state for S and returns new state for S. |
| 825 | |
| 826 | The attribute takes string arguments to instruct the compiler which state |
| 827 | is shared. The supported states for S are: |
| 828 | |
| 829 | - `"za"` for Matrix Storage (requires SME) |
| 830 | |
| 831 | The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and |
| 832 | `__arm_preserves(S)` are all mutually exclusive for the same state S.)reST" ; |
| 833 | |
| 834 | static const char AttrDoc_ArmPreserves[] = R"reST(The `__arm_preserves` keyword applies to prototyped function types and |
| 835 | specifies that the function does not read a given state S and returns |
| 836 | with state S unchanged. |
| 837 | |
| 838 | The attribute takes string arguments to instruct the compiler which state |
| 839 | is shared. The supported states for S are: |
| 840 | |
| 841 | - `"za"` for Matrix Storage (requires SME) |
| 842 | |
| 843 | The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and |
| 844 | `__arm_preserves(S)` are all mutually exclusive for the same state S.)reST" ; |
| 845 | |
| 846 | static const char AttrDoc_ArmStreaming[] = R"reST(The `__arm_streaming` keyword applies to prototyped function types and specifies |
| 847 | that the function has a "streaming interface". This means that: |
| 848 | |
| 849 | - the function requires that the processor implements the Scalable Matrix |
| 850 | Extension (SME). |
| 851 | - the function must be entered in streaming mode (that is, with PSTATE.SM |
| 852 | set to 1) |
| 853 | - the function must return in streaming mode |
| 854 | |
| 855 | Clang manages PSTATE.SM automatically; it is not the source code's |
| 856 | responsibility to do this. For example, if a non-streaming |
| 857 | function calls an `__arm_streaming` function, Clang generates code |
| 858 | that switches into streaming mode before calling the function and |
| 859 | switches back to non-streaming mode on return.)reST" ; |
| 860 | |
| 861 | static const char AttrDoc_ArmStreamingCompatible[] = R"reST(The `__arm_streaming_compatible` keyword applies to prototyped function types and |
| 862 | specifies that the function has a "streaming compatible interface". This |
| 863 | means that: |
| 864 | |
| 865 | - the function may be entered in either non-streaming mode (PSTATE.SM=0) or |
| 866 | in streaming mode (PSTATE.SM=1). |
| 867 | - the function must return in the same mode as it was entered. |
| 868 | - the code executed in the function is compatible with either mode. |
| 869 | |
| 870 | Clang manages PSTATE.SM automatically; it is not the source code's |
| 871 | responsibility to do this. Clang will ensure that the generated code in |
| 872 | streaming-compatible functions is valid in either mode (PSTATE.SM=0 or |
| 873 | PSTATE.SM=1). For example, if an `__arm_streaming_compatible` function calls a |
| 874 | non-streaming function, Clang generates code to temporarily switch out of streaming |
| 875 | mode before calling the function and switch back to streaming-mode on return if |
| 876 | `PSTATE.SM` is `1` on entry of the caller. If `PSTATE.SM` is `0` on |
| 877 | entry to the `__arm_streaming_compatible` function, the call will be executed |
| 878 | without changing modes.)reST" ; |
| 879 | |
| 880 | static const char AttrDoc_Artificial[] = R"reST(The `artificial` attribute can be applied to an inline function. If such a |
| 881 | function is inlined, the attribute indicates that debuggers should associate |
| 882 | the resulting instructions with the call site, rather than with the |
| 883 | corresponding line within the inlined callee.)reST" ; |
| 884 | |
| 885 | static const char AttrDoc_AsmLabel[] = R"reST(This attribute can be used on a function or variable to specify its symbol name. |
| 886 | |
| 887 | On some targets, all C symbols are prefixed by default with a single character, |
| 888 | typically `_`. This was done historically to distinguish them from symbols |
| 889 | used by other languages. (This prefix is also added to the standard Itanium |
| 890 | C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true |
| 891 | symbol name for a C++ variable declared as `int cppvar;` would be |
| 892 | `__Z6cppvar`; note the two underscores.) This prefix is *not* added to the |
| 893 | symbol names specified by the `__asm` attribute; programmers wishing to match |
| 894 | a C symbol name must compensate for this. |
| 895 | |
| 896 | For example, consider the following C code: |
| 897 | |
| 898 | ```c |
| 899 | int var1 __asm("altvar") = 1; // "altvar" in symbol table. |
| 900 | int var2 = 1; // "_var2" in symbol table. |
| 901 | |
| 902 | void func1(void) __asm("altfunc"); |
| 903 | void func1(void) {} // "altfunc" in symbol table. |
| 904 | void func2(void) {} // "_func2" in symbol table. |
| 905 | ``` |
| 906 | |
| 907 | Clang's implementation of this attribute is compatible with GCC's, [documented here](https://gcc.gnu.org/onlinedocs/gcc/Asm-Labels.html). |
| 908 | |
| 909 | While it is possible to use this attribute to name a special symbol used |
| 910 | internally by the compiler, such as an LLVM intrinsic, this is neither |
| 911 | recommended nor supported and may cause the compiler to crash or miscompile. |
| 912 | Users who wish to gain access to intrinsic behavior are strongly encouraged to |
| 913 | request new builtin functions.)reST" ; |
| 914 | |
| 915 | static const char AttrDoc_AssertCapability[] = R"reST(Marks a function that dynamically tests whether a capability is held, and halts |
| 916 | the program if it is not held.)reST" ; |
| 917 | |
| 918 | static const char AttrDoc_AssumeAligned[] = R"reST(Use `__attribute__((assume_aligned(<alignment>[,<offset>]))` on a function |
| 919 | declaration to specify that the return value of the function (which must be a |
| 920 | pointer type) has the specified offset, in bytes, from an address with the |
| 921 | specified alignment. The offset is taken to be zero if omitted. |
| 922 | |
| 923 | ```c++ |
| 924 | // The returned pointer value has 32-byte alignment. |
| 925 | void *a() __attribute__((assume_aligned (32))); |
| 926 | |
| 927 | // The returned pointer value is 4 bytes greater than an address having |
| 928 | // 32-byte alignment. |
| 929 | void *b() __attribute__((assume_aligned (32, 4))); |
| 930 | ``` |
| 931 | |
| 932 | Note that this attribute provides information to the compiler regarding a |
| 933 | condition that the code already ensures is true. It does not cause the compiler |
| 934 | to enforce the provided alignment assumption.)reST" ; |
| 935 | |
| 936 | static const char AttrDoc_Atomic[] = R"reST(The `atomic` attribute can be applied to *compound statements* to override or |
| 937 | further specify the default atomic code-generation behavior, especially on |
| 938 | targets such as AMDGPU. You can annotate compound statements with options |
| 939 | to modify how atomic instructions inside that statement are emitted at the IR |
| 940 | level. |
| 941 | |
| 942 | For details, see the documentation for |
| 943 | {ref}`@atomic <langext-atomic-code-generation>`)reST" ; |
| 944 | |
| 945 | static const char AttrDoc_Availability[] = R"reST(The `availability` attribute can be placed on declarations to describe the |
| 946 | lifecycle of that declaration relative to operating system versions. Consider |
| 947 | the function declaration for a hypothetical function `f`: |
| 948 | |
| 949 | ```c++ |
| 950 | void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7))); |
| 951 | ``` |
| 952 | |
| 953 | The availability attribute states that `f` was introduced in macOS 10.4, |
| 954 | deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information |
| 955 | is used by Clang to determine when it is safe to use `f`: for example, if |
| 956 | Clang is instructed to compile code for macOS 10.5, a call to `f()` |
| 957 | succeeds. If Clang is instructed to compile code for macOS 10.6, the call |
| 958 | succeeds but Clang emits a warning specifying that the function is deprecated. |
| 959 | Finally, if Clang is instructed to compile code for macOS 10.7, the call |
| 960 | fails because `f()` is no longer available. |
| 961 | |
| 962 | Clang is instructed to compile code for a minimum deployment version using |
| 963 | the `-target` or `-mtargetos` command line arguments. For example, |
| 964 | macOS 10.7 would be specified as `-target x86_64-apple-macos10.7` or |
| 965 | `-mtargetos=macos10.7`. Variants like Mac Catalyst are specified as |
| 966 | `-target arm64-apple-ios15.0-macabi` or `-mtargetos=ios15.0-macabi` |
| 967 | |
| 968 | The availability attribute is a comma-separated list starting with the |
| 969 | platform name and then including clauses specifying important milestones in the |
| 970 | declaration's lifetime (in any order) along with additional information. Those |
| 971 | clauses can be: |
| 972 | |
| 973 | introduced=*version* |
| 974 | |
| 975 | : The first version in which this declaration was introduced. |
| 976 | |
| 977 | deprecated=*version* |
| 978 | |
| 979 | : The first version in which this declaration was deprecated, meaning that |
| 980 | users should migrate away from this API. |
| 981 | |
| 982 | obsoleted=*version* |
| 983 | |
| 984 | : The first version in which this declaration was obsoleted, meaning that it |
| 985 | was removed completely and can no longer be used. |
| 986 | |
| 987 | unavailable |
| 988 | |
| 989 | : This declaration is never available on this platform. |
| 990 | |
| 991 | message=*string-literal* |
| 992 | |
| 993 | : Additional message text that Clang will provide when emitting a warning or |
| 994 | error about use of a deprecated or obsoleted declaration. Useful to direct |
| 995 | users to replacement APIs. |
| 996 | |
| 997 | replacement=*string-literal* |
| 998 | |
| 999 | : Additional message text that Clang will use to provide Fix-It when emitting |
| 1000 | a warning about use of a deprecated declaration. The Fix-It will replace |
| 1001 | the deprecated declaration with the new declaration specified. |
| 1002 | |
| 1003 | environment=*identifier* |
| 1004 | |
| 1005 | : Target environment in which this declaration is available. If present, |
| 1006 | the availability attribute applies only to targets with the same platform |
| 1007 | and environment. The parameter is currently supported only in HLSL. |
| 1008 | |
| 1009 | Multiple availability attributes can be placed on a declaration, which may |
| 1010 | correspond to different platforms. For most platforms, the availability |
| 1011 | attribute with the platform corresponding to the target platform will be used; |
| 1012 | any others will be ignored. However, the availability for `watchOS` and |
| 1013 | `tvOS` can be implicitly inferred from an `iOS` availability attribute. |
| 1014 | Any explicit availability attributes for those platforms are still preferred over |
| 1015 | the implicitly inferred availability attributes. If no availability attribute |
| 1016 | specifies availability for the current target platform, the availability |
| 1017 | attributes are ignored. Supported platforms are: |
| 1018 | |
| 1019 | `iOS` |
| 1020 | `macOS` |
| 1021 | `tvOS` |
| 1022 | `watchOS` |
| 1023 | `iOSApplicationExtension` |
| 1024 | `macOSApplicationExtension` |
| 1025 | `tvOSApplicationExtension` |
| 1026 | `watchOSApplicationExtension` |
| 1027 | `macCatalyst` |
| 1028 | `macCatalystApplicationExtension` |
| 1029 | `visionOS` |
| 1030 | `visionOSApplicationExtension` |
| 1031 | `driverkit` |
| 1032 | `anyAppleOS` |
| 1033 | `swift` |
| 1034 | `android` |
| 1035 | `fuchsia` |
| 1036 | `ohos` |
| 1037 | `zos` |
| 1038 | `ShaderModel` |
| 1039 | |
| 1040 | Some platforms have alias names: |
| 1041 | |
| 1042 | `ios` |
| 1043 | `macos` |
| 1044 | `macosx (deprecated)` |
| 1045 | `tvos` |
| 1046 | `watchos` |
| 1047 | `ios_app_extension` |
| 1048 | `macos_app_extension` |
| 1049 | `macosx_app_extension (deprecated)` |
| 1050 | `tvos_app_extension` |
| 1051 | `watchos_app_extension` |
| 1052 | `maccatalyst` |
| 1053 | `maccatalyst_app_extension` |
| 1054 | `visionos` |
| 1055 | `visionos_app_extension` |
| 1056 | `anyappleos` |
| 1057 | `shadermodel` |
| 1058 | |
| 1059 | Supported environment names for the ShaderModel platform: |
| 1060 | |
| 1061 | `pixel` |
| 1062 | `vertex` |
| 1063 | `geometry` |
| 1064 | `hull` |
| 1065 | `domain` |
| 1066 | `compute` |
| 1067 | `raygeneration` |
| 1068 | `intersection` |
| 1069 | `anyhit` |
| 1070 | `closesthit` |
| 1071 | `miss` |
| 1072 | `callable` |
| 1073 | `mesh` |
| 1074 | `amplification` |
| 1075 | `library` |
| 1076 | |
| 1077 | The special platform `anyAppleOS` (alias: `anyappleos`) is a shorthand that |
| 1078 | applies the availability attribute to all Apple Darwin platforms. An explicit |
| 1079 | platform-specific availability attribute takes precedence over an `anyAppleOS` |
| 1080 | attribute for that platform. Versions specified with `anyAppleOS` must be at |
| 1081 | least 26.0, which is the first OS release where all supported Apple platforms |
| 1082 | share a unified version number. |
| 1083 | |
| 1084 | A declaration can typically be used even when deploying back to a platform |
| 1085 | version prior to when the declaration was introduced. When this happens, the |
| 1086 | declaration is [weakly linked](https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html), |
| 1087 | as if the `weak_import` attribute were added to the declaration. A |
| 1088 | weakly-linked declaration may or may not be present a run-time, and a program |
| 1089 | can determine whether the declaration is present by checking whether the |
| 1090 | address of that declaration is non-NULL. |
| 1091 | |
| 1092 | The flag `strict` disallows using API when deploying back to a |
| 1093 | platform version prior to when the declaration was introduced. An |
| 1094 | attempt to use such API before its introduction causes a hard error. |
| 1095 | Weakly-linking is almost always a better API choice, since it allows |
| 1096 | users to query availability at runtime. |
| 1097 | |
| 1098 | If there are multiple declarations of the same entity, the availability |
| 1099 | attributes must either match on a per-platform basis or later |
| 1100 | declarations must not have availability attributes for that |
| 1101 | platform. For example: |
| 1102 | |
| 1103 | ```c |
| 1104 | void g(void) __attribute__((availability(macos,introduced=10.4))); |
| 1105 | void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches |
| 1106 | void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform |
| 1107 | void g(void); // okay, inherits both macos and ios availability from above. |
| 1108 | void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch |
| 1109 | ``` |
| 1110 | |
| 1111 | When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,: |
| 1112 | |
| 1113 | ```objc |
| 1114 | @interface A |
| 1115 | - (id)method __attribute__((availability(macos,introduced=10.4))); |
| 1116 | - (id)method2 __attribute__((availability(macos,introduced=10.4))); |
| 1117 | @end |
| 1118 | |
| 1119 | @interface B : A |
| 1120 | - (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later |
| 1121 | - (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4 |
| 1122 | @end |
| 1123 | ``` |
| 1124 | |
| 1125 | Starting with the macOS 10.12 SDK, the `API_AVAILABLE` macro from |
| 1126 | `<os/availability.h>` can simplify the spelling: |
| 1127 | |
| 1128 | ```objc |
| 1129 | @interface A |
| 1130 | - (id)method API_AVAILABLE(macos(10.11))); |
| 1131 | - (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0)); |
| 1132 | @end |
| 1133 | ``` |
| 1134 | |
| 1135 | Availability attributes can also be applied using a `#pragma clang attribute`. |
| 1136 | Any explicit availability attribute whose platform corresponds to the target |
| 1137 | platform is applied to a declaration regardless of the availability attributes |
| 1138 | specified in the pragma. For example, in the code below, |
| 1139 | `hasExplicitAvailabilityAttribute` will use the `macOS` availability |
| 1140 | attribute that is specified with the declaration, whereas |
| 1141 | `getsThePragmaAvailabilityAttribute` will use the `macOS` availability |
| 1142 | attribute that is applied by the pragma. |
| 1143 | |
| 1144 | ```c |
| 1145 | #pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function) |
| 1146 | void getsThePragmaAvailabilityAttribute(void); |
| 1147 | void hasExplicitAvailabilityAttribute(void) __attribute__((availability(macos,introduced=10.4))); |
| 1148 | #pragma clang attribute pop |
| 1149 | ``` |
| 1150 | |
| 1151 | For platforms like `watchOS` and `tvOS`, whose availability attributes can |
| 1152 | be implicitly inferred from an `iOS` availability attribute, the logic is |
| 1153 | slightly more complex. The explicit and the pragma-applied availability |
| 1154 | attributes whose platform corresponds to the target platform are applied as |
| 1155 | described in the previous paragraph. However, the implicitly inferred attributes |
| 1156 | are applied to a declaration only when there is no explicit or pragma-applied |
| 1157 | availability attribute whose platform corresponds to the target platform. For |
| 1158 | example, the function below will receive the `tvOS` availability from the |
| 1159 | pragma rather than using the inferred `iOS` availability from the declaration: |
| 1160 | |
| 1161 | ```c |
| 1162 | #pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function) |
| 1163 | void getsThePragmaTVOSAvailabilityAttribute(void) __attribute__((availability(iOS,introduced=11.0))); |
| 1164 | #pragma clang attribute pop |
| 1165 | ``` |
| 1166 | |
| 1167 | The compiler is also able to apply implicitly inferred attributes from a pragma |
| 1168 | as well. For example, when targeting `tvOS`, the function below will receive |
| 1169 | a `tvOS` availability attribute that is implicitly inferred from the `iOS` |
| 1170 | availability attribute applied by the pragma: |
| 1171 | |
| 1172 | ```c |
| 1173 | #pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function) |
| 1174 | void infersTVOSAvailabilityFromPragma(void); |
| 1175 | #pragma clang attribute pop |
| 1176 | ``` |
| 1177 | |
| 1178 | The implicit attributes that are inferred from explicitly specified attributes |
| 1179 | whose platform corresponds to the target platform are applied to the declaration |
| 1180 | even if there is an availability attribute that can be inferred from a pragma. |
| 1181 | For example, the function below will receive the `tvOS, introduced=11.0` |
| 1182 | availability that is inferred from the attribute on the declaration rather than |
| 1183 | inferring availability from the pragma: |
| 1184 | |
| 1185 | ```c |
| 1186 | #pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function) |
| 1187 | void infersTVOSAvailabilityFromAttributeNextToDeclaration(void) |
| 1188 | __attribute__((availability(iOS,introduced=11.0))); |
| 1189 | #pragma clang attribute pop |
| 1190 | ``` |
| 1191 | |
| 1192 | Also see the documentation for |
| 1193 | {ref}`@available <langext-objective-c-available>`)reST" ; |
| 1194 | |
| 1195 | static const char AttrDoc_AvailableOnlyInDefaultEvalMethod[] = R"reST(No documentation.)reST" ; |
| 1196 | |
| 1197 | static const char AttrDoc_BPFFastCall[] = R"reST(Functions annotated with this attribute are likely to be inlined by BPF JIT. |
| 1198 | It is assumed that inlined implementation uses less caller saved registers, |
| 1199 | than a regular function. |
| 1200 | Specifically, the following registers are likely to be preserved: |
| 1201 | - `R0` if function return value is `void`; |
| 1202 | - `R2-R5` if function takes 1 argument; |
| 1203 | - `R3-R5` if function takes 2 arguments; |
| 1204 | - `R4-R5` if function takes 3 arguments; |
| 1205 | - `R5` if function takes 4 arguments; |
| 1206 | |
| 1207 | For such functions Clang generates code pattern that allows BPF JIT |
| 1208 | to recognize and remove unnecessary spills and fills of the preserved |
| 1209 | registers.)reST" ; |
| 1210 | |
| 1211 | static const char AttrDoc_BPFPreserveAccessIndex[] = R"reST(Clang supports the `__attribute__((preserve_access_index))` |
| 1212 | attribute for the BPF target. This attribute may be attached to a |
| 1213 | struct or union declaration, where if -g is specified, it enables |
| 1214 | preserving struct or union member access debuginfo indices of this |
| 1215 | struct or union, similar to clang `__builtin_preserve_access_index()`.)reST" ; |
| 1216 | |
| 1217 | static const char AttrDoc_BPFPreserveStaticOffset[] = R"reST(Clang supports the `__attribute__((preserve_static_offset))` |
| 1218 | attribute for the BPF target. This attribute may be attached to a |
| 1219 | struct or union declaration. Reading or writing fields of types having |
| 1220 | such annotation is guaranteed to generate LDX/ST/STX instruction with |
| 1221 | offset corresponding to the field. |
| 1222 | |
| 1223 | For example: |
| 1224 | |
| 1225 | ```c |
| 1226 | struct foo { |
| 1227 | int a; |
| 1228 | int b; |
| 1229 | }; |
| 1230 | |
| 1231 | struct bar { |
| 1232 | int a; |
| 1233 | struct foo b; |
| 1234 | } __attribute__((preserve_static_offset)); |
| 1235 | |
| 1236 | void buz(struct bar *g) { |
| 1237 | g->b.a = 42; |
| 1238 | } |
| 1239 | ``` |
| 1240 | |
| 1241 | The assignment to `g`'s field would produce an ST instruction with |
| 1242 | offset 8: `*(u32)(r1 + 8) = 42;`. |
| 1243 | |
| 1244 | Without this attribute generated instructions might be different, |
| 1245 | depending on optimizations behavior. E.g. the example above could be |
| 1246 | rewritten as `r1 += 8; *(u32)(r1 + 0) = 42;`.)reST" ; |
| 1247 | |
| 1248 | static const char AttrDoc_BTFDeclTag[] = R"reST(Clang supports the `__attribute__((btf_decl_tag("ARGUMENT")))` attribute for |
| 1249 | all targets. This attribute may be attached to a struct/union, struct/union |
| 1250 | field, function, function parameter, variable or typedef declaration. If -g is |
| 1251 | specified, the `ARGUMENT` info will be preserved in IR and be emitted to |
| 1252 | dwarf. For BPF targets, the `ARGUMENT` info will be emitted to .BTF ELF |
| 1253 | section too.)reST" ; |
| 1254 | |
| 1255 | static const char AttrDoc_BTFTypeTag[] = R"reST(Clang supports the `__attribute__((btf_type_tag("ARGUMENT")))` attribute for |
| 1256 | all targets. It only has effect when `-g` is specified on the command line. |
| 1257 | |
| 1258 | The attribute can be applied to a pointer type, in which case the tag is |
| 1259 | associated with the pointee type, e.g.: |
| 1260 | |
| 1261 | ```c |
| 1262 | int __attribute__((btf_type_tag("tag"))) *p; |
| 1263 | ``` |
| 1264 | |
| 1265 | It can also be applied to the underlying type of a typedef, in which case the |
| 1266 | tag follows the typedef down to its base type, e.g.: |
| 1267 | |
| 1268 | ```c |
| 1269 | typedef struct foo __attribute__((btf_type_tag("tag"))) foo_t; |
| 1270 | ``` |
| 1271 | |
| 1272 | The following is the corresponding btf: |
| 1273 | |
| 1274 | ``` |
| 1275 | ... |
| 1276 | [2] TYPE_TAG 'tag' type_id=4 |
| 1277 | [3] TYPEDEF 'foo_t' type_id=2 |
| 1278 | [4] STRUCT 'foo' size=4 vlen=1 |
| 1279 | 'c' type_id=5 bits_offset=0 |
| 1280 | [5] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED |
| 1281 | ... |
| 1282 | ``` |
| 1283 | |
| 1284 | The attribute is currently silently ignored in any other position (note: this |
| 1285 | scenario may be diagnosed in the future). |
| 1286 | |
| 1287 | The `ARGUMENT` string will be preserved in IR and emitted to DWARF for the |
| 1288 | types used in variable declarations, function declarations, or typedef |
| 1289 | declarations. |
| 1290 | |
| 1291 | For BPF targets, the `ARGUMENT` string will also be emitted to .BTF ELF |
| 1292 | section.)reST" ; |
| 1293 | |
| 1294 | static const char AttrDoc_Blocking[] = R"reST(Declares that a function potentially blocks, and prevents any potential inference of `nonblocking` |
| 1295 | by the compiler.)reST" ; |
| 1296 | |
| 1297 | static const char AttrDoc_Blocks[] = R"reST(No documentation.)reST" ; |
| 1298 | |
| 1299 | static const char AttrDoc_Builtin[] = R"reST()reST" ; |
| 1300 | |
| 1301 | static const char AttrDoc_BuiltinAlias[] = R"reST(This attribute is used in the implementation of the C intrinsics. |
| 1302 | It allows the C intrinsic functions to be declared using the names defined |
| 1303 | in target builtins, and still be recognized as clang builtins equivalent to the |
| 1304 | underlying name. For example, `riscv_vector.h` declares the function `vadd` |
| 1305 | with `__attribute__((clang_builtin_alias(__builtin_rvv_vadd_vv_i8m1)))`. |
| 1306 | This ensures that both functions are recognized as that clang builtin, |
| 1307 | and in the latter case, the choice of which builtin to identify the |
| 1308 | function as can be deferred until after overload resolution. |
| 1309 | |
| 1310 | This attribute can only be used to set up the aliases for certain ARM/RISC-V |
| 1311 | C intrinsic functions; it is intended for use only inside `arm_*.h` and |
| 1312 | `riscv_*.h` and is not a general mechanism for declaring arbitrary aliases |
| 1313 | for clang builtin functions.)reST" ; |
| 1314 | |
| 1315 | static const char AttrDoc_C11NoReturn[] = R"reST(A function declared as `_Noreturn` shall not return to its caller. The |
| 1316 | compiler will generate a diagnostic for a function declared as `_Noreturn` |
| 1317 | that appears to be capable of returning to its caller. Despite being a type |
| 1318 | specifier, the `_Noreturn` attribute cannot be specified on a function |
| 1319 | pointer type.)reST" ; |
| 1320 | |
| 1321 | static const char AttrDoc_CDecl[] = R"reST(No documentation.)reST" ; |
| 1322 | |
| 1323 | static const char AttrDoc_CFAuditedTransfer[] = R"reST(No documentation.)reST" ; |
| 1324 | |
| 1325 | static const char AttrDoc_CFConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation |
| 1326 | (Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming |
| 1327 | convention (e.g. functions starting with "get" are assumed to return at |
| 1328 | `+0`). |
| 1329 | |
| 1330 | It can be overridden using a family of the following attributes. In |
| 1331 | Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to |
| 1332 | a function communicates that the object is returned at `+1`, and the caller |
| 1333 | is responsible for freeing it. |
| 1334 | Similarly, the annotation `__attribute__((ns_returns_not_retained))` |
| 1335 | specifies that the object is returned at `+0` and the ownership remains with |
| 1336 | the callee. |
| 1337 | The annotation `__attribute__((ns_consumes_self))` specifies that |
| 1338 | the Objective-C method call consumes the reference to `self`, e.g. by |
| 1339 | attaching it to a supplied parameter. |
| 1340 | Additionally, parameters can have an annotation |
| 1341 | `__attribute__((ns_consumed))`, which specifies that passing an owned object |
| 1342 | as that parameter effectively transfers the ownership, and the caller is no |
| 1343 | longer responsible for it. |
| 1344 | These attributes affect code generation when interacting with ARC code, and |
| 1345 | they are used by the Clang Static Analyzer. |
| 1346 | |
| 1347 | In C programs using CoreFoundation, a similar set of attributes: |
| 1348 | `__attribute__((cf_returns_not_retained))`, |
| 1349 | `__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))` |
| 1350 | have the same respective semantics when applied to CoreFoundation objects. |
| 1351 | These attributes affect code generation when interacting with ARC code, and |
| 1352 | they are used by the Clang Static Analyzer. |
| 1353 | |
| 1354 | Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), |
| 1355 | the same attribute family is present: |
| 1356 | `__attribute__((os_returns_not_retained))`, |
| 1357 | `__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`, |
| 1358 | with the same respective semantics. |
| 1359 | Similar to `__attribute__((ns_consumes_self))`, |
| 1360 | `__attribute__((os_consumes_this))` specifies that the method call consumes |
| 1361 | the reference to "this" (e.g., when attaching it to a different object supplied |
| 1362 | as a parameter). |
| 1363 | Out parameters (parameters the function is meant to write into, |
| 1364 | either via pointers-to-pointers or references-to-pointers) |
| 1365 | may be annotated with `__attribute__((os_returns_retained))` |
| 1366 | or `__attribute__((os_returns_not_retained))` which specifies that the object |
| 1367 | written into the out parameter should (or respectively should not) be released |
| 1368 | after use. |
| 1369 | Since often out parameters may or may not be written depending on the exit |
| 1370 | code of the function, |
| 1371 | annotations `__attribute__((os_returns_retained_on_zero))` |
| 1372 | and `__attribute__((os_returns_retained_on_non_zero))` specify that |
| 1373 | an out parameter at `+1` is written if and only if the function returns a zero |
| 1374 | (respectively non-zero) error code. |
| 1375 | Observe that return-code-dependent out parameter annotations are only |
| 1376 | available for retained out parameters, as non-retained object do not have to be |
| 1377 | released by the callee. |
| 1378 | These attributes are only used by the Clang Static Analyzer. |
| 1379 | |
| 1380 | The family of attributes `X_returns_X_retained` can be added to functions, |
| 1381 | C++ methods, and Objective-C methods and properties. |
| 1382 | Attributes `X_consumed` can be added to parameters of methods, functions, |
| 1383 | and Objective-C methods.)reST" ; |
| 1384 | |
| 1385 | static const char AttrDoc_CFGuard[] = R"reST(Code can indicate CFG checks are not wanted with the `__declspec(guard(nocf))` |
| 1386 | attribute. This directs the compiler to not insert any CFG checks for the entire |
| 1387 | function. This approach is typically used only sparingly in specific situations |
| 1388 | where the programmer has manually inserted "CFG-equivalent" protection. The |
| 1389 | programmer knows that they are calling through some read-only function table |
| 1390 | whose address is obtained through read-only memory references and for which the |
| 1391 | index is masked to the function table limit. This approach may also be applied |
| 1392 | to small wrapper functions that are not inlined and that do nothing more than |
| 1393 | make a call through a function pointer. Since incorrect usage of this directive |
| 1394 | can compromise the security of CFG, the programmer must be very careful using |
| 1395 | the directive. Typically, this usage is limited to very small functions that |
| 1396 | only call one function. |
| 1397 | |
| 1398 | `Control Flow Guard documentation <https://docs.microsoft.com/en-us/windows/win32/secbp/pe-metadata>`)reST" ; |
| 1399 | |
| 1400 | static const char AttrDoc_CFICanonicalJumpTable[] = R"reST(Use `__attribute__((cfi_canonical_jump_table))` on a function declaration to |
| 1401 | make the function's CFI jump table canonical. See {ref}`the CFI documentation |
| 1402 | <cfi-canonical-jump-tables>` for more details.)reST" ; |
| 1403 | |
| 1404 | static const char AttrDoc_CFISalt[] = R"reST(The `cfi_salt` attribute specifies a string literal that is used as a salt |
| 1405 | for Control-Flow Integrity (CFI) checks to distinguish between functions with |
| 1406 | the same type signature. This attribute can be applied to function declarations, |
| 1407 | function definitions, and function pointer typedefs. |
| 1408 | |
| 1409 | The attribute prevents function pointers from being replaced with pointers to |
| 1410 | functions that have a compatible type, which can be a CFI bypass vector. |
| 1411 | |
| 1412 | **Syntax:** |
| 1413 | |
| 1414 | - GNU-style: `__attribute__((cfi_salt("<salt_string>")))` |
| 1415 | - C++11-style: `[[clang::cfi_salt("<salt_string>")]]` |
| 1416 | |
| 1417 | **Usage:** |
| 1418 | |
| 1419 | The attribute takes a single string literal argument that serves as the salt. |
| 1420 | Functions or function types with different salt values will have different CFI |
| 1421 | hashes, even if they have identical type signatures. |
| 1422 | |
| 1423 | **Motivation:** |
| 1424 | |
| 1425 | In large codebases like the Linux kernel, there are often hundreds of functions |
| 1426 | with identical type signatures that are called indirectly: |
| 1427 | |
| 1428 | ``` |
| 1429 | 1662 functions with void (*)(void) |
| 1430 | 1179 functions with int (*)(void) |
| 1431 | ... |
| 1432 | ``` |
| 1433 | |
| 1434 | By salting the CFI hashes, you can make CFI more robust by ensuring that |
| 1435 | functions intended for different purposes have distinct CFI identities. |
| 1436 | |
| 1437 | **Type Compatibility:** |
| 1438 | |
| 1439 | - Functions with different salt values are considered to have incompatible types |
| 1440 | - Function pointers with different salt values cannot be assigned to each other |
| 1441 | - All declarations of the same function must use the same salt value |
| 1442 | |
| 1443 | **Example:** |
| 1444 | |
| 1445 | ```c |
| 1446 | // Header file - define convenience macros |
| 1447 | #define __cfi_salt(s) __attribute__((cfi_salt(s))) |
| 1448 | |
| 1449 | // Typedef for regular function pointers |
| 1450 | typedef int (*fptr_t)(void); |
| 1451 | |
| 1452 | // Typedef for salted function pointers |
| 1453 | typedef int (*fptr_salted_t)(void) __cfi_salt("pepper"); |
| 1454 | |
| 1455 | struct widget_ops { |
| 1456 | fptr_t init; // Regular CFI |
| 1457 | fptr_salted_t exec; // Salted CFI |
| 1458 | fptr_t cleanup; // Regular CFI |
| 1459 | }; |
| 1460 | |
| 1461 | // Function implementations |
| 1462 | static int widget_init(void) { return 0; } |
| 1463 | static int widget_exec(void) __cfi_salt("pepper") { return 1; } |
| 1464 | static int widget_cleanup(void) { return 0; } |
| 1465 | |
| 1466 | static struct widget_ops ops = { |
| 1467 | .init = widget_init, // OK - compatible types |
| 1468 | .exec = widget_exec, // OK - both use "pepper" salt |
| 1469 | .cleanup = widget_cleanup // OK - compatible types |
| 1470 | }; |
| 1471 | |
| 1472 | // Using C++11 attribute syntax |
| 1473 | void secure_callback(void) [[clang::cfi_salt("secure")]]; |
| 1474 | |
| 1475 | // This would cause a compilation error: |
| 1476 | // fptr_t bad_ptr = widget_exec; // Error: incompatible types |
| 1477 | ``` |
| 1478 | |
| 1479 | **Notes:** |
| 1480 | |
| 1481 | - The salt string can contain non-NULL ASCII characters, including spaces and |
| 1482 | quotes |
| 1483 | - This attribute only applies to function types; using it on non-function |
| 1484 | types will generate a warning |
| 1485 | - All declarations and definitions of the same function must use identical |
| 1486 | salt values |
| 1487 | - The attribute affects type compatibility during compilation and CFI hash |
| 1488 | generation during code generation)reST" ; |
| 1489 | |
| 1490 | static const char AttrDoc_CFIUncheckedCallee[] = R"reST(`cfi_unchecked_callee` is a function type attribute which prevents the |
| 1491 | compiler from instrumenting |
| 1492 | {doc}`Control Flow Integrity <ControlFlowIntegrity>` checks on indirect |
| 1493 | function calls. This also includes control flow checks added by |
| 1494 | `-fsanitize=function`; see {ref}`Available checks <ubsan-checks>`. |
| 1495 | Specifically, the attribute has the following semantics: |
| 1496 | |
| 1497 | 1. Indirect calls to a function type with this attribute will not be instrumented with CFI. That is, |
| 1498 | the indirect call will not be checked. Note that this only changes the behavior for indirect calls |
| 1499 | on pointers to function types having this attribute. It does not prevent all indirect function calls |
| 1500 | for a given type from being checked. |
| 1501 | 2. All direct references to a function whose type has this attribute will always reference the |
| 1502 | function definition rather than an entry in the CFI jump table. |
| 1503 | 3. When a pointer to a function with this attribute is implicitly cast to a pointer to a function |
| 1504 | without this attribute, the compiler will give a warning saying this attribute is discarded. This |
| 1505 | warning can be silenced with an explicit cast. Note an explicit cast just disables the warning, so |
| 1506 | direct references to a function with a `cfi_unchecked_callee` attribute will still reference the |
| 1507 | function definition rather than the CFI jump table. |
| 1508 | |
| 1509 | ```c |
| 1510 | #define CFI_UNCHECKED_CALLEE __attribute__((cfi_unchecked_callee)) |
| 1511 | |
| 1512 | void no_cfi() CFI_UNCHECKED_CALLEE {} |
| 1513 | |
| 1514 | void (*with_cfi)() = no_cfi; // warning: implicit conversion discards `cfi_unchecked_callee` attribute. |
| 1515 | // `with_cfi` also points to the actual definition of `no_cfi` rather than |
| 1516 | // its jump table entry. |
| 1517 | |
| 1518 | void invoke(void (CFI_UNCHECKED_CALLEE *func)()) { |
| 1519 | func(); // CFI will not instrument this indirect call. |
| 1520 | |
| 1521 | void (*func2)() = func; // warning: implicit conversion discards `cfi_unchecked_callee` attribute. |
| 1522 | |
| 1523 | func2(); // CFI will instrument this indirect call. Users should be careful however because if this |
| 1524 | // references a function with type `cfi_unchecked_callee`, then the CFI check may incorrectly |
| 1525 | // fail because the reference will be to the function definition rather than the CFI jump |
| 1526 | // table entry. |
| 1527 | } |
| 1528 | ``` |
| 1529 | |
| 1530 | This attribute can only be applied on functions or member functions. This attribute can be a good |
| 1531 | alternative to `no_sanitize("cfi")` if you only want to disable innstrumentation for specific indirect |
| 1532 | calls rather than applying `no_sanitize("cfi")` on the whole function containing indirect call. Note |
| 1533 | that `cfi_unchecked_attribute` is a type attribute doesn't disable CFI instrumentation on a function |
| 1534 | body.)reST" ; |
| 1535 | |
| 1536 | static const char AttrDoc_CFReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation |
| 1537 | (Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming |
| 1538 | convention (e.g. functions starting with "get" are assumed to return at |
| 1539 | `+0`). |
| 1540 | |
| 1541 | It can be overridden using a family of the following attributes. In |
| 1542 | Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to |
| 1543 | a function communicates that the object is returned at `+1`, and the caller |
| 1544 | is responsible for freeing it. |
| 1545 | Similarly, the annotation `__attribute__((ns_returns_not_retained))` |
| 1546 | specifies that the object is returned at `+0` and the ownership remains with |
| 1547 | the callee. |
| 1548 | The annotation `__attribute__((ns_consumes_self))` specifies that |
| 1549 | the Objective-C method call consumes the reference to `self`, e.g. by |
| 1550 | attaching it to a supplied parameter. |
| 1551 | Additionally, parameters can have an annotation |
| 1552 | `__attribute__((ns_consumed))`, which specifies that passing an owned object |
| 1553 | as that parameter effectively transfers the ownership, and the caller is no |
| 1554 | longer responsible for it. |
| 1555 | These attributes affect code generation when interacting with ARC code, and |
| 1556 | they are used by the Clang Static Analyzer. |
| 1557 | |
| 1558 | In C programs using CoreFoundation, a similar set of attributes: |
| 1559 | `__attribute__((cf_returns_not_retained))`, |
| 1560 | `__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))` |
| 1561 | have the same respective semantics when applied to CoreFoundation objects. |
| 1562 | These attributes affect code generation when interacting with ARC code, and |
| 1563 | they are used by the Clang Static Analyzer. |
| 1564 | |
| 1565 | Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), |
| 1566 | the same attribute family is present: |
| 1567 | `__attribute__((os_returns_not_retained))`, |
| 1568 | `__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`, |
| 1569 | with the same respective semantics. |
| 1570 | Similar to `__attribute__((ns_consumes_self))`, |
| 1571 | `__attribute__((os_consumes_this))` specifies that the method call consumes |
| 1572 | the reference to "this" (e.g., when attaching it to a different object supplied |
| 1573 | as a parameter). |
| 1574 | Out parameters (parameters the function is meant to write into, |
| 1575 | either via pointers-to-pointers or references-to-pointers) |
| 1576 | may be annotated with `__attribute__((os_returns_retained))` |
| 1577 | or `__attribute__((os_returns_not_retained))` which specifies that the object |
| 1578 | written into the out parameter should (or respectively should not) be released |
| 1579 | after use. |
| 1580 | Since often out parameters may or may not be written depending on the exit |
| 1581 | code of the function, |
| 1582 | annotations `__attribute__((os_returns_retained_on_zero))` |
| 1583 | and `__attribute__((os_returns_retained_on_non_zero))` specify that |
| 1584 | an out parameter at `+1` is written if and only if the function returns a zero |
| 1585 | (respectively non-zero) error code. |
| 1586 | Observe that return-code-dependent out parameter annotations are only |
| 1587 | available for retained out parameters, as non-retained object do not have to be |
| 1588 | released by the callee. |
| 1589 | These attributes are only used by the Clang Static Analyzer. |
| 1590 | |
| 1591 | The family of attributes `X_returns_X_retained` can be added to functions, |
| 1592 | C++ methods, and Objective-C methods and properties. |
| 1593 | Attributes `X_consumed` can be added to parameters of methods, functions, |
| 1594 | and Objective-C methods.)reST" ; |
| 1595 | |
| 1596 | static const char AttrDoc_CFReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation |
| 1597 | (Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming |
| 1598 | convention (e.g. functions starting with "get" are assumed to return at |
| 1599 | `+0`). |
| 1600 | |
| 1601 | It can be overridden using a family of the following attributes. In |
| 1602 | Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to |
| 1603 | a function communicates that the object is returned at `+1`, and the caller |
| 1604 | is responsible for freeing it. |
| 1605 | Similarly, the annotation `__attribute__((ns_returns_not_retained))` |
| 1606 | specifies that the object is returned at `+0` and the ownership remains with |
| 1607 | the callee. |
| 1608 | The annotation `__attribute__((ns_consumes_self))` specifies that |
| 1609 | the Objective-C method call consumes the reference to `self`, e.g. by |
| 1610 | attaching it to a supplied parameter. |
| 1611 | Additionally, parameters can have an annotation |
| 1612 | `__attribute__((ns_consumed))`, which specifies that passing an owned object |
| 1613 | as that parameter effectively transfers the ownership, and the caller is no |
| 1614 | longer responsible for it. |
| 1615 | These attributes affect code generation when interacting with ARC code, and |
| 1616 | they are used by the Clang Static Analyzer. |
| 1617 | |
| 1618 | In C programs using CoreFoundation, a similar set of attributes: |
| 1619 | `__attribute__((cf_returns_not_retained))`, |
| 1620 | `__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))` |
| 1621 | have the same respective semantics when applied to CoreFoundation objects. |
| 1622 | These attributes affect code generation when interacting with ARC code, and |
| 1623 | they are used by the Clang Static Analyzer. |
| 1624 | |
| 1625 | Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), |
| 1626 | the same attribute family is present: |
| 1627 | `__attribute__((os_returns_not_retained))`, |
| 1628 | `__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`, |
| 1629 | with the same respective semantics. |
| 1630 | Similar to `__attribute__((ns_consumes_self))`, |
| 1631 | `__attribute__((os_consumes_this))` specifies that the method call consumes |
| 1632 | the reference to "this" (e.g., when attaching it to a different object supplied |
| 1633 | as a parameter). |
| 1634 | Out parameters (parameters the function is meant to write into, |
| 1635 | either via pointers-to-pointers or references-to-pointers) |
| 1636 | may be annotated with `__attribute__((os_returns_retained))` |
| 1637 | or `__attribute__((os_returns_not_retained))` which specifies that the object |
| 1638 | written into the out parameter should (or respectively should not) be released |
| 1639 | after use. |
| 1640 | Since often out parameters may or may not be written depending on the exit |
| 1641 | code of the function, |
| 1642 | annotations `__attribute__((os_returns_retained_on_zero))` |
| 1643 | and `__attribute__((os_returns_retained_on_non_zero))` specify that |
| 1644 | an out parameter at `+1` is written if and only if the function returns a zero |
| 1645 | (respectively non-zero) error code. |
| 1646 | Observe that return-code-dependent out parameter annotations are only |
| 1647 | available for retained out parameters, as non-retained object do not have to be |
| 1648 | released by the callee. |
| 1649 | These attributes are only used by the Clang Static Analyzer. |
| 1650 | |
| 1651 | The family of attributes `X_returns_X_retained` can be added to functions, |
| 1652 | C++ methods, and Objective-C methods and properties. |
| 1653 | Attributes `X_consumed` can be added to parameters of methods, functions, |
| 1654 | and Objective-C methods.)reST" ; |
| 1655 | |
| 1656 | static const char AttrDoc_CFUnknownTransfer[] = R"reST(No documentation.)reST" ; |
| 1657 | |
| 1658 | static const char AttrDoc_CPUDispatch[] = R"reST(The `cpu_specific` and `cpu_dispatch` attributes are used to define and |
| 1659 | resolve multiversioned functions. This form of multiversioning provides a |
| 1660 | mechanism for declaring versions across translation units and manually |
| 1661 | specifying the resolved function list. A specified CPU defines a set of minimum |
| 1662 | features that are required for the function to be called. The result of this is |
| 1663 | that future processors execute the most restrictive version of the function the |
| 1664 | new processor can execute. |
| 1665 | |
| 1666 | In addition, unlike the ICC implementation of this feature, the selection of the |
| 1667 | version does not consider the manufacturer or microarchitecture of the processor. |
| 1668 | It tests solely the list of features that are both supported by the specified |
| 1669 | processor and present in the compiler-rt library. This can be surprising at times, |
| 1670 | as the runtime processor may be from a completely different manufacturer, as long |
| 1671 | as it supports the same feature set. |
| 1672 | |
| 1673 | This can additionally be surprising, as some processors are indistringuishable from |
| 1674 | others based on the list of testable features. When this happens, the variant |
| 1675 | is selected in an unspecified manner. |
| 1676 | |
| 1677 | Function versions are defined with `cpu_specific`, which takes one or more CPU |
| 1678 | names as a parameter. For example: |
| 1679 | |
| 1680 | ```c |
| 1681 | // Declares and defines the ivybridge version of single_cpu. |
| 1682 | __attribute__((cpu_specific(ivybridge))) |
| 1683 | void single_cpu(void){} |
| 1684 | |
| 1685 | // Declares and defines the atom version of single_cpu. |
| 1686 | __attribute__((cpu_specific(atom))) |
| 1687 | void single_cpu(void){} |
| 1688 | |
| 1689 | // Declares and defines both the ivybridge and atom version of multi_cpu. |
| 1690 | __attribute__((cpu_specific(ivybridge, atom))) |
| 1691 | void multi_cpu(void){} |
| 1692 | ``` |
| 1693 | |
| 1694 | A dispatching (or resolving) function can be declared anywhere in a project's |
| 1695 | source code with `cpu_dispatch`. This attribute takes one or more CPU names |
| 1696 | as a parameter (like `cpu_specific`). Functions marked with `cpu_dispatch` |
| 1697 | are not expected to be defined, only declared. If such a marked function has a |
| 1698 | definition, any side effects of the function are ignored; trivial function |
| 1699 | bodies are permissible for ICC compatibility. |
| 1700 | |
| 1701 | ```c |
| 1702 | // Creates a resolver for single_cpu above. |
| 1703 | __attribute__((cpu_dispatch(ivybridge, atom))) |
| 1704 | void single_cpu(void){} |
| 1705 | |
| 1706 | // Creates a resolver for multi_cpu, but adds a 3rd version defined in another |
| 1707 | // translation unit. |
| 1708 | __attribute__((cpu_dispatch(ivybridge, atom, sandybridge))) |
| 1709 | void multi_cpu(void){} |
| 1710 | ``` |
| 1711 | |
| 1712 | Note that it is possible to have a resolving function that dispatches based on |
| 1713 | more or fewer options than are present in the program. Specifying fewer will |
| 1714 | result in the omitted options not being considered during resolution. Specifying |
| 1715 | a version for resolution that isn't defined in the program will result in a |
| 1716 | linking failure. |
| 1717 | |
| 1718 | It is also possible to specify a CPU name of `generic` which will be resolved |
| 1719 | if the executing processor doesn't satisfy the features required in the CPU |
| 1720 | name. The behavior of a program executing on a processor that doesn't satisfy |
| 1721 | any option of a multiversioned function is undefined.)reST" ; |
| 1722 | |
| 1723 | static const char AttrDoc_CPUSpecific[] = R"reST(The `cpu_specific` and `cpu_dispatch` attributes are used to define and |
| 1724 | resolve multiversioned functions. This form of multiversioning provides a |
| 1725 | mechanism for declaring versions across translation units and manually |
| 1726 | specifying the resolved function list. A specified CPU defines a set of minimum |
| 1727 | features that are required for the function to be called. The result of this is |
| 1728 | that future processors execute the most restrictive version of the function the |
| 1729 | new processor can execute. |
| 1730 | |
| 1731 | In addition, unlike the ICC implementation of this feature, the selection of the |
| 1732 | version does not consider the manufacturer or microarchitecture of the processor. |
| 1733 | It tests solely the list of features that are both supported by the specified |
| 1734 | processor and present in the compiler-rt library. This can be surprising at times, |
| 1735 | as the runtime processor may be from a completely different manufacturer, as long |
| 1736 | as it supports the same feature set. |
| 1737 | |
| 1738 | This can additionally be surprising, as some processors are indistringuishable from |
| 1739 | others based on the list of testable features. When this happens, the variant |
| 1740 | is selected in an unspecified manner. |
| 1741 | |
| 1742 | Function versions are defined with `cpu_specific`, which takes one or more CPU |
| 1743 | names as a parameter. For example: |
| 1744 | |
| 1745 | ```c |
| 1746 | // Declares and defines the ivybridge version of single_cpu. |
| 1747 | __attribute__((cpu_specific(ivybridge))) |
| 1748 | void single_cpu(void){} |
| 1749 | |
| 1750 | // Declares and defines the atom version of single_cpu. |
| 1751 | __attribute__((cpu_specific(atom))) |
| 1752 | void single_cpu(void){} |
| 1753 | |
| 1754 | // Declares and defines both the ivybridge and atom version of multi_cpu. |
| 1755 | __attribute__((cpu_specific(ivybridge, atom))) |
| 1756 | void multi_cpu(void){} |
| 1757 | ``` |
| 1758 | |
| 1759 | A dispatching (or resolving) function can be declared anywhere in a project's |
| 1760 | source code with `cpu_dispatch`. This attribute takes one or more CPU names |
| 1761 | as a parameter (like `cpu_specific`). Functions marked with `cpu_dispatch` |
| 1762 | are not expected to be defined, only declared. If such a marked function has a |
| 1763 | definition, any side effects of the function are ignored; trivial function |
| 1764 | bodies are permissible for ICC compatibility. |
| 1765 | |
| 1766 | ```c |
| 1767 | // Creates a resolver for single_cpu above. |
| 1768 | __attribute__((cpu_dispatch(ivybridge, atom))) |
| 1769 | void single_cpu(void){} |
| 1770 | |
| 1771 | // Creates a resolver for multi_cpu, but adds a 3rd version defined in another |
| 1772 | // translation unit. |
| 1773 | __attribute__((cpu_dispatch(ivybridge, atom, sandybridge))) |
| 1774 | void multi_cpu(void){} |
| 1775 | ``` |
| 1776 | |
| 1777 | Note that it is possible to have a resolving function that dispatches based on |
| 1778 | more or fewer options than are present in the program. Specifying fewer will |
| 1779 | result in the omitted options not being considered during resolution. Specifying |
| 1780 | a version for resolution that isn't defined in the program will result in a |
| 1781 | linking failure. |
| 1782 | |
| 1783 | It is also possible to specify a CPU name of `generic` which will be resolved |
| 1784 | if the executing processor doesn't satisfy the features required in the CPU |
| 1785 | name. The behavior of a program executing on a processor that doesn't satisfy |
| 1786 | any option of a multiversioned function is undefined.)reST" ; |
| 1787 | |
| 1788 | static const char AttrDoc_CUDAClusterDims[] = R"reST(In CUDA/HIP programming, the `cluster_dims` attribute, conventionally exposed as the |
| 1789 | `__cluster_dims__` macro, can be applied to a kernel function to set the dimensions of a |
| 1790 | thread block cluster, which is an optional level of hierarchy and made up of thread blocks. |
| 1791 | `__cluster_dims__` defines the cluster size as `(X, Y, Z)`, where each value is the number |
| 1792 | of thread blocks in that dimension. The `cluster_dims` and `no_cluster` attributes are |
| 1793 | mutually exclusive. |
| 1794 | |
| 1795 | ``` |
| 1796 | __global__ __cluster_dims__(2, 1, 1) void kernel(...) { |
| 1797 | ... |
| 1798 | } |
| 1799 | ```)reST" ; |
| 1800 | |
| 1801 | static const char AttrDoc_CUDAConstant[] = R"reST(No documentation.)reST" ; |
| 1802 | |
| 1803 | static const char AttrDoc_CUDADevice[] = R"reST(No documentation.)reST" ; |
| 1804 | |
| 1805 | static const char AttrDoc_CUDADeviceBuiltinSurfaceType[] = R"reST(The `device_builtin_surface_type` attribute can be applied to a class |
| 1806 | template when declaring the surface reference. A surface reference variable |
| 1807 | could be accessed on the host side and, on the device side, might be translated |
| 1808 | into an internal surface object, which is established through surface bind and |
| 1809 | unbind runtime APIs.)reST" ; |
| 1810 | |
| 1811 | static const char AttrDoc_CUDADeviceBuiltinTextureType[] = R"reST(The `device_builtin_texture_type` attribute can be applied to a class |
| 1812 | template when declaring the texture reference. A texture reference variable |
| 1813 | could be accessed on the host side and, on the device side, might be translated |
| 1814 | into an internal texture object, which is established through texture bind and |
| 1815 | unbind runtime APIs.)reST" ; |
| 1816 | |
| 1817 | static const char AttrDoc_CUDAGlobal[] = R"reST(No documentation.)reST" ; |
| 1818 | |
| 1819 | static const char AttrDoc_CUDAGridConstant[] = R"reST(The `__grid_constant__` attribute can be applied to a `const`-qualified kernel |
| 1820 | function argument and allows compiler to take the address of that argument without |
| 1821 | making a copy. The argument applies to sm_70 or newer GPUs, during compilation |
| 1822 | with CUDA-11.7(PTX 7.7) or newer, and is ignored otherwise.)reST" ; |
| 1823 | |
| 1824 | static const char AttrDoc_CUDAHost[] = R"reST(No documentation.)reST" ; |
| 1825 | |
| 1826 | static const char AttrDoc_CUDAInvalidTarget[] = R"reST()reST" ; |
| 1827 | |
| 1828 | static const char AttrDoc_CUDALaunchBounds[] = R"reST(The ``__launch_bounds__`` attribute (also spelled ``launch_bounds``) originates |
| 1829 | in CUDA. It informs the compiler of the launch configuration a kernel will be |
| 1830 | dispatched with, allowing it to optimize the kernel accordingly. It takes the |
| 1831 | form ``__launch_bounds__(<max-threads-per-block>[, |
| 1832 | <min-blocks-per-multiprocessor>[, <max-blocks-per-cluster>]])``. All arguments |
| 1833 | are constant expressions. |
| 1834 | |
| 1835 | The attribute only takes effect on ``__global__`` (kernel) functions; like |
| 1836 | NVCC, Clang ignores it on any other function. |
| 1837 | |
| 1838 | ``<max-threads-per-block>`` specifies the maximum number of threads per block |
| 1839 | the kernel will be launched with. ``<min-blocks-per-multiprocessor>`` specifies |
| 1840 | the desired minimum number of blocks resident per multiprocessor, and |
| 1841 | ``<max-blocks-per-cluster>`` the maximum number of blocks per cluster. |
| 1842 | |
| 1843 | For the NVPTX target, ``<max-threads-per-block>`` and |
| 1844 | ``<min-blocks-per-multiprocessor>`` map to the ``.maxntid`` and ``.minnctapersm`` |
| 1845 | PTX directives, respectively, and ``<max-blocks-per-cluster>`` (which requires |
| 1846 | ``sm_90`` or newer) maps to ``.maxclusterrank``. |
| 1847 | |
| 1848 | For the AMDGPU target, the attribute is translated into the equivalent AMDGPU |
| 1849 | kernel attributes: |
| 1850 | |
| 1851 | - ``<max-threads-per-block>`` sets the maximum |
| 1852 | ``amdgpu_flat_work_group_size`` (as ``1, <max-threads-per-block>``). |
| 1853 | - ``<min-blocks-per-multiprocessor>`` sets the minimum |
| 1854 | ``amdgpu_waves_per_eu``. Note that HIP reinterprets this CUDA argument as a |
| 1855 | minimum number of waves per execution unit, so its meaning differs from the |
| 1856 | NVPTX interpretation. |
| 1857 | - ``<max-blocks-per-cluster>`` is currently ignored. |
| 1858 | |
| 1859 | An explicit ``amdgpu_flat_work_group_size`` or ``amdgpu_waves_per_eu`` attribute |
| 1860 | takes precedence over the value derived from ``__launch_bounds__``. |
| 1861 | |
| 1862 | When the same kernel is declared multiple times, the launch bounds from the most |
| 1863 | recent declaration that specifies them are used; a definition without |
| 1864 | ``__launch_bounds__`` inherits the bounds from an earlier declaration.)reST" ; |
| 1865 | |
| 1866 | static const char AttrDoc_CUDANoCluster[] = R"reST(In CUDA/HIP programming, a kernel function can still be launched with the cluster feature enabled |
| 1867 | at runtime, even without being annotated with `__cluster_dims__`. The LLVM/Clang-exclusive |
| 1868 | `no_cluster` attribute, conventionally exposed as the `__no_cluster__` macro, can be applied to |
| 1869 | a kernel function to explicitly indicate that the cluster feature will not be enabled either at |
| 1870 | compile time or at kernel launch time. This allows the compiler to apply certain optimizations |
| 1871 | without assuming that clustering could be enabled at runtime. It is undefined behavior to launch a |
| 1872 | kernel annotated with `__no_cluster__` if the cluster feature is enabled at runtime. |
| 1873 | The `cluster_dims` and `no_cluster` attributes are mutually exclusive. |
| 1874 | |
| 1875 | ``` |
| 1876 | __global__ __no_cluster__ void kernel(...) { |
| 1877 | ... |
| 1878 | } |
| 1879 | ```)reST" ; |
| 1880 | |
| 1881 | static const char AttrDoc_CUDAShared[] = R"reST(No documentation.)reST" ; |
| 1882 | |
| 1883 | static const char AttrDoc_CXX11NoReturn[] = R"reST(A function declared as `[[noreturn]]` shall not return to its caller. The |
| 1884 | compiler will generate a diagnostic for a function declared as `[[noreturn]]` |
| 1885 | that appears to be capable of returning to its caller. |
| 1886 | |
| 1887 | The `[[_Noreturn]]` spelling is deprecated and only exists to ease code |
| 1888 | migration for code using `[[noreturn]]` after including `<stdnoreturn.h>`.)reST" ; |
| 1889 | |
| 1890 | static const char AttrDoc_CXXAssume[] = R"reST(The `assume` attribute is used to indicate to the optimizer that a |
| 1891 | certain condition is assumed to be true at a certain point in the |
| 1892 | program. If this condition is violated at runtime, the behavior is |
| 1893 | undefined. `assume` can only be applied to a null statement. |
| 1894 | |
| 1895 | Different optimisers are likely to react differently to the presence of |
| 1896 | this attribute; in some cases, adding `assume` may affect performance |
| 1897 | negatively. It should be used with parsimony and care. |
| 1898 | |
| 1899 | Example: |
| 1900 | |
| 1901 | ```c++ |
| 1902 | int f(int x, int y) { |
| 1903 | [[assume(x == 27)]]; |
| 1904 | [[assume(x == y)]]; |
| 1905 | return y + 1; // May be optimised to `return 28`. |
| 1906 | } |
| 1907 | ```)reST" ; |
| 1908 | |
| 1909 | static const char AttrDoc_CallableWhen[] = R"reST(Use `__attribute__((callable_when(...)))` to indicate what states a method |
| 1910 | may be called in. Valid states are unconsumed, consumed, or unknown. Each |
| 1911 | argument to this attribute must be a quoted string. E.g.: |
| 1912 | |
| 1913 | `__attribute__((callable_when("unconsumed", "unknown")))`)reST" ; |
| 1914 | |
| 1915 | static const char AttrDoc_Callback[] = R"reST(The `callback` attribute specifies that the annotated function may invoke the |
| 1916 | specified callback zero or more times. The callback, as well as the passed |
| 1917 | arguments, are identified by their parameter name or position (starting with |
| 1918 | 1!) in the annotated function. The first position in the attribute identifies |
| 1919 | the callback callee, the following positions declare describe its arguments. |
| 1920 | The callback callee is required to be callable with the number, and order, of |
| 1921 | the specified arguments. The index `0`, or the identifier `this`, is used to |
| 1922 | represent an implicit "this" pointer in class methods. If there is no implicit |
| 1923 | "this" pointer it shall not be referenced. The index '-1', or the name "\_\_", |
| 1924 | represents an unknown callback callee argument. This can be a value which is |
| 1925 | not present in the declared parameter list, or one that is, but is potentially |
| 1926 | inspected, captured, or modified. Parameter names and indices can be mixed in |
| 1927 | the callback attribute. |
| 1928 | |
| 1929 | The `callback` attribute, which is directly translated to `callback` |
| 1930 | metadata \<<http://llvm.org/docs/LangRef.html#callback-metadata>>, make the |
| 1931 | connection between the call to the annotated function and the callback callee. |
| 1932 | This can enable interprocedural optimizations which were otherwise impossible. |
| 1933 | If a function parameter is mentioned in the `callback` attribute, through its |
| 1934 | position, it is undefined if that parameter is used for anything other than the |
| 1935 | actual callback. Inspected, captured, or modified parameters shall not be |
| 1936 | listed in the `callback` metadata. |
| 1937 | |
| 1938 | Example encodings for the callback performed by `pthread_create` are shown |
| 1939 | below. The explicit attribute annotation indicates that the third parameter |
| 1940 | (`start_routine`) is called zero or more times by the `pthread_create` function, |
| 1941 | and that the fourth parameter (`arg`) is passed along. Note that the callback |
| 1942 | behavior of `pthread_create` is automatically recognized by Clang. In addition, |
| 1943 | the declarations of `__kmpc_fork_teams` and `__kmpc_fork_call`, generated for |
| 1944 | `#pragma omp target teams` and `#pragma omp parallel`, respectively, are also |
| 1945 | automatically recognized as broker functions. Further functions might be added |
| 1946 | in the future. |
| 1947 | |
| 1948 | ```c |
| 1949 | __attribute__((callback (start_routine, arg))) |
| 1950 | int pthread_create(pthread_t *thread, const pthread_attr_t *attr, |
| 1951 | void *(*start_routine) (void *), void *arg); |
| 1952 | |
| 1953 | __attribute__((callback (3, 4))) |
| 1954 | int pthread_create(pthread_t *thread, const pthread_attr_t *attr, |
| 1955 | void *(*start_routine) (void *), void *arg); |
| 1956 | ```)reST" ; |
| 1957 | |
| 1958 | static const char AttrDoc_CalledOnce[] = R"reST(The `called_once` attribute specifies that the annotated function or method |
| 1959 | parameter is invoked exactly once on all execution paths. It only applies |
| 1960 | to parameters with function-like types, i.e. function pointers or blocks. This |
| 1961 | concept is particularly useful for asynchronous programs. |
| 1962 | |
| 1963 | Clang implements a check for `called_once` parameters, |
| 1964 | `-Wcalled-once-parameter`. It is on by default and finds the following |
| 1965 | violations: |
| 1966 | |
| 1967 | - Parameter is not called at all. |
| 1968 | - Parameter is called more than once. |
| 1969 | - Parameter is not called on one of the execution paths. |
| 1970 | |
| 1971 | In the latter case, Clang pinpoints the path where parameter is not invoked |
| 1972 | by showing the control-flow statement where the path diverges. |
| 1973 | |
| 1974 | ```objc |
| 1975 | void fooWithCallback(void (^callback)(void) __attribute__((called_once))) { |
| 1976 | if (somePredicate()) { |
| 1977 | ... |
| 1978 | callback(); |
| 1979 | } else { |
| 1980 | callback(); // OK: callback is called on every path |
| 1981 | } |
| 1982 | } |
| 1983 | |
| 1984 | void barWithCallback(void (^callback)(void) __attribute__((called_once))) { |
| 1985 | if (somePredicate()) { |
| 1986 | ... |
| 1987 | callback(); // note: previous call is here |
| 1988 | } |
| 1989 | callback(); // warning: callback is called twice |
| 1990 | } |
| 1991 | |
| 1992 | void foobarWithCallback(void (^callback)(void) __attribute__((called_once))) { |
| 1993 | if (somePredicate()) { // warning: callback is not called when condition is false |
| 1994 | ... |
| 1995 | callback(); |
| 1996 | } |
| 1997 | } |
| 1998 | ``` |
| 1999 | |
| 2000 | This attribute is useful for API developers who want to double-check if they |
| 2001 | implemented their method correctly.)reST" ; |
| 2002 | |
| 2003 | static const char AttrDoc_Capability[] = R"reST(No documentation.)reST" ; |
| 2004 | |
| 2005 | static const char AttrDoc_CapturedRecord[] = R"reST()reST" ; |
| 2006 | |
| 2007 | static const char AttrDoc_CarriesDependency[] = R"reST(The `carries_dependency` attribute specifies dependency propagation into and |
| 2008 | out of functions. |
| 2009 | |
| 2010 | When specified on a function or Objective-C method, the `carries_dependency` |
| 2011 | attribute means that the return value carries a dependency out of the function, |
| 2012 | so that the implementation need not constrain ordering upon return from that |
| 2013 | function. Implementations of the function and its caller may choose to preserve |
| 2014 | dependencies instead of emitting memory ordering instructions such as fences. |
| 2015 | |
| 2016 | Note, this attribute does not change the meaning of the program, but may result |
| 2017 | in generation of more efficient code.)reST" ; |
| 2018 | |
| 2019 | static const char AttrDoc_Cleanup[] = R"reST(This attribute allows a function to be run when a local variable goes out of |
| 2020 | scope. The attribute takes the identifier of a function with a parameter type |
| 2021 | that is a pointer to the type with the attribute. |
| 2022 | |
| 2023 | ```c |
| 2024 | static void foo (int *) { ... } |
| 2025 | static void bar (int *) { ... } |
| 2026 | void baz (void) { |
| 2027 | int x __attribute__((cleanup(foo))); |
| 2028 | { |
| 2029 | int y __attribute__((cleanup(bar))); |
| 2030 | } |
| 2031 | } |
| 2032 | ``` |
| 2033 | |
| 2034 | The above example will result in a call to `bar` being passed the address of |
| 2035 | `y` when `y` goes out of scope, then a call to `foo` being passed the |
| 2036 | address of `x` when `x` goes out of scope. If two or more variables share |
| 2037 | the same scope, their `cleanup` callbacks are invoked in the reverse order |
| 2038 | the variables were declared in. It is not possible to check the return value |
| 2039 | (if any) of these `cleanup` callback functions.)reST" ; |
| 2040 | |
| 2041 | static const char AttrDoc_ClspvLibclcBuiltin[] = R"reST(Attribute used by [clspv][clspv] (OpenCL-C to Vulkan SPIR-V compiler) to identify functions coming from [libclc][libclc] (OpenCL-C builtin library). |
| 2042 | |
| 2043 | ```c |
| 2044 | void __attribute__((clspv_libclc_builtin)) libclc_builtin() {} |
| 2045 | ``` |
| 2046 | |
| 2047 | [clspv]: https://github.com/google/clspv |
| 2048 | [libclc]: https://libclc.llvm.org)reST" ; |
| 2049 | |
| 2050 | static const char AttrDoc_CmseNSCall[] = R"reST(This attribute declares a non-secure function type. When compiling for secure |
| 2051 | state, a call to such a function would switch from secure to non-secure state. |
| 2052 | All non-secure function calls must happen only through a function pointer, and |
| 2053 | a non-secure function type should only be used as a base type of a pointer. |
| 2054 | See [ARMv8-M Security Extensions: Requirements on Development |
| 2055 | Tools - Engineering Specification Documentation](https://developer.arm.com/docs/ecm0359818/latest/) for more information.)reST" ; |
| 2056 | |
| 2057 | static const char AttrDoc_CmseNSEntry[] = R"reST(This attribute declares a function that can be called from non-secure state, or |
| 2058 | from secure state. Entering from and returning to non-secure state would switch |
| 2059 | to and from secure state, respectively, and prevent flow of information |
| 2060 | to non-secure state, except via return values. See [ARMv8-M Security Extensions: |
| 2061 | Requirements on Development Tools - Engineering Specification Documentation](https://developer.arm.com/docs/ecm0359818/latest/) for more information.)reST" ; |
| 2062 | |
| 2063 | static const char AttrDoc_CodeAlign[] = R"reST(The `clang::code_align(N)` attribute applies to a loop and specifies the byte |
| 2064 | alignment for a loop. The attribute accepts a positive integer constant |
| 2065 | initialization expression indicating the number of bytes for the minimum |
| 2066 | alignment boundary. Its value must be a power of 2, between 1 and 4096 |
| 2067 | (inclusive). |
| 2068 | |
| 2069 | ```c++ |
| 2070 | void foo() { |
| 2071 | int var = 0; |
| 2072 | [[clang::code_align(16)]] for (int i = 0; i < 10; ++i) var++; |
| 2073 | } |
| 2074 | |
| 2075 | void Array(int *array, size_t n) { |
| 2076 | [[clang::code_align(64)]] for (int i = 0; i < n; ++i) array[i] = 0; |
| 2077 | } |
| 2078 | |
| 2079 | void count () { |
| 2080 | int a1[10], int i = 0; |
| 2081 | [[clang::code_align(32)]] while (i < 10) { a1[i] += 3; } |
| 2082 | } |
| 2083 | |
| 2084 | void check() { |
| 2085 | int a = 10; |
| 2086 | [[clang::code_align(8)]] do { |
| 2087 | a = a + 1; |
| 2088 | } while (a < 20); |
| 2089 | } |
| 2090 | |
| 2091 | template<int A> |
| 2092 | void func() { |
| 2093 | [[clang::code_align(A)]] for(;;) { } |
| 2094 | } |
| 2095 | ```)reST" ; |
| 2096 | |
| 2097 | static const char AttrDoc_CodeModel[] = R"reST(The `model` attribute allows overriding the translation unit's |
| 2098 | code model (specified by `-mcmodel`) for a specific global variable. |
| 2099 | |
| 2100 | On LoongArch, allowed values are "normal", "medium", "extreme". |
| 2101 | |
| 2102 | On x86-64, allowed values are `"small"` and `"large"`. `"small"` is |
| 2103 | roughly equivalent to `-mcmodel=small`, meaning the global is considered |
| 2104 | "small" placed closer to the `.text` section relative to "large" globals, and |
| 2105 | to prefer using 32-bit relocations to access the global. `"large"` is roughly |
| 2106 | equivalent to `-mcmodel=large`, meaning the global is considered "large" and |
| 2107 | placed further from the `.text` section relative to "small" globals, and |
| 2108 | 64-bit relocations must be used to access the global.)reST" ; |
| 2109 | |
| 2110 | static const char AttrDoc_CodeSeg[] = R"reST(The `__declspec(code_seg)` attribute enables the placement of code into separate |
| 2111 | named segments that can be paged or locked in memory individually. This attribute |
| 2112 | is used to control the placement of instantiated templates and compiler-generated |
| 2113 | code. See the documentation for [\_\_declspec(code_seg)][__declspec(code_seg)] on MSDN. |
| 2114 | |
| 2115 | [__declspec(code_seg)]: http://msdn.microsoft.com/en-us/library/dn636922.aspx)reST" ; |
| 2116 | |
| 2117 | static const char AttrDoc_Cold[] = R"reST(`__attribute__((cold))` marks a function as cold, as a manual alternative to PGO hotness data. |
| 2118 | If PGO data is available, the profile count based hotness overrides the `__attribute__((cold))` annotation (unlike `__attribute__((hot))`).)reST" ; |
| 2119 | |
| 2120 | static const char AttrDoc_Common[] = R"reST(No documentation.)reST" ; |
| 2121 | |
| 2122 | static const char AttrDoc_Const[] = R"reST(No documentation.)reST" ; |
| 2123 | |
| 2124 | static const char AttrDoc_ConstInit[] = R"reST(This attribute specifies that the variable to which it is attached is intended |
| 2125 | to have a [constant initializer](http://en.cppreference.com/w/cpp/language/constant_initialization) |
| 2126 | according to the rules of [basic.start.static]. The variable is required to |
| 2127 | have static or thread storage duration. If the initialization of the variable |
| 2128 | is not a constant initializer an error will be produced. This attribute may |
| 2129 | only be used in C++; the `constinit` spelling is only accepted in C++20 |
| 2130 | onwards. |
| 2131 | |
| 2132 | Note that in C++03 strict constant expression checking is not done. Instead |
| 2133 | the attribute reports if Clang can emit the variable as a constant, even if it's |
| 2134 | not technically a 'constant initializer'. This behavior is non-portable. |
| 2135 | |
| 2136 | Static storage duration variables with constant initializers avoid hard-to-find |
| 2137 | bugs caused by the indeterminate order of dynamic initialization. They can also |
| 2138 | be safely used during dynamic initialization across translation units. |
| 2139 | |
| 2140 | This attribute acts as a compile time assertion that the requirements |
| 2141 | for constant initialization have been met. Since these requirements change |
| 2142 | between dialects and have subtle pitfalls it's important to fail fast instead |
| 2143 | of silently falling back on dynamic initialization. |
| 2144 | |
| 2145 | The first use of the attribute on a variable must be part of, or precede, the |
| 2146 | initializing declaration of the variable. C++20 requires the `constinit` |
| 2147 | spelling of the attribute to be present on the initializing declaration if it |
| 2148 | is used anywhere. The other spellings can be specified on a forward declaration |
| 2149 | and omitted on a later initializing declaration. |
| 2150 | |
| 2151 | ```c++ |
| 2152 | // -std=c++14 |
| 2153 | #define SAFE_STATIC [[clang::require_constant_initialization]] |
| 2154 | struct T { |
| 2155 | constexpr T(int) {} |
| 2156 | ~T(); // non-trivial |
| 2157 | }; |
| 2158 | SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor. |
| 2159 | SAFE_STATIC T y = 42; // error: variable does not have a constant initializer |
| 2160 | // copy initialization is not a constant expression on a non-literal type. |
| 2161 | ```)reST" ; |
| 2162 | |
| 2163 | static const char AttrDoc_Constructor[] = R"reST(The `constructor` attribute causes the function to be called before entering |
| 2164 | `main()`, and the `destructor` attribute causes the function to be called |
| 2165 | after returning from `main()` or when the `exit()` function has been |
| 2166 | called. Note, `quick_exit()`, `_Exit()`, and `abort()` prevent a function |
| 2167 | marked `destructor` from being called. |
| 2168 | |
| 2169 | The constructor or destructor function should not accept any arguments and its |
| 2170 | return type should be `void`. |
| 2171 | |
| 2172 | The attributes accept an optional argument used to specify the priority order |
| 2173 | in which to execute constructor and destructor functions. The priority is |
| 2174 | given as an integer constant expression between 101 and 65535 (inclusive). |
| 2175 | Priorities outside of that range are reserved for use by the implementation. A |
| 2176 | lower value indicates a higher priority of initialization. Note that only the |
| 2177 | relative ordering of values is important. For example: |
| 2178 | |
| 2179 | ```c++ |
| 2180 | __attribute__((constructor(200))) void foo(void); |
| 2181 | __attribute__((constructor(101))) void bar(void); |
| 2182 | ``` |
| 2183 | |
| 2184 | `bar()` will be called before `foo()`, and both will be called before |
| 2185 | `main()`. If no argument is given to the `constructor` or `destructor` |
| 2186 | attribute, they default to the value `65535`.)reST" ; |
| 2187 | |
| 2188 | static const char AttrDoc_Consumable[] = R"reST(Each `class` that uses any of the typestate annotations must first be marked |
| 2189 | using the `consumable` attribute. Failure to do so will result in a warning. |
| 2190 | |
| 2191 | This attribute accepts a single parameter that must be one of the following: |
| 2192 | `unknown`, `consumed`, or `unconsumed`.)reST" ; |
| 2193 | |
| 2194 | static const char AttrDoc_ConsumableAutoCast[] = R"reST(No documentation.)reST" ; |
| 2195 | |
| 2196 | static const char AttrDoc_ConsumableSetOnRead[] = R"reST(No documentation.)reST" ; |
| 2197 | |
| 2198 | static const char AttrDoc_Convergent[] = R"reST(The `convergent` attribute can be placed on a function declaration. It is |
| 2199 | translated into the LLVM `convergent` attribute, which indicates that the call |
| 2200 | instructions of a function with this attribute cannot be made control-dependent |
| 2201 | on any additional values. |
| 2202 | |
| 2203 | This attribute is different from `noduplicate` because it allows duplicating |
| 2204 | function calls if it can be proved that the duplicated function calls are |
| 2205 | not made control-dependent on any additional values, e.g., unrolling a loop |
| 2206 | executed by all work items. |
| 2207 | |
| 2208 | Sample usage: |
| 2209 | |
| 2210 | ```c |
| 2211 | void convfunc(void) __attribute__((convergent)); |
| 2212 | // Setting it as a C++11 attribute is also valid in a C++ program. |
| 2213 | // void convfunc(void) [[clang::convergent]]; |
| 2214 | ```)reST" ; |
| 2215 | |
| 2216 | static const char AttrDoc_CoroAwaitElidable[] = R"reST(The `[[clang::coro_await_elidable]]` is a class attribute which can be |
| 2217 | applied to a coroutine return type. It provides a hint to the compiler to apply |
| 2218 | Heap Allocation Elision more aggressively. |
| 2219 | |
| 2220 | When a coroutine function returns such a type, a direct call expression therein |
| 2221 | that returns a prvalue of a type attributed `[[clang::coro_await_elidable]]` |
| 2222 | is said to be under a safe elide context if one of the following is true: |
| 2223 | |
| 2224 | - it is the immediate right-hand side operand to a co_await expression. |
| 2225 | - it is an argument to a `[[clang::coro_await_elidable_argument]]` parameter |
| 2226 | or parameter pack of another direct call expression under a safe elide context. |
| 2227 | |
| 2228 | Do note that the safe elide context applies only to the call expression itself, |
| 2229 | and the context does not transitively include any of its subexpressions unless |
| 2230 | exceptional rules of `[[clang::coro_await_elidable_argument]]` apply. |
| 2231 | |
| 2232 | The compiler performs heap allocation elision on call expressions under a safe |
| 2233 | elide context, if the callee is a coroutine. |
| 2234 | |
| 2235 | Example: |
| 2236 | |
| 2237 | ```c++ |
| 2238 | class [[clang::coro_await_elidable]] Task { ... }; |
| 2239 | |
| 2240 | Task foo(); |
| 2241 | Task bar() { |
| 2242 | co_await foo(); // foo()'s coroutine frame on this line is elidable |
| 2243 | auto t = foo(); // foo()'s coroutine frame on this line is NOT elidable |
| 2244 | co_await t; |
| 2245 | } |
| 2246 | ``` |
| 2247 | |
| 2248 | Such elision replaces the heap allocated activation frame of the callee coroutine |
| 2249 | with a local variable within the enclosing braces in the caller's stack frame. |
| 2250 | The local variable, like other variables in coroutines, may be collected into the |
| 2251 | coroutine frame, which may be allocated on the heap. The behavior is undefined |
| 2252 | if the caller coroutine is destroyed earlier than the callee coroutine.)reST" ; |
| 2253 | |
| 2254 | static const char AttrDoc_CoroAwaitElidableArgument[] = R"reST(The `[[clang::coro_await_elidable_argument]]` is a function parameter attribute. |
| 2255 | It works in conjunction with `[[clang::coro_await_elidable]]` to propagate a |
| 2256 | safe elide context to a parameter or parameter pack if the function is called |
| 2257 | under a safe elide context. |
| 2258 | |
| 2259 | This is sometimes necessary on utility functions used to compose or modify the |
| 2260 | behavior of a callee coroutine. |
| 2261 | |
| 2262 | Example: |
| 2263 | |
| 2264 | ```c++ |
| 2265 | template <typename T> |
| 2266 | class [[clang::coro_await_elidable]] Task { ... }; |
| 2267 | |
| 2268 | template <typename... T> |
| 2269 | class [[clang::coro_await_elidable]] WhenAll { ... }; |
| 2270 | |
| 2271 | // `when_all` is a utility function that composes coroutines. It does not |
| 2272 | // need to be a coroutine to propagate. |
| 2273 | template <typename... T> |
| 2274 | WhenAll<T...> when_all([[clang::coro_await_elidable_argument]] Task<T> tasks...); |
| 2275 | |
| 2276 | Task<int> foo(); |
| 2277 | Task<int> bar(); |
| 2278 | Task<void> example1() { |
| 2279 | // `when_all`, `foo`, and `bar` are all elide safe because `when_all` is |
| 2280 | // under a safe elide context and, thanks to the [[clang::coro_await_elidable_argument]] |
| 2281 | // attribute, such context is propagated to foo and bar. |
| 2282 | co_await when_all(foo(), bar()); |
| 2283 | } |
| 2284 | |
| 2285 | Task<void> example2() { |
| 2286 | // `when_all` and `bar` are elide safe. `foo` is not elide safe. |
| 2287 | auto f = foo(); |
| 2288 | co_await when_all(f, bar()); |
| 2289 | } |
| 2290 | |
| 2291 | |
| 2292 | Task<void> example3() { |
| 2293 | // None of the calls are elide safe. |
| 2294 | auto t = when_all(foo(), bar()); |
| 2295 | co_await t; |
| 2296 | } |
| 2297 | ```)reST" ; |
| 2298 | |
| 2299 | static const char AttrDoc_CoroDisableLifetimeBound[] = R"reST(The `[[clang::coro_lifetimebound]]` is a class attribute which can be applied |
| 2300 | to a coroutine return type ([coro_return_type, coro_wrapper]) (i.e. |
| 2301 | it should also be annotated with `[[clang::coro_return_type]]`). |
| 2302 | |
| 2303 | All parameters of a function are considered to be lifetime bound if the function returns a |
| 2304 | coroutine return type (CRT) annotated with `[[clang::coro_lifetimebound]]`. |
| 2305 | This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function |
| 2306 | with `[[clang::coro_disable_lifetimebound]]` function attribute . |
| 2307 | See documentation of [lifetimebound] for details about lifetime bound analysis. |
| 2308 | |
| 2309 | Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables. |
| 2310 | |
| 2311 | For example, |
| 2312 | |
| 2313 | ```c++ |
| 2314 | task<int> coro(const int& a) { co_return a + 1; } |
| 2315 | task<int> dangling_refs(int a) { |
| 2316 | // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`. |
| 2317 | auto foo = coro(1); |
| 2318 | // `coro` captures reference to local variable `a` which is destroyed after the return. |
| 2319 | return coro(a); |
| 2320 | } |
| 2321 | ``` |
| 2322 | |
| 2323 | Lifetime bound static analysis can be used to detect such instances when coroutines capture references |
| 2324 | which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with |
| 2325 | `[[clang::coro_lifetimebound]]`, then lifetime bound analysis would detect capturing reference to |
| 2326 | temporaries or return address of a local variable. |
| 2327 | |
| 2328 | Both coroutines and coroutine wrappers are part of this analysis. |
| 2329 | |
| 2330 | ```c++ |
| 2331 | template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task { |
| 2332 | using promise_type = some_promise_type; |
| 2333 | }; |
| 2334 | |
| 2335 | Task<int> coro(const int& a) { co_return a + 1; } |
| 2336 | [[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) { |
| 2337 | return a > b ? coro(a) : coro(b); |
| 2338 | } |
| 2339 | Task<int> temporary_reference() { |
| 2340 | auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression. |
| 2341 | |
| 2342 | int a = 1; |
| 2343 | auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary. |
| 2344 | |
| 2345 | co_return co_await coro(1); // fine. |
| 2346 | } |
| 2347 | [[clang::coro_wrapper]] Task<int> stack_reference(int a) { |
| 2348 | return coro(a); // warning: returning address of stack variable `a`. |
| 2349 | } |
| 2350 | ``` |
| 2351 | |
| 2352 | This analysis can be disabled for all calls to a particular function by annotating the function |
| 2353 | with function attribute `[[clang::coro_disable_lifetimebound]]`. |
| 2354 | For example, this could be useful for coroutine wrappers which accept reference parameters |
| 2355 | but do not pass them to the underlying coroutine or pass them by value. |
| 2356 | |
| 2357 | ```c++ |
| 2358 | Task<int> coro(int a) { co_return a + 1; } |
| 2359 | [[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) { |
| 2360 | return coro(a + 1); |
| 2361 | } |
| 2362 | void use() { |
| 2363 | auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound. |
| 2364 | } |
| 2365 | ```)reST" ; |
| 2366 | |
| 2367 | static const char AttrDoc_CoroLifetimeBound[] = R"reST(The `[[clang::coro_lifetimebound]]` is a class attribute which can be applied |
| 2368 | to a coroutine return type ([coro_return_type, coro_wrapper]) (i.e. |
| 2369 | it should also be annotated with `[[clang::coro_return_type]]`). |
| 2370 | |
| 2371 | All parameters of a function are considered to be lifetime bound if the function returns a |
| 2372 | coroutine return type (CRT) annotated with `[[clang::coro_lifetimebound]]`. |
| 2373 | This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function |
| 2374 | with `[[clang::coro_disable_lifetimebound]]` function attribute . |
| 2375 | See documentation of [lifetimebound] for details about lifetime bound analysis. |
| 2376 | |
| 2377 | Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables. |
| 2378 | |
| 2379 | For example, |
| 2380 | |
| 2381 | ```c++ |
| 2382 | task<int> coro(const int& a) { co_return a + 1; } |
| 2383 | task<int> dangling_refs(int a) { |
| 2384 | // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`. |
| 2385 | auto foo = coro(1); |
| 2386 | // `coro` captures reference to local variable `a` which is destroyed after the return. |
| 2387 | return coro(a); |
| 2388 | } |
| 2389 | ``` |
| 2390 | |
| 2391 | Lifetime bound static analysis can be used to detect such instances when coroutines capture references |
| 2392 | which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with |
| 2393 | `[[clang::coro_lifetimebound]]`, then lifetime bound analysis would detect capturing reference to |
| 2394 | temporaries or return address of a local variable. |
| 2395 | |
| 2396 | Both coroutines and coroutine wrappers are part of this analysis. |
| 2397 | |
| 2398 | ```c++ |
| 2399 | template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task { |
| 2400 | using promise_type = some_promise_type; |
| 2401 | }; |
| 2402 | |
| 2403 | Task<int> coro(const int& a) { co_return a + 1; } |
| 2404 | [[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) { |
| 2405 | return a > b ? coro(a) : coro(b); |
| 2406 | } |
| 2407 | Task<int> temporary_reference() { |
| 2408 | auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression. |
| 2409 | |
| 2410 | int a = 1; |
| 2411 | auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary. |
| 2412 | |
| 2413 | co_return co_await coro(1); // fine. |
| 2414 | } |
| 2415 | [[clang::coro_wrapper]] Task<int> stack_reference(int a) { |
| 2416 | return coro(a); // warning: returning address of stack variable `a`. |
| 2417 | } |
| 2418 | ``` |
| 2419 | |
| 2420 | This analysis can be disabled for all calls to a particular function by annotating the function |
| 2421 | with function attribute `[[clang::coro_disable_lifetimebound]]`. |
| 2422 | For example, this could be useful for coroutine wrappers which accept reference parameters |
| 2423 | but do not pass them to the underlying coroutine or pass them by value. |
| 2424 | |
| 2425 | ```c++ |
| 2426 | Task<int> coro(int a) { co_return a + 1; } |
| 2427 | [[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) { |
| 2428 | return coro(a + 1); |
| 2429 | } |
| 2430 | void use() { |
| 2431 | auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound. |
| 2432 | } |
| 2433 | ```)reST" ; |
| 2434 | |
| 2435 | static const char AttrDoc_CoroOnlyDestroyWhenComplete[] = R"reST(The `coro_only_destroy_when_complete` attribute should be marked on a C++ class. The coroutines |
| 2436 | whose return type is marked with the attribute are assumed to be destroyed only after the coroutine has |
| 2437 | reached the final suspend point. |
| 2438 | |
| 2439 | This is helpful for the optimizers to reduce the size of the destroy function for the coroutines. |
| 2440 | |
| 2441 | For example, |
| 2442 | |
| 2443 | ```c++ |
| 2444 | A foo() { |
| 2445 | dtor d; |
| 2446 | co_await something(); |
| 2447 | dtor d1; |
| 2448 | co_await something(); |
| 2449 | dtor d2; |
| 2450 | co_return 43; |
| 2451 | } |
| 2452 | ``` |
| 2453 | |
| 2454 | The compiler may generate the following pseudocode: |
| 2455 | |
| 2456 | ```c++ |
| 2457 | void foo.destroy(foo.Frame *frame) { |
| 2458 | switch(frame->suspend_index()) { |
| 2459 | case 1: |
| 2460 | frame->d.~dtor(); |
| 2461 | break; |
| 2462 | case 2: |
| 2463 | frame->d.~dtor(); |
| 2464 | frame->d1.~dtor(); |
| 2465 | break; |
| 2466 | case 3: |
| 2467 | frame->d.~dtor(); |
| 2468 | frame->d1.~dtor(); |
| 2469 | frame->d2.~dtor(); |
| 2470 | break; |
| 2471 | default: // coroutine completed or haven't started |
| 2472 | break; |
| 2473 | } |
| 2474 | |
| 2475 | frame->promise.~promise_type(); |
| 2476 | delete frame; |
| 2477 | } |
| 2478 | ``` |
| 2479 | |
| 2480 | The `foo.destroy()` function's purpose is to release all of the resources |
| 2481 | initialized for the coroutine when it is destroyed in a suspended state. |
| 2482 | However, if the coroutine is only ever destroyed at the final suspend state, |
| 2483 | the rest of the conditions are superfluous. |
| 2484 | |
| 2485 | The user can use the `coro_only_destroy_when_complete` attributo suppress |
| 2486 | generation of the other destruction cases, optimizing the above `foo.destroy` to: |
| 2487 | |
| 2488 | ```c++ |
| 2489 | void foo.destroy(foo.Frame *frame) { |
| 2490 | frame->promise.~promise_type(); |
| 2491 | delete frame; |
| 2492 | } |
| 2493 | ```)reST" ; |
| 2494 | |
| 2495 | static const char AttrDoc_CoroReturnType[] = R"reST(The `[[clang::coro_return_type]]` attribute is used to help static analyzers to recognize |
| 2496 | coroutines from the function signatures. |
| 2497 | |
| 2498 | The `coro_return_type` attribute should be marked on a C++ class to mark it as |
| 2499 | a **coroutine return type (CRT)**. |
| 2500 | |
| 2501 | A function `R func(P1, .., PN)` has a coroutine return type (CRT) `R` if `R` |
| 2502 | is marked by `[[clang::coro_return_type]]` and `R` has a promise type associated to it |
| 2503 | (i.e., std::coroutine_traits\<R, P1, .., PN>::promise_type is a valid promise type). |
| 2504 | |
| 2505 | If the return type of a function is a `CRT` then the function must be a coroutine. |
| 2506 | Otherwise the program is invalid. It is allowed for a non-coroutine to return a `CRT` |
| 2507 | if the function is marked with `[[clang::coro_wrapper]]`. |
| 2508 | |
| 2509 | The `[[clang::coro_wrapper]]` attribute should be marked on a C++ function to mark it as |
| 2510 | a **coroutine wrapper**. A coroutine wrapper is a function which returns a `CRT`, |
| 2511 | is not a coroutine itself and is marked with `[[clang::coro_wrapper]]`. |
| 2512 | |
| 2513 | Clang will enforce that all functions that return a `CRT` are either coroutines or marked |
| 2514 | with `[[clang::coro_wrapper]]`. Clang will enforce this with an error. |
| 2515 | |
| 2516 | From a language perspective, it is not possible to differentiate between a coroutine and a |
| 2517 | function returning a CRT by merely looking at the function signature. |
| 2518 | |
| 2519 | Coroutine wrappers, in particular, are susceptible to capturing |
| 2520 | references to temporaries and other lifetime issues. This allows to avoid such lifetime |
| 2521 | issues with coroutine wrappers. |
| 2522 | |
| 2523 | For example, |
| 2524 | |
| 2525 | ```c++ |
| 2526 | // This is a CRT. |
| 2527 | template <typename T> struct [[clang::coro_return_type]] Task { |
| 2528 | using promise_type = some_promise_type; |
| 2529 | }; |
| 2530 | |
| 2531 | Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine. |
| 2532 | Task<int> foo() { return increment(1); } // Error. foo is not a coroutine. |
| 2533 | |
| 2534 | // Fine for a coroutine wrapper to return a CRT. |
| 2535 | [[clang::coro_wrapper]] Task<int> foo() { return increment(1); } |
| 2536 | |
| 2537 | void bar() { |
| 2538 | // Invalid. This intantiates a function which returns a CRT but is not marked as |
| 2539 | // a coroutine wrapper. |
| 2540 | std::function<Task<int>(int)> f = increment; |
| 2541 | } |
| 2542 | ``` |
| 2543 | |
| 2544 | Note: `a_promise_type::get_return_object` is exempted from this analysis as it is a necessary |
| 2545 | implementation detail of any coroutine library.)reST" ; |
| 2546 | |
| 2547 | static const char AttrDoc_CoroWrapper[] = R"reST(The `[[clang::coro_return_type]]` attribute is used to help static analyzers to recognize |
| 2548 | coroutines from the function signatures. |
| 2549 | |
| 2550 | The `coro_return_type` attribute should be marked on a C++ class to mark it as |
| 2551 | a **coroutine return type (CRT)**. |
| 2552 | |
| 2553 | A function `R func(P1, .., PN)` has a coroutine return type (CRT) `R` if `R` |
| 2554 | is marked by `[[clang::coro_return_type]]` and `R` has a promise type associated to it |
| 2555 | (i.e., std::coroutine_traits\<R, P1, .., PN>::promise_type is a valid promise type). |
| 2556 | |
| 2557 | If the return type of a function is a `CRT` then the function must be a coroutine. |
| 2558 | Otherwise the program is invalid. It is allowed for a non-coroutine to return a `CRT` |
| 2559 | if the function is marked with `[[clang::coro_wrapper]]`. |
| 2560 | |
| 2561 | The `[[clang::coro_wrapper]]` attribute should be marked on a C++ function to mark it as |
| 2562 | a **coroutine wrapper**. A coroutine wrapper is a function which returns a `CRT`, |
| 2563 | is not a coroutine itself and is marked with `[[clang::coro_wrapper]]`. |
| 2564 | |
| 2565 | Clang will enforce that all functions that return a `CRT` are either coroutines or marked |
| 2566 | with `[[clang::coro_wrapper]]`. Clang will enforce this with an error. |
| 2567 | |
| 2568 | From a language perspective, it is not possible to differentiate between a coroutine and a |
| 2569 | function returning a CRT by merely looking at the function signature. |
| 2570 | |
| 2571 | Coroutine wrappers, in particular, are susceptible to capturing |
| 2572 | references to temporaries and other lifetime issues. This allows to avoid such lifetime |
| 2573 | issues with coroutine wrappers. |
| 2574 | |
| 2575 | For example, |
| 2576 | |
| 2577 | ```c++ |
| 2578 | // This is a CRT. |
| 2579 | template <typename T> struct [[clang::coro_return_type]] Task { |
| 2580 | using promise_type = some_promise_type; |
| 2581 | }; |
| 2582 | |
| 2583 | Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine. |
| 2584 | Task<int> foo() { return increment(1); } // Error. foo is not a coroutine. |
| 2585 | |
| 2586 | // Fine for a coroutine wrapper to return a CRT. |
| 2587 | [[clang::coro_wrapper]] Task<int> foo() { return increment(1); } |
| 2588 | |
| 2589 | void bar() { |
| 2590 | // Invalid. This intantiates a function which returns a CRT but is not marked as |
| 2591 | // a coroutine wrapper. |
| 2592 | std::function<Task<int>(int)> f = increment; |
| 2593 | } |
| 2594 | ``` |
| 2595 | |
| 2596 | Note: `a_promise_type::get_return_object` is exempted from this analysis as it is a necessary |
| 2597 | implementation detail of any coroutine library.)reST" ; |
| 2598 | |
| 2599 | static const char AttrDoc_CountedBy[] = R"reST(The `counted_by` attribute is applied to a pointer or flexible array member to |
| 2600 | indicate that the pointer points to (or the flexible array member contains) at |
| 2601 | least the number of *elements* given by the attribute's argument. |
| 2602 | |
| 2603 | This attribute is used by {doc}`-fbounds-safety <BoundsSafety>` to propagate |
| 2604 | bounds information on API surfaces without any ABI changes. This attribute is |
| 2605 | also used to improve the results of the array bound sanitizer and the |
| 2606 | `__builtin_dynamic_object_size` builtin. |
| 2607 | |
| 2608 | Because the size of the pointee type must be known to compute the pointer's |
| 2609 | bounds, such a pointer must not be used while its pointee type is incomplete; a |
| 2610 | pointer to a forward-declared type is accepted on fields annotated with |
| 2611 | `counted_by`, but the type must be completed before the pointer is used. If |
| 2612 | the pointee type can never be completed, `counted_by` is rejected and |
| 2613 | `sized_by` should be used instead. `void *` is a special case: as a GNU |
| 2614 | extension (diagnosed by `-Wgnu-pointer-arith`), `counted_by` is accepted on |
| 2615 | it, where it behaves like `sized_by` (the argument is treated as a byte count, |
| 2616 | `void` having an assumed size of one byte). |
| 2617 | |
| 2618 | A pointer annotated with `counted_by` must have a count of zero when it is |
| 2619 | null. This requirement is currently only enforced when compiling with |
| 2620 | {doc}`-fbounds-safety <BoundsSafety>` (see {ref}`Current status of |
| 2621 | -fbounds-safety support in upstream Clang <bounds-safety-current-upstream-status>`). Use |
| 2622 | `counted_by_or_null` for a pointer that may be null while carrying a nonzero |
| 2623 | count. |
| 2624 | |
| 2625 | #### Keeping pointer and count in sync |
| 2626 | |
| 2627 | The `counted_by` attribute establishes a relationship between the annotated |
| 2628 | pointer and its count: the pointer must point to at least `count` elements. |
| 2629 | Assigning to only one of them can break this relationship. |
| 2630 | Without {doc}`-fbounds-safety <BoundsSafety>`, it is the programmer's |
| 2631 | responsibility to ensure the pointer and count remain in sync. With |
| 2632 | `-fbounds-safety` it is automatically enforced. For example: |
| 2633 | |
| 2634 | ```c |
| 2635 | struct buffer { |
| 2636 | int *buf __attribute__((counted_by(count))); |
| 2637 | size_t count; |
| 2638 | }; |
| 2639 | |
| 2640 | void grow(struct buffer *b, size_t new_count) { |
| 2641 | // b->buf isn't updated. The underlying memory pointed to by b->buf might be |
| 2642 | // smaller than new_count which would contradict the counted_by attribute. |
| 2643 | // Compile error with -fbounds-safety but allowed without -fbounds-safety. |
| 2644 | b->count = new_count; |
| 2645 | } |
| 2646 | ``` |
| 2647 | |
| 2648 | Updating both together - so that `buf` points to `count` elements - keeps |
| 2649 | the attribute true. For example: |
| 2650 | |
| 2651 | ```c |
| 2652 | void grow(struct buffer *b, size_t new_count) { |
| 2653 | // Allowed by -fbounds-safety |
| 2654 | int *new_buf = malloc(new_count * sizeof(int)); |
| 2655 | // -fbounds-safety enforces that the `new_buf` points to at least `new_count` |
| 2656 | // integers at runtime. Without -fbounds-safety nothing enforces this. |
| 2657 | b->buf = new_buf; |
| 2658 | b->count = new_count; |
| 2659 | } |
| 2660 | ``` |
| 2661 | |
| 2662 | #### Flexible array members |
| 2663 | |
| 2664 | The `counted_by` attribute may also be applied to the flexible array member of |
| 2665 | a structure in C. In this case the argument names the field member holding the |
| 2666 | count of elements in the flexible array; that field must be within the same |
| 2667 | non-anonymous, enclosing struct as the flexible array member. |
| 2668 | |
| 2669 | This example specifies that the flexible array member `array` has the number |
| 2670 | of elements allocated for it in `count`: |
| 2671 | |
| 2672 | ```c |
| 2673 | struct bar; |
| 2674 | |
| 2675 | struct foo { |
| 2676 | size_t count; |
| 2677 | char other; |
| 2678 | struct bar *array[] __attribute__((counted_by(count))); |
| 2679 | }; |
| 2680 | ``` |
| 2681 | |
| 2682 | This establishes a relationship between `array` and `count`. Specifically, |
| 2683 | `array` must have at least `count` number of elements available. It's the |
| 2684 | user's responsibility to ensure that this relationship is maintained through |
| 2685 | changes to the structure. |
| 2686 | |
| 2687 | In the following example, the allocated array erroneously has fewer elements |
| 2688 | than what's specified by `p->count`. This would result in an out-of-bounds |
| 2689 | access not being detected. |
| 2690 | |
| 2691 | ```c |
| 2692 | #define SIZE_INCR 42 |
| 2693 | |
| 2694 | struct foo *p; |
| 2695 | |
| 2696 | void foo_alloc(size_t count) { |
| 2697 | p = malloc(MAX(sizeof(struct foo), |
| 2698 | offsetof(struct foo, array[0]) + count * sizeof(struct bar *))); |
| 2699 | p->count = count + SIZE_INCR; |
| 2700 | } |
| 2701 | ``` |
| 2702 | |
| 2703 | The next example updates `p->count`, but breaks the relationship requirement |
| 2704 | that `p->array` must have at least `p->count` number of elements available: |
| 2705 | |
| 2706 | ```c |
| 2707 | #define SIZE_INCR 42 |
| 2708 | |
| 2709 | struct foo *p; |
| 2710 | |
| 2711 | void foo_alloc(size_t count) { |
| 2712 | p = malloc(MAX(sizeof(struct foo), |
| 2713 | offsetof(struct foo, array[0]) + count * sizeof(struct bar *))); |
| 2714 | p->count = count; |
| 2715 | } |
| 2716 | |
| 2717 | void use_foo(int index, int val) { |
| 2718 | p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */ |
| 2719 | p->array[index] = val; /* The sanitizer can't properly check this access. */ |
| 2720 | } |
| 2721 | ``` |
| 2722 | |
| 2723 | In this example, an update to `p->count` maintains the relationship |
| 2724 | requirement: |
| 2725 | |
| 2726 | ```c |
| 2727 | void use_foo(int index, int val) { |
| 2728 | if (p->count == 0) |
| 2729 | return; |
| 2730 | --p->count; |
| 2731 | p->array[index] = val; |
| 2732 | } |
| 2733 | ```)reST" ; |
| 2734 | |
| 2735 | static const char AttrDoc_CountedByOrNull[] = R"reST(The `counted_by_or_null` attribute is applied to a pointer to indicate that, |
| 2736 | if the pointer is non-null, it points to memory containing at least the number |
| 2737 | of *elements* given by the attribute's argument. If the pointer is null, the |
| 2738 | value of the argument is ignored and the pointer points to zero elements. |
| 2739 | |
| 2740 | The `counted_by_or_null` attribute is identical to `counted_by` except that |
| 2741 | it treats null pointers differently and cannot be applied to a flexible array |
| 2742 | member. Whereas `counted_by` requires a null pointer to have a count of zero, |
| 2743 | `counted_by_or_null` allows the pointer to be null regardless of the value of |
| 2744 | the count. This supports the common idiom where a pointer is either null or |
| 2745 | points to memory containing at least the given number of elements. |
| 2746 | |
| 2747 | Currently only {doc}`-fbounds-safety <BoundsSafety>` makes use of the |
| 2748 | distinction between `counted_by_or_null` and `counted_by` (see |
| 2749 | {ref}`Current status of -fbounds-safety support in upstream Clang |
| 2750 | <bounds-safety-current-upstream-status>`).)reST" ; |
| 2751 | |
| 2752 | static const char AttrDoc_DLLExport[] = R"reST(The `__declspec(dllexport)` attribute declares a variable, function, or |
| 2753 | Objective-C interface to be exported from the module. It is available under the |
| 2754 | `-fdeclspec` flag for compatibility with various compilers. The primary use |
| 2755 | is for COFF object files which explicitly specify what interfaces are available |
| 2756 | for external use. See the [dllexport][dllexport] documentation on MSDN for more |
| 2757 | information. |
| 2758 | |
| 2759 | [dllexport]: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST" ; |
| 2760 | |
| 2761 | static const char AttrDoc_DLLExportOnDecl[] = R"reST()reST" ; |
| 2762 | |
| 2763 | static const char AttrDoc_DLLExportStaticLocal[] = R"reST()reST" ; |
| 2764 | |
| 2765 | static const char AttrDoc_DLLImport[] = R"reST(The `__declspec(dllimport)` attribute declares a variable, function, or |
| 2766 | Objective-C interface to be imported from an external module. It is available |
| 2767 | under the `-fdeclspec` flag for compatibility with various compilers. The |
| 2768 | primary use is for COFF object files which explicitly specify what interfaces |
| 2769 | are imported from external modules. See the [dllimport][dllimport] documentation on MSDN |
| 2770 | for more information. |
| 2771 | |
| 2772 | Note that a dllimport function may still be inlined, if its definition is |
| 2773 | available and it doesn't reference any non-dllimport functions or global |
| 2774 | variables. |
| 2775 | |
| 2776 | [dllimport]: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST" ; |
| 2777 | |
| 2778 | static const char AttrDoc_DLLImportStaticLocal[] = R"reST()reST" ; |
| 2779 | |
| 2780 | static const char AttrDoc_Deprecated[] = R"reST(The `deprecated` attribute can be applied to a function, a variable, or a |
| 2781 | type. This is useful when identifying functions, variables, or types that are |
| 2782 | expected to be removed in a future version of a program. |
| 2783 | |
| 2784 | Consider the function declaration for a hypothetical function `f`: |
| 2785 | |
| 2786 | ```c++ |
| 2787 | void f(void) __attribute__((deprecated("message", "replacement"))); |
| 2788 | ``` |
| 2789 | |
| 2790 | When spelled as `__attribute__((deprecated))`, the deprecated attribute can have |
| 2791 | two optional string arguments. The first one is the message to display when |
| 2792 | emitting the warning; the second one enables the compiler to provide a Fix-It |
| 2793 | to replace the deprecated name with a new name. Otherwise, when spelled as |
| 2794 | `[[gnu::deprecated]]` or `[[deprecated]]`, the attribute can have one optional |
| 2795 | string argument which is the message to display when emitting the warning.)reST" ; |
| 2796 | |
| 2797 | static const char AttrDoc_Destructor[] = R"reST(The `constructor` attribute causes the function to be called before entering |
| 2798 | `main()`, and the `destructor` attribute causes the function to be called |
| 2799 | after returning from `main()` or when the `exit()` function has been |
| 2800 | called. Note, `quick_exit()`, `_Exit()`, and `abort()` prevent a function |
| 2801 | marked `destructor` from being called. |
| 2802 | |
| 2803 | The constructor or destructor function should not accept any arguments and its |
| 2804 | return type should be `void`. |
| 2805 | |
| 2806 | The attributes accept an optional argument used to specify the priority order |
| 2807 | in which to execute constructor and destructor functions. The priority is |
| 2808 | given as an integer constant expression between 101 and 65535 (inclusive). |
| 2809 | Priorities outside of that range are reserved for use by the implementation. A |
| 2810 | lower value indicates a higher priority of initialization. Note that only the |
| 2811 | relative ordering of values is important. For example: |
| 2812 | |
| 2813 | ```c++ |
| 2814 | __attribute__((constructor(200))) void foo(void); |
| 2815 | __attribute__((constructor(101))) void bar(void); |
| 2816 | ``` |
| 2817 | |
| 2818 | `bar()` will be called before `foo()`, and both will be called before |
| 2819 | `main()`. If no argument is given to the `constructor` or `destructor` |
| 2820 | attribute, they default to the value `65535`.)reST" ; |
| 2821 | |
| 2822 | static const char AttrDoc_DeviceKernel[] = R"reST(These attributes specify that the function represents a kernel for device offloading. |
| 2823 | The specific semantics depend on the offloading language, target, and attribute spelling. |
| 2824 | Here is a code example using the attribute to mark a function as a kernel: |
| 2825 | |
| 2826 | ```c++ |
| 2827 | [[clang::device_kernel]] int foo(int x) { return ++x; } |
| 2828 | ```)reST" ; |
| 2829 | |
| 2830 | static const char AttrDoc_DiagnoseAsBuiltin[] = R"reST(The `diagnose_as_builtin` attribute indicates that Fortify diagnostics are to |
| 2831 | be applied to the declared function as if it were the function specified by the |
| 2832 | attribute. The builtin function whose diagnostics are to be mimicked should be |
| 2833 | given. In addition, the order in which arguments should be applied must also |
| 2834 | be given. |
| 2835 | |
| 2836 | For example, the attribute can be used as follows. |
| 2837 | |
| 2838 | ```c |
| 2839 | __attribute__((diagnose_as_builtin(__builtin_memset, 3, 2, 1))) |
| 2840 | void *mymemset(int n, int c, void *s) { |
| 2841 | // ... |
| 2842 | } |
| 2843 | ``` |
| 2844 | |
| 2845 | This indicates that calls to `mymemset` should be diagnosed as if they were |
| 2846 | calls to `__builtin_memset`. The arguments `3, 2, 1` indicate by index the |
| 2847 | order in which arguments of `mymemset` should be applied to |
| 2848 | `__builtin_memset`. The third argument should be applied first, then the |
| 2849 | second, and then the first. Thus (when Fortify warnings are enabled) the call |
| 2850 | `mymemset(n, c, s)` will diagnose overflows as if it were the call |
| 2851 | `__builtin_memset(s, c, n)`. |
| 2852 | |
| 2853 | For variadic functions, the variadic arguments must come in the same order as |
| 2854 | they would to the builtin function, after all normal arguments. For instance, |
| 2855 | to diagnose a new function as if it were `sscanf`, we can use the attribute as |
| 2856 | follows. |
| 2857 | |
| 2858 | ```c |
| 2859 | __attribute__((diagnose_as_builtin(sscanf, 1, 2))) |
| 2860 | int mysscanf(const char *str, const char *format, ...) { |
| 2861 | // ... |
| 2862 | } |
| 2863 | ``` |
| 2864 | |
| 2865 | Then the call `mysscanf("abc def", "%4s %4s", buf1, buf2)` will be diagnosed as |
| 2866 | if it were the call `sscanf("abc def", "%4s %4s", buf1, buf2)`. |
| 2867 | |
| 2868 | This attribute cannot be applied to non-static member functions.)reST" ; |
| 2869 | |
| 2870 | static const char AttrDoc_DiagnoseIf[] = R"reST(The `diagnose_if` attribute can be placed on function declarations to emit |
| 2871 | warnings or errors at compile-time if calls to the attributed function meet |
| 2872 | certain user-defined criteria. For example: |
| 2873 | |
| 2874 | ```c |
| 2875 | int abs(int a) |
| 2876 | __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning"))); |
| 2877 | int must_abs(int a) |
| 2878 | __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error"))); |
| 2879 | |
| 2880 | int val = abs(1); // warning: Redundant abs call |
| 2881 | int val2 = must_abs(1); // error: Redundant abs call |
| 2882 | int val3 = abs(val); |
| 2883 | int val4 = must_abs(val); // Because run-time checks are not emitted for |
| 2884 | // diagnose_if attributes, this executes without |
| 2885 | // issue. |
| 2886 | ``` |
| 2887 | |
| 2888 | `diagnose_if` is closely related to `enable_if`, with a few key differences: |
| 2889 | |
| 2890 | - Overload resolution is not aware of `diagnose_if` attributes: they're |
| 2891 | considered only after we select the best candidate from a given candidate set. |
| 2892 | - Function declarations that differ only in their `diagnose_if` attributes are |
| 2893 | considered to be redeclarations of the same function (not overloads). |
| 2894 | - If the condition provided to `diagnose_if` cannot be evaluated, no |
| 2895 | diagnostic will be emitted. |
| 2896 | |
| 2897 | Otherwise, `diagnose_if` is essentially the logical negation of `enable_if`. |
| 2898 | |
| 2899 | As a result of bullet number two, `diagnose_if` attributes will stack on the |
| 2900 | same function. For example: |
| 2901 | |
| 2902 | ```c |
| 2903 | int foo() __attribute__((diagnose_if(1, "diag1", "warning"))); |
| 2904 | int foo() __attribute__((diagnose_if(1, "diag2", "warning"))); |
| 2905 | |
| 2906 | int bar = foo(); // warning: diag1 |
| 2907 | // warning: diag2 |
| 2908 | int (*fooptr)(void) = foo; // warning: diag1 |
| 2909 | // warning: diag2 |
| 2910 | |
| 2911 | constexpr int supportsAPILevel(int N) { return N < 5; } |
| 2912 | int baz(int a) |
| 2913 | __attribute__((diagnose_if(!supportsAPILevel(10), |
| 2914 | "Upgrade to API level 10 to use baz", "error"))); |
| 2915 | int baz(int a) |
| 2916 | __attribute__((diagnose_if(!a, "0 is not recommended.", "warning"))); |
| 2917 | |
| 2918 | int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz |
| 2919 | int v = baz(0); // error: Upgrade to API level 10 to use baz |
| 2920 | ``` |
| 2921 | |
| 2922 | Query for this feature with `__has_attribute(diagnose_if)`.)reST" ; |
| 2923 | |
| 2924 | static const char AttrDoc_DisableSanitizerInstrumentation[] = R"reST(Use the `disable_sanitizer_instrumentation` attribute on a function, |
| 2925 | Objective-C method, or global variable, to specify that no sanitizer |
| 2926 | instrumentation should be applied. |
| 2927 | |
| 2928 | This is not the same as `__attribute__((no_sanitize(...)))`, which depending |
| 2929 | on the tool may still insert instrumentation to prevent false positive reports.)reST" ; |
| 2930 | |
| 2931 | static const char AttrDoc_DisableTailCalls[] = R"reST(The `disable_tail_calls` attribute instructs the backend to not perform tail |
| 2932 | call optimization inside the marked function. |
| 2933 | |
| 2934 | For example: |
| 2935 | |
| 2936 | ```c |
| 2937 | int callee(int); |
| 2938 | |
| 2939 | int foo(int a) __attribute__((disable_tail_calls)) { |
| 2940 | return callee(a); // This call is not tail-call optimized. |
| 2941 | } |
| 2942 | ``` |
| 2943 | |
| 2944 | Marking virtual functions as `disable_tail_calls` is legal. |
| 2945 | |
| 2946 | ```c++ |
| 2947 | int callee(int); |
| 2948 | |
| 2949 | class Base { |
| 2950 | public: |
| 2951 | [[clang::disable_tail_calls]] virtual int foo1() { |
| 2952 | return callee(); // This call is not tail-call optimized. |
| 2953 | } |
| 2954 | }; |
| 2955 | |
| 2956 | class Derived1 : public Base { |
| 2957 | public: |
| 2958 | int foo1() override { |
| 2959 | return callee(); // This call is tail-call optimized. |
| 2960 | } |
| 2961 | }; |
| 2962 | ```)reST" ; |
| 2963 | |
| 2964 | static const char AttrDoc_EmptyBases[] = R"reST(The empty_bases attribute permits the compiler to utilize the |
| 2965 | empty-base-optimization more frequently. |
| 2966 | This attribute only applies to struct, class, and union types. |
| 2967 | It is only supported when using the Microsoft C++ ABI.)reST" ; |
| 2968 | |
| 2969 | static const char AttrDoc_EnableIf[] = R"reST(:::{Note} |
| 2970 | Some features of this attribute are experimental. The meaning of |
| 2971 | multiple enable_if attributes on a single declaration is subject to change in |
| 2972 | a future version of clang. Also, the ABI is not standardized and the name |
| 2973 | mangling may change in future versions. To avoid that, use asm labels. |
| 2974 | ::: |
| 2975 | |
| 2976 | The `enable_if` attribute can be placed on function declarations to control |
| 2977 | which overload is selected based on the values of the function's arguments. |
| 2978 | When combined with the `overloadable` attribute, this feature is also |
| 2979 | available in C. |
| 2980 | |
| 2981 | ```c++ |
| 2982 | int isdigit(int c); |
| 2983 | int isdigit(int c) __attribute__((enable_if(c <= -1 || c > 255, "chosen when 'c' is out of range"))) __attribute__((unavailable("'c' must have the value of an unsigned char or EOF"))); |
| 2984 | |
| 2985 | void foo(char c) { |
| 2986 | isdigit(c); |
| 2987 | isdigit(10); |
| 2988 | isdigit(-10); // results in a compile-time error. |
| 2989 | } |
| 2990 | ``` |
| 2991 | |
| 2992 | The enable_if attribute takes two arguments, the first is an expression written |
| 2993 | in terms of the function parameters, the second is a string explaining why this |
| 2994 | overload candidate could not be selected to be displayed in diagnostics. The |
| 2995 | expression is part of the function signature for the purposes of determining |
| 2996 | whether it is a redeclaration (following the rules used when determining |
| 2997 | whether a C++ template specialization is ODR-equivalent), but is not part of |
| 2998 | the type. |
| 2999 | |
| 3000 | The enable_if expression is evaluated as if it were the body of a |
| 3001 | bool-returning constexpr function declared with the arguments of the function |
| 3002 | it is being applied to, then called with the parameters at the call site. If the |
| 3003 | result is false or could not be determined through constant expression |
| 3004 | evaluation, then this overload will not be chosen and the provided string may |
| 3005 | be used in a diagnostic if the compile fails as a result. |
| 3006 | |
| 3007 | Because the enable_if expression is an unevaluated context, there are no global |
| 3008 | state changes, nor the ability to pass information from the enable_if |
| 3009 | expression to the function body. For example, suppose we want calls to |
| 3010 | strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of |
| 3011 | strbuf) only if the size of strbuf can be determined: |
| 3012 | |
| 3013 | ```c++ |
| 3014 | __attribute__((always_inline)) |
| 3015 | static inline size_t strnlen(const char *s, size_t maxlen) |
| 3016 | __attribute__((overloadable)) |
| 3017 | __attribute__((enable_if(__builtin_object_size(s, 0) != -1))), |
| 3018 | "chosen when the buffer size is known but 'maxlen' is not"))) |
| 3019 | { |
| 3020 | return strnlen_chk(s, maxlen, __builtin_object_size(s, 0)); |
| 3021 | } |
| 3022 | ``` |
| 3023 | |
| 3024 | Multiple enable_if attributes may be applied to a single declaration. In this |
| 3025 | case, the enable_if expressions are evaluated from left to right in the |
| 3026 | following manner. First, the candidates whose enable_if expressions evaluate to |
| 3027 | false or cannot be evaluated are discarded. If the remaining candidates do not |
| 3028 | share ODR-equivalent enable_if expressions, the overload resolution is |
| 3029 | ambiguous. Otherwise, enable_if overload resolution continues with the next |
| 3030 | enable_if attribute on the candidates that have not been discarded and have |
| 3031 | remaining enable_if attributes. In this way, we pick the most specific |
| 3032 | overload out of a number of viable overloads using enable_if. |
| 3033 | |
| 3034 | ```c++ |
| 3035 | void f() __attribute__((enable_if(true, ""))); // #1 |
| 3036 | void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2 |
| 3037 | |
| 3038 | void g(int i, int j) __attribute__((enable_if(i, ""))); // #1 |
| 3039 | void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2 |
| 3040 | ``` |
| 3041 | |
| 3042 | In this example, a call to f() is always resolved to #2, as the first enable_if |
| 3043 | expression is ODR-equivalent for both declarations, but #1 does not have another |
| 3044 | enable_if expression to continue evaluating, so the next round of evaluation has |
| 3045 | only a single candidate. In a call to g(1, 1), the call is ambiguous even though |
| 3046 | #2 has more enable_if attributes, because the first enable_if expressions are |
| 3047 | not ODR-equivalent. |
| 3048 | |
| 3049 | Query for this feature with `__has_attribute(enable_if)`. |
| 3050 | |
| 3051 | Note that functions with one or more `enable_if` attributes may not have |
| 3052 | their address taken, unless all of the conditions specified by said |
| 3053 | `enable_if` are constants that evaluate to `true`. For example: |
| 3054 | |
| 3055 | ```c |
| 3056 | const int TrueConstant = 1; |
| 3057 | const int FalseConstant = 0; |
| 3058 | int f(int a) __attribute__((enable_if(a > 0, ""))); |
| 3059 | int g(int a) __attribute__((enable_if(a == 0 || a != 0, ""))); |
| 3060 | int h(int a) __attribute__((enable_if(1, ""))); |
| 3061 | int i(int a) __attribute__((enable_if(TrueConstant, ""))); |
| 3062 | int j(int a) __attribute__((enable_if(FalseConstant, ""))); |
| 3063 | |
| 3064 | void fn() { |
| 3065 | int (*ptr)(int); |
| 3066 | ptr = &f; // error: 'a > 0' is not always true |
| 3067 | ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant |
| 3068 | ptr = &h; // OK: 1 is a truthy constant |
| 3069 | ptr = &i; // OK: 'TrueConstant' is a truthy constant |
| 3070 | ptr = &j; // error: 'FalseConstant' is a constant, but not truthy |
| 3071 | } |
| 3072 | ``` |
| 3073 | |
| 3074 | Because `enable_if` evaluation happens during overload resolution, |
| 3075 | `enable_if` may give unintuitive results when used with templates, depending |
| 3076 | on when overloads are resolved. In the example below, clang will emit a |
| 3077 | diagnostic about no viable overloads for `foo` in `bar`, but not in `baz`: |
| 3078 | |
| 3079 | ```c++ |
| 3080 | double foo(int i) __attribute__((enable_if(i > 0, ""))); |
| 3081 | void *foo(int i) __attribute__((enable_if(i <= 0, ""))); |
| 3082 | template <int I> |
| 3083 | auto bar() { return foo(I); } |
| 3084 | |
| 3085 | template <typename T> |
| 3086 | auto baz() { return foo(T::number); } |
| 3087 | |
| 3088 | struct WithNumber { constexpr static int number = 1; }; |
| 3089 | void callThem() { |
| 3090 | bar<sizeof(WithNumber)>(); |
| 3091 | baz<WithNumber>(); |
| 3092 | } |
| 3093 | ``` |
| 3094 | |
| 3095 | This is because, in `bar`, `foo` is resolved prior to template |
| 3096 | instantiation, so the value for `I` isn't known (thus, both `enable_if` |
| 3097 | conditions for `foo` fail). However, in `baz`, `foo` is resolved during |
| 3098 | template instantiation, so the value for `T::number` is known.)reST" ; |
| 3099 | |
| 3100 | static const char AttrDoc_EnforceTCB[] = R"reST(The `enforce_tcb` attribute can be placed on functions to enforce that a |
| 3101 | trusted compute base (TCB) does not call out of the TCB. This generates a |
| 3102 | warning every time a function not marked with an `enforce_tcb` attribute is |
| 3103 | called from a function with the `enforce_tcb` attribute. A function may be a |
| 3104 | part of multiple TCBs. Invocations through function pointers are currently |
| 3105 | not checked. Builtins are considered to a part of every TCB. |
| 3106 | |
| 3107 | - `enforce_tcb(Name)` indicates that this function is a part of the TCB named `Name`)reST" ; |
| 3108 | |
| 3109 | static const char AttrDoc_EnforceTCBLeaf[] = R"reST(The `enforce_tcb_leaf` attribute satisfies the requirement enforced by |
| 3110 | `enforce_tcb` for the marked function to be in the named TCB but does not |
| 3111 | continue to check the functions called from within the leaf function. |
| 3112 | |
| 3113 | - `enforce_tcb_leaf(Name)` indicates that this function is a part of the TCB named `Name`)reST" ; |
| 3114 | |
| 3115 | static const char AttrDoc_EnumExtensibility[] = R"reST(Attribute `enum_extensibility` is used to distinguish between enum definitions |
| 3116 | that are extensible and those that are not. The attribute can take either |
| 3117 | `closed` or `open` as an argument. `closed` indicates a variable of the |
| 3118 | enum type takes a value that corresponds to one of the enumerators listed in the |
| 3119 | enum definition or, when the enum is annotated with `flag_enum`, a value that |
| 3120 | can be constructed using values corresponding to the enumerators. `open` |
| 3121 | indicates a variable of the enum type can take any values allowed by the |
| 3122 | standard and instructs clang to be more lenient when issuing warnings. |
| 3123 | |
| 3124 | ```c |
| 3125 | enum __attribute__((enum_extensibility(closed))) ClosedEnum { |
| 3126 | A0, A1 |
| 3127 | }; |
| 3128 | |
| 3129 | enum __attribute__((enum_extensibility(open))) OpenEnum { |
| 3130 | B0, B1 |
| 3131 | }; |
| 3132 | |
| 3133 | enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum { |
| 3134 | C0 = 1 << 0, C1 = 1 << 1 |
| 3135 | }; |
| 3136 | |
| 3137 | enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum { |
| 3138 | D0 = 1 << 0, D1 = 1 << 1 |
| 3139 | }; |
| 3140 | |
| 3141 | void foo1() { |
| 3142 | enum ClosedEnum ce; |
| 3143 | enum OpenEnum oe; |
| 3144 | enum ClosedFlagEnum cfe; |
| 3145 | enum OpenFlagEnum ofe; |
| 3146 | |
| 3147 | ce = A1; // no warnings |
| 3148 | ce = 100; // warning issued |
| 3149 | oe = B1; // no warnings |
| 3150 | oe = 100; // no warnings |
| 3151 | cfe = C0 | C1; // no warnings |
| 3152 | cfe = C0 | C1 | 4; // warning issued |
| 3153 | ofe = D0 | D1; // no warnings |
| 3154 | ofe = D0 | D1 | 4; // no warnings |
| 3155 | } |
| 3156 | ```)reST" ; |
| 3157 | |
| 3158 | static const char AttrDoc_Error[] = R"reST(The `error` and `warning` function attributes can be used to specify a |
| 3159 | custom diagnostic to be emitted when a call to such a function is not |
| 3160 | eliminated via optimizations. This can be used to create compile time |
| 3161 | assertions that depend on optimizations, while providing diagnostics |
| 3162 | pointing to precise locations of the call site in the source. |
| 3163 | |
| 3164 | ```c++ |
| 3165 | __attribute__((warning("oh no"))) void dontcall(); |
| 3166 | void foo() { |
| 3167 | if (someCompileTimeAssertionThatsTrue) |
| 3168 | dontcall(); // Warning |
| 3169 | |
| 3170 | dontcall(); // Warning |
| 3171 | |
| 3172 | if (someCompileTimeAssertionThatsFalse) |
| 3173 | dontcall(); // No Warning |
| 3174 | sizeof(dontcall()); // No Warning |
| 3175 | } |
| 3176 | ``` |
| 3177 | |
| 3178 | When the call occurs through inlined functions, the |
| 3179 | `-fdiagnostics-show-inlining-chain` option can be used to show the |
| 3180 | inlining chain that led to the call. This helps identify which call site |
| 3181 | triggered the diagnostic when the attributed function is called from |
| 3182 | multiple locations through inline functions. |
| 3183 | |
| 3184 | When enabled, this option automatically uses debug info for accurate source |
| 3185 | locations if available (`-gline-directives-only` (implicitly enabled at |
| 3186 | `-g1`) or higher), or falls back to a heuristic based on metadata tracking. |
| 3187 | When falling back, a note is emitted suggesting `-gline-directives-only` for |
| 3188 | more accurate locations.)reST" ; |
| 3189 | |
| 3190 | static const char AttrDoc_ExcludeFromExplicitInstantiation[] = R"reST(The `exclude_from_explicit_instantiation` attribute opts-out a member of a |
| 3191 | class template from being part of explicit template instantiations of that |
| 3192 | class template. This means that an explicit instantiation will not instantiate |
| 3193 | members of the class template marked with the attribute, but also that code |
| 3194 | where an extern template declaration of the enclosing class template is visible |
| 3195 | will not take for granted that an external instantiation of the class template |
| 3196 | would provide those members (which would otherwise be a link error, since the |
| 3197 | explicit instantiation won't provide those members). For example, let's say we |
| 3198 | don't want the `data()` method to be part of libc++'s ABI. To make sure it |
| 3199 | is not exported from the dylib, we give it hidden visibility: |
| 3200 | |
| 3201 | ```c++ |
| 3202 | // in <string> |
| 3203 | template <class CharT> |
| 3204 | class basic_string { |
| 3205 | public: |
| 3206 | __attribute__((__visibility__("hidden"))) |
| 3207 | const value_type* data() const noexcept { ... } |
| 3208 | }; |
| 3209 | |
| 3210 | template class basic_string<char>; |
| 3211 | ``` |
| 3212 | |
| 3213 | Since an explicit template instantiation declaration for `basic_string<char>` |
| 3214 | is provided, the compiler is free to assume that `basic_string<char>::data()` |
| 3215 | will be provided by another translation unit, and it is free to produce an |
| 3216 | external call to this function. However, since `data()` has hidden visibility |
| 3217 | and the explicit template instantiation is provided in a shared library (as |
| 3218 | opposed to simply another translation unit), `basic_string<char>::data()` |
| 3219 | won't be found and a link error will ensue. This happens because the compiler |
| 3220 | assumes that `basic_string<char>::data()` is part of the explicit template |
| 3221 | instantiation declaration, when it really isn't. To tell the compiler that |
| 3222 | `data()` is not part of the explicit template instantiation declaration, the |
| 3223 | `exclude_from_explicit_instantiation` attribute can be used: |
| 3224 | |
| 3225 | ```c++ |
| 3226 | // in <string> |
| 3227 | template <class CharT> |
| 3228 | class basic_string { |
| 3229 | public: |
| 3230 | __attribute__((__visibility__("hidden"))) |
| 3231 | __attribute__((exclude_from_explicit_instantiation)) |
| 3232 | const value_type* data() const noexcept { ... } |
| 3233 | }; |
| 3234 | |
| 3235 | template class basic_string<char>; |
| 3236 | ``` |
| 3237 | |
| 3238 | Now, the compiler won't assume that `basic_string<char>::data()` is provided |
| 3239 | externally despite there being an explicit template instantiation declaration: |
| 3240 | the compiler will implicitly instantiate `basic_string<char>::data()` in the |
| 3241 | TUs where it is used. |
| 3242 | |
| 3243 | This attribute can be used on static and non-static member functions of class |
| 3244 | templates, static data members of class templates and member classes of class |
| 3245 | templates. |
| 3246 | |
| 3247 | **Interaction with \_\_declspec(dllexport/dllimport)** |
| 3248 | |
| 3249 | For a DLL platform (i.e., Windows), this attribute also means "this member will |
| 3250 | never be exported or imported". Despite its name, this semantics applies to |
| 3251 | implicit instantiations and non-template entities as well. |
| 3252 | |
| 3253 | ```c++ |
| 3254 | // in <exception> |
| 3255 | class __declspec(dllimport) nested_exception { |
| 3256 | ... |
| 3257 | public: |
| 3258 | __attribute__((exclude_from_explicit_instantiation)) |
| 3259 | exception_ptr nested_ptr() const noexcept { ... } |
| 3260 | }; |
| 3261 | ``` |
| 3262 | |
| 3263 | In this case, `nested_exception::nested_ptr` will never be attempted to be |
| 3264 | imported.)reST" ; |
| 3265 | |
| 3266 | static const char AttrDoc_ExplicitInit[] = R"reST(The `clang::require_explicit_initialization` attribute indicates that a |
| 3267 | field of an aggregate must be initialized explicitly by the user when an object |
| 3268 | of the aggregate type is constructed. The attribute supports both C and C++, |
| 3269 | but its usage is invalid on non-aggregates. |
| 3270 | |
| 3271 | Note that this attribute is *not* a memory safety feature, and is *not* intended |
| 3272 | to guard against use of uninitialized memory. |
| 3273 | |
| 3274 | Rather, it is intended for use in "parameter-objects", used to simulate, |
| 3275 | for example, the passing of named parameters. |
| 3276 | Except inside unevaluated contexts, the attribute generates a warning when |
| 3277 | explicit initializers for such variables are not provided (this occurs |
| 3278 | regardless of whether any in-class field initializers exist): |
| 3279 | |
| 3280 | ```c++ |
| 3281 | struct Buffer { |
| 3282 | void *address [[clang::require_explicit_initialization]]; |
| 3283 | size_t length [[clang::require_explicit_initialization]] = 0; |
| 3284 | }; |
| 3285 | |
| 3286 | struct ArrayIOParams { |
| 3287 | size_t count [[clang::require_explicit_initialization]]; |
| 3288 | size_t element_size [[clang::require_explicit_initialization]]; |
| 3289 | int flags = 0; |
| 3290 | }; |
| 3291 | |
| 3292 | size_t ReadArray(FILE *file, struct Buffer buffer, |
| 3293 | struct ArrayIOParams params); |
| 3294 | |
| 3295 | int main() { |
| 3296 | unsigned int buf[512]; |
| 3297 | ReadArray(stdin, { |
| 3298 | buf |
| 3299 | // warning: field 'length' is not explicitly initialized |
| 3300 | }, { |
| 3301 | .count = sizeof(buf) / sizeof(*buf), |
| 3302 | // warning: field 'element_size' is not explicitly initialized |
| 3303 | // (Note that a missing initializer for 'flags' is not diagnosed, because |
| 3304 | // the field is not marked as requiring explicit initialization.) |
| 3305 | }); |
| 3306 | } |
| 3307 | ```)reST" ; |
| 3308 | |
| 3309 | static const char AttrDoc_ExtVectorType[] = R"reST(The `ext_vector_type(N)` attribute specifies that a type is a vector with N |
| 3310 | elements, directly mapping to an LLVM vector type. Originally from OpenCL, it |
| 3311 | allows element access the array subscript operator `[]`, `sN` where N is |
| 3312 | a hexadecimal value, or `x, y, z, w` for graphics-style indexing. |
| 3313 | This attribute enables efficient SIMD operations and is usable in |
| 3314 | general-purpose code. |
| 3315 | |
| 3316 | ```c++ |
| 3317 | template <typename T, uint32_t N> |
| 3318 | constexpr T simd_reduce(T [[clang::ext_vector_type(N)]] v) { |
| 3319 | static_assert((N & (N - 1)) == 0, "N must be a power of two"); |
| 3320 | if constexpr (N == 1) |
| 3321 | return v[0]; |
| 3322 | else |
| 3323 | return simd_reduce<T, N / 2>(v.hi + v.lo); |
| 3324 | } |
| 3325 | ``` |
| 3326 | |
| 3327 | The vector type also supports swizzling up to sixteen elements. This can be done |
| 3328 | using the object accessors. The OpenCL documentation lists all of the accepted |
| 3329 | values. |
| 3330 | |
| 3331 | ```c++ |
| 3332 | using f16_x16 = _Float16 __attribute__((ext_vector_type(16))); |
| 3333 | |
| 3334 | f16_x16 reverse(f16_x16 v) { return v.sfedcba9876543210; } |
| 3335 | ``` |
| 3336 | |
| 3337 | See the OpenCL documentation for some more complete examples.)reST" ; |
| 3338 | |
| 3339 | static const char AttrDoc_ExternalSourceSymbol[] = R"reST(The `external_source_symbol` attribute specifies that a declaration originates |
| 3340 | from an external source and describes the nature of that source. |
| 3341 | |
| 3342 | The fact that Clang is capable of recognizing declarations that were defined |
| 3343 | externally can be used to provide better tooling support for mixed-language |
| 3344 | projects or projects that rely on auto-generated code. For instance, an IDE that |
| 3345 | uses Clang and that supports mixed-language projects can use this attribute to |
| 3346 | provide a correct 'jump-to-definition' feature. For a concrete example, |
| 3347 | consider a protocol that's defined in a Swift file: |
| 3348 | |
| 3349 | ```swift |
| 3350 | @objc public protocol SwiftProtocol { |
| 3351 | func method() |
| 3352 | } |
| 3353 | ``` |
| 3354 | |
| 3355 | This protocol can be used from Objective-C code by including a header file that |
| 3356 | was generated by the Swift compiler. The declarations in that header can use |
| 3357 | the `external_source_symbol` attribute to make Clang aware of the fact |
| 3358 | that `SwiftProtocol` actually originates from a Swift module: |
| 3359 | |
| 3360 | ```objc |
| 3361 | __attribute__((external_source_symbol(language="Swift",defined_in="module"))) |
| 3362 | @protocol SwiftProtocol |
| 3363 | @required |
| 3364 | - (void) method; |
| 3365 | @end |
| 3366 | ``` |
| 3367 | |
| 3368 | Consequently, when 'jump-to-definition' is performed at a location that |
| 3369 | references `SwiftProtocol`, the IDE can jump to the original definition in |
| 3370 | the Swift source file rather than jumping to the Objective-C declaration in the |
| 3371 | auto-generated header file. |
| 3372 | |
| 3373 | The `external_source_symbol` attribute is a comma-separated list that includes |
| 3374 | clauses that describe the origin and the nature of the particular declaration. |
| 3375 | Those clauses can be: |
| 3376 | |
| 3377 | language=*string-literal* |
| 3378 | |
| 3379 | : The name of the source language in which this declaration was defined. |
| 3380 | |
| 3381 | defined_in=*string-literal* |
| 3382 | |
| 3383 | : The name of the source container in which the declaration was defined. The |
| 3384 | exact definition of source container is language-specific, e.g. Swift's |
| 3385 | source containers are modules, so `defined_in` should specify the Swift |
| 3386 | module name. |
| 3387 | |
| 3388 | USR=*string-literal* |
| 3389 | |
| 3390 | : String that specifies a unified symbol resolution (USR) value for this |
| 3391 | declaration. USR string uniquely identifies this particular declaration, and |
| 3392 | is typically used when constructing an index of a codebase. |
| 3393 | The USR value in this attribute is expected to be generated by an external |
| 3394 | compiler that compiled the native declaration using its original source |
| 3395 | language. The exact format of the USR string and its other attributes |
| 3396 | are determined by the specification of this declaration's source language. |
| 3397 | When not specified, Clang's indexer will use the Clang USR for this symbol. |
| 3398 | User can query to see if Clang supports the use of the `USR` clause in |
| 3399 | the `external_source_symbol` attribute with |
| 3400 | `__has_attribute(external_source_symbol) >= 20230206`. |
| 3401 | |
| 3402 | generated_declaration |
| 3403 | |
| 3404 | : This declaration was automatically generated by some tool. |
| 3405 | |
| 3406 | The clauses can be specified in any order. The clauses that are listed above are |
| 3407 | all optional, but the attribute has to have at least one clause.)reST" ; |
| 3408 | |
| 3409 | static const char AttrDoc_FallThrough[] = R"reST(The `fallthrough` (or `clang::fallthrough`) attribute is used |
| 3410 | to annotate intentional fall-through |
| 3411 | between switch labels. It can only be applied to a null statement placed at a |
| 3412 | point of execution between any statement and the next switch label. It is |
| 3413 | common to mark these places with a specific comment, but this attribute is |
| 3414 | meant to replace comments with a more strict annotation, which can be checked |
| 3415 | by the compiler. This attribute doesn't change semantics of the code and can |
| 3416 | be used wherever an intended fall-through occurs. It is designed to mimic |
| 3417 | control-flow statements like `break;`, so it can be placed in most places |
| 3418 | where `break;` can, but only if there are no statements on the execution path |
| 3419 | between it and the next switch label. |
| 3420 | |
| 3421 | By default, Clang does not warn on unannotated fallthrough from one `switch` |
| 3422 | case to another. Diagnostics on fallthrough without a corresponding annotation |
| 3423 | can be enabled with the `-Wimplicit-fallthrough` argument. |
| 3424 | |
| 3425 | Here is an example: |
| 3426 | |
| 3427 | ```c++ |
| 3428 | // compile with -Wimplicit-fallthrough |
| 3429 | switch (n) { |
| 3430 | case 22: |
| 3431 | case 33: // no warning: no statements between case labels |
| 3432 | f(); |
| 3433 | case 44: // warning: unannotated fall-through |
| 3434 | g(); |
| 3435 | [[clang::fallthrough]]; |
| 3436 | case 55: // no warning |
| 3437 | if (x) { |
| 3438 | h(); |
| 3439 | break; |
| 3440 | } |
| 3441 | else { |
| 3442 | i(); |
| 3443 | [[clang::fallthrough]]; |
| 3444 | } |
| 3445 | case 66: // no warning |
| 3446 | p(); |
| 3447 | [[clang::fallthrough]]; // warning: fallthrough annotation does not |
| 3448 | // directly precede case label |
| 3449 | q(); |
| 3450 | case 77: // warning: unannotated fall-through |
| 3451 | r(); |
| 3452 | } |
| 3453 | ```)reST" ; |
| 3454 | |
| 3455 | static const char AttrDoc_FastCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a |
| 3456 | function to use ECX and EDX as register parameters and clear parameters off of |
| 3457 | the stack on return. This convention does not support variadic calls or |
| 3458 | unprototyped functions in C, and has no effect on x86_64 targets. This calling |
| 3459 | convention is supported primarily for compatibility with existing code. Users |
| 3460 | seeking register parameters should use the `regparm` attribute, which does |
| 3461 | not require callee-cleanup. See the documentation for [\_\_fastcall][__fastcall] on MSDN. |
| 3462 | |
| 3463 | [__fastcall]: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx)reST" ; |
| 3464 | |
| 3465 | static const char AttrDoc_Final[] = R"reST()reST" ; |
| 3466 | |
| 3467 | static const char AttrDoc_FlagEnum[] = R"reST(This attribute can be added to an enumerator to signal to the compiler that it |
| 3468 | is intended to be used as a flag type. This will cause the compiler to assume |
| 3469 | that the range of the type includes all of the values that you can get by |
| 3470 | manipulating bits of the enumerator when issuing warnings.)reST" ; |
| 3471 | |
| 3472 | static const char AttrDoc_Flatten[] = R"reST(The `flatten` attribute causes calls within the attributed function to |
| 3473 | be inlined unless it is impossible to do so, for example if the body of the |
| 3474 | callee is unavailable or if the callee has the `noinline` attribute.)reST" ; |
| 3475 | |
| 3476 | static const char AttrDoc_Format[] = R"reST(Clang supports the `format` attribute, which indicates that the function |
| 3477 | accepts (among other possibilities) a `printf` or `scanf`-like format string |
| 3478 | and corresponding arguments or a `va_list` that contains these arguments. |
| 3479 | |
| 3480 | Please see [GCC documentation about format attribute](http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html) to find details |
| 3481 | about attribute syntax. |
| 3482 | |
| 3483 | Clang implements two kinds of checks with this attribute. |
| 3484 | |
| 3485 | 1. Clang checks that the function with the `format` attribute is called with |
| 3486 | a format string that uses format specifiers that are allowed, and that |
| 3487 | arguments match the format string. This is the `-Wformat` warning, it is |
| 3488 | on by default. |
| 3489 | |
| 3490 | 2. Clang checks that the format string argument is a literal string. This is |
| 3491 | the `-Wformat-nonliteral` warning, it is off by default. |
| 3492 | |
| 3493 | Clang implements this mostly the same way as GCC, but there is a difference |
| 3494 | for functions that accept a `va_list` argument (for example, `vprintf`). |
| 3495 | GCC does not emit `-Wformat-nonliteral` warning for calls to such |
| 3496 | functions. Clang does not warn if the format string comes from a function |
| 3497 | parameter, where the function is annotated with a compatible attribute, |
| 3498 | otherwise it warns. For example: |
| 3499 | |
| 3500 | ```c |
| 3501 | __attribute__((__format__ (__scanf__, 1, 3))) |
| 3502 | void foo(const char* s, char *buf, ...) { |
| 3503 | va_list ap; |
| 3504 | va_start(ap, buf); |
| 3505 | |
| 3506 | vprintf(s, ap); // warning: format string is not a string literal |
| 3507 | } |
| 3508 | ``` |
| 3509 | |
| 3510 | In this case we warn because `s` contains a format string for a |
| 3511 | `scanf`-like function, but it is passed to a `printf`-like function. |
| 3512 | |
| 3513 | If the attribute is removed, clang still warns, because the format string is |
| 3514 | not a string literal. |
| 3515 | |
| 3516 | Another example: |
| 3517 | |
| 3518 | ```c |
| 3519 | __attribute__((__format__ (__printf__, 1, 3))) |
| 3520 | void foo(const char* s, char *buf, ...) { |
| 3521 | va_list ap; |
| 3522 | va_start(ap, buf); |
| 3523 | |
| 3524 | vprintf(s, ap); // warning |
| 3525 | } |
| 3526 | ``` |
| 3527 | |
| 3528 | In this case Clang does not warn because the format string `s` and |
| 3529 | the corresponding arguments are annotated. If the arguments are |
| 3530 | incorrect, the caller of `foo` will receive a warning. |
| 3531 | |
| 3532 | As an extension to GCC's behavior, Clang accepts the `format` attribute on |
| 3533 | non-variadic functions. Clang checks non-variadic format functions for the same |
| 3534 | classes of issues that can be found on variadic functions, as controlled by the |
| 3535 | same warning flags, except that the types of formatted arguments is forced by |
| 3536 | the function signature. For example: |
| 3537 | |
| 3538 | ```c |
| 3539 | __attribute__((__format__(__printf__, 1, 2))) |
| 3540 | void fmt(const char *s, const char *a, int b); |
| 3541 | |
| 3542 | void bar(void) { |
| 3543 | fmt("%s %i", "hello", 123); // OK |
| 3544 | fmt("%i %g", "hello", 123); // warning: arguments don't match format |
| 3545 | extern const char *fmt; |
| 3546 | fmt(fmt, "hello", 123); // warning: format string is not a string literal |
| 3547 | } |
| 3548 | ``` |
| 3549 | |
| 3550 | When using the format attribute on a variadic function, the first data parameter |
| 3551 | \_must\_ be the index of the ellipsis in the parameter list. Clang will generate |
| 3552 | a diagnostic otherwise, as it wouldn't be possible to forward that argument list |
| 3553 | to `printf`-family functions. For instance, this is an error: |
| 3554 | |
| 3555 | ```c |
| 3556 | __attribute__((__format__(__printf__, 1, 2))) |
| 3557 | void fmt(const char *s, int b, ...); |
| 3558 | // ^ error: format attribute parameter 3 is out of bounds |
| 3559 | // (must be __printf__, 1, 3) |
| 3560 | ``` |
| 3561 | |
| 3562 | Using the `format` attribute on a non-variadic function emits a GCC |
| 3563 | compatibility diagnostic.)reST" ; |
| 3564 | |
| 3565 | static const char AttrDoc_FormatArg[] = R"reST(No documentation.)reST" ; |
| 3566 | |
| 3567 | static const char AttrDoc_FormatMatches[] = R"reST(The `format` attribute is the basis for the enforcement of diagnostics in the |
| 3568 | `-Wformat` family, but it only handles the case where the format string is |
| 3569 | passed along with the arguments it is going to format. It cannot handle the case |
| 3570 | where the format string and the format arguments are passed separately from each |
| 3571 | other. For instance: |
| 3572 | |
| 3573 | ```c |
| 3574 | static const char *first_name; |
| 3575 | static double todays_temperature; |
| 3576 | static int wind_speed; |
| 3577 | |
| 3578 | void say_hi(const char *fmt) { |
| 3579 | printf(fmt, first_name, todays_temperature); |
| 3580 | // ^ warning: format string is not a string literal |
| 3581 | printf(fmt, first_name, wind_speed); |
| 3582 | // ^ warning: format string is not a string literal |
| 3583 | } |
| 3584 | |
| 3585 | int main() { |
| 3586 | say_hi("hello %s, it is %g degrees outside"); |
| 3587 | say_hi("hello %s, it is %d degrees outside!"); |
| 3588 | // ^ no diagnostic, but %d cannot format doubles |
| 3589 | } |
| 3590 | ``` |
| 3591 | |
| 3592 | In this example, `fmt` is expected to format a `const char *` and a |
| 3593 | `double`, but these values are not passed to `say_hi`. Without the |
| 3594 | `format` attribute (which cannot apply in this case), the -Wformat-nonliteral |
| 3595 | diagnostic unnecessarily triggers in the body of `say_hi`, and incorrect |
| 3596 | `say_hi` call sites do not trigger a diagnostic. |
| 3597 | |
| 3598 | To complement the `format` attribute, Clang also defines the |
| 3599 | `format_matches` attribute. Its syntax is similar to the `format` |
| 3600 | attribute's, but instead of taking the index of the first formatted value |
| 3601 | argument, it takes a C string literal with the expected specifiers: |
| 3602 | |
| 3603 | ```c |
| 3604 | static const char *first_name; |
| 3605 | static double todays_temperature; |
| 3606 | static int wind_speed; |
| 3607 | |
| 3608 | __attribute__((__format_matches__(printf, 1, "%s %g"))) |
| 3609 | void say_hi(const char *fmt) { |
| 3610 | printf(fmt, first_name, todays_temperature); // no dignostic |
| 3611 | printf(fmt, first_name, wind_speed); // warning: format specifies type 'int' but the argument has type 'double' |
| 3612 | } |
| 3613 | |
| 3614 | int main() { |
| 3615 | say_hi("hello %s, it is %g degrees outside"); |
| 3616 | say_hi("it is %g degrees outside, have a good day %s!"); |
| 3617 | // warning: format specifies 'double' where 'const char *' is required |
| 3618 | // warning: format specifies 'const char *' where 'double' is required |
| 3619 | } |
| 3620 | ``` |
| 3621 | |
| 3622 | The third argument to `format_matches` is expected to evaluate to a **C string |
| 3623 | literal** even when the format string would normally be a different type for the |
| 3624 | given flavor, like a `CFStringRef` or a `NSString *`. |
| 3625 | |
| 3626 | The only requirement on the format string literal is that it has specifiers |
| 3627 | that are compatible with the arguments that will be used. It can contain |
| 3628 | arbitrary non-format characters. For instance, for the purposes of compile-time |
| 3629 | validation, `"%s scored %g%% on her test"` and `"%s%g"` are interchangeable |
| 3630 | as the format string argument. As a means of self-documentation, users may |
| 3631 | prefer the former when it provides a useful example of an expected format |
| 3632 | string. |
| 3633 | |
| 3634 | In the implementation of a function with the `format_matches` attribute, |
| 3635 | format verification works as if the format string was identical to the one |
| 3636 | specified in the attribute. |
| 3637 | |
| 3638 | ```c |
| 3639 | __attribute__((__format_matches__(printf, 1, "%s %g"))) |
| 3640 | void say_hi(const char *fmt) { |
| 3641 | printf(fmt, "person", 546); |
| 3642 | // ^ warning: format specifies type 'double' but the |
| 3643 | // argument has type 'int' |
| 3644 | // note: format string is defined here: |
| 3645 | // __attribute__((__format_matches__(printf, 1, "%s %g"))) |
| 3646 | // ^~ |
| 3647 | } |
| 3648 | ``` |
| 3649 | |
| 3650 | At the call sites of functions with the `format_matches` attribute, format |
| 3651 | verification instead compares the two format strings to evaluate their |
| 3652 | equivalence. Each format flavor defines equivalence between format specifiers. |
| 3653 | Generally speaking, two specifiers are equivalent if they format the same type. |
| 3654 | For instance, in the `printf` flavor, `%2i` and `%-0.5d` are compatible. |
| 3655 | When `-Wformat-signedness` is disabled, `%d` and `%u` are compatible. For |
| 3656 | a negative example, `%ld` is incompatible with `%d`. |
| 3657 | |
| 3658 | Do note the following un-obvious cases: |
| 3659 | |
| 3660 | - Passing `NULL` as the format string does not trigger format diagnostics. |
| 3661 | - When the format string is not NULL, it cannot \_miss\_ specifiers, even in |
| 3662 | trailing positions. For instance, `%d` is not accepted when the required |
| 3663 | format is `%d %d %d`. |
| 3664 | - While checks for the `format` attribute tolerate sone size mismatches |
| 3665 | that standard argument promotion renders immaterial (such as formatting an |
| 3666 | `int` with `%hhd`, which specifies a `char`-sized integer), checks for |
| 3667 | `format_matches` require specified argument sizes to match exactly. |
| 3668 | - Format strings expecting a variable modifier (such as `%*s`) are |
| 3669 | incompatible with format strings that would itemize the variable modifiers |
| 3670 | (such as `%i %s`), even if the two specify ABI-compatible argument lists. |
| 3671 | - All pointer specifiers, modifiers aside, are mutually incompatible. For |
| 3672 | instance, `%s` is not compatible with `%p`, and `%p` is not compatible |
| 3673 | with `%n`, and `%hhn` is incompatible with `%s`, even if the pointers |
| 3674 | are ABI-compatible or identical on the selected platform. However, `%0.5s` |
| 3675 | is compatible with `%s`, since the difference only exists in modifier flags. |
| 3676 | This is not overridable with `-Wformat-pedantic` or its inverse, which |
| 3677 | control similar behavior in `-Wformat`. |
| 3678 | |
| 3679 | At this time, clang implements `format_matches` only for format types in the |
| 3680 | `printf` family. This includes variants such as Apple's NSString format and |
| 3681 | the FreeBSD `kprintf`, but excludes `scanf`. Using a known but unsupported |
| 3682 | format silently fails in order to be compatible with other implementations that |
| 3683 | would support these formats.)reST" ; |
| 3684 | |
| 3685 | static const char AttrDoc_FunctionReturnThunks[] = R"reST(The attribute `function_return` can replace return instructions with jumps to |
| 3686 | target-specific symbols. This attribute supports 2 possible values, |
| 3687 | corresponding to the values supported by the `-mfunction-return=` command |
| 3688 | line flag: |
| 3689 | |
| 3690 | - `__attribute__((function_return("keep")))` to disable related transforms. |
| 3691 | This is useful for undoing global setting from `-mfunction-return=` locally |
| 3692 | for individual functions. |
| 3693 | - `__attribute__((function_return("thunk-extern")))` to replace returns with |
| 3694 | jumps, while NOT emitting the thunk. |
| 3695 | |
| 3696 | The values `thunk` and `thunk-inline` from GCC are not supported. |
| 3697 | |
| 3698 | The symbol used for `thunk-extern` is target specific: |
| 3699 | \* X86: `__x86_return_thunk` |
| 3700 | |
| 3701 | As such, this function attribute is currently only supported on X86 targets.)reST" ; |
| 3702 | |
| 3703 | static const char AttrDoc_GCCStruct[] = R"reST(The `ms_struct` and `gcc_struct` attributes request the compiler to enter a |
| 3704 | special record layout compatibility mode which mimics the layout of Microsoft or |
| 3705 | Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the |
| 3706 | requested ABI, the attribute does nothing. However, if it does not, annotated |
| 3707 | structure or class is laid out in a special compatibility mode, which slightly |
| 3708 | changes offsets for fields and bit-fields. The intention is to match the layout |
| 3709 | of the requested ABI for structures which only use C features. |
| 3710 | |
| 3711 | Note that the default behavior can be controlled by `-mms-bitfields` and |
| 3712 | `-mno-ms-bitfields` switches and via `#pragma ms_struct`. |
| 3713 | |
| 3714 | The primary difference is for bitfields, where the MS variant only packs |
| 3715 | adjacent fields into the same allocation unit if they have integral types |
| 3716 | of the same size, while the GCC/Itanium variant packs all fields in a bitfield |
| 3717 | tightly.)reST" ; |
| 3718 | |
| 3719 | static const char AttrDoc_GNUInline[] = R"reST(The `gnu_inline` changes the meaning of `extern inline` to use GNU inline |
| 3720 | semantics, meaning: |
| 3721 | |
| 3722 | - If any declaration that is declared `inline` is not declared `extern`, |
| 3723 | then the `inline` keyword is just a hint. In particular, an out-of-line |
| 3724 | definition is still emitted for a function with external linkage, even if all |
| 3725 | call sites are inlined, unlike in C99 and C++ inline semantics. |
| 3726 | - If all declarations that are declared `inline` are also declared |
| 3727 | `extern`, then the function body is present only for inlining and no |
| 3728 | out-of-line version is emitted. |
| 3729 | |
| 3730 | Some important consequences: `static inline` emits an out-of-line |
| 3731 | version if needed, a plain `inline` definition emits an out-of-line version |
| 3732 | always, and an `extern inline` definition (in a header) followed by a |
| 3733 | (non-`extern`) `inline` declaration in a source file emits an out-of-line |
| 3734 | version of the function in that source file but provides the function body for |
| 3735 | inlining to all includers of the header. |
| 3736 | |
| 3737 | Either `__GNUC_GNU_INLINE__` (GNU inline semantics) or |
| 3738 | `__GNUC_STDC_INLINE__` (C99 semantics) will be defined (they are mutually |
| 3739 | exclusive). If `__GNUC_STDC_INLINE__` is defined, then the `gnu_inline` |
| 3740 | function attribute can be used to get GNU inline semantics on a per function |
| 3741 | basis. If `__GNUC_GNU_INLINE__` is defined, then the translation unit is |
| 3742 | already being compiled with GNU inline semantics as the implied default. It is |
| 3743 | unspecified which macro is defined in a C++ compilation. |
| 3744 | |
| 3745 | GNU inline semantics are the default behavior with `-std=gnu89`, |
| 3746 | `-std=c89`, `-fgnu89-inline`, or `-std=iso9899:199409`.)reST" ; |
| 3747 | |
| 3748 | static const char AttrDoc_GuardedBy[] = R"reST(No documentation.)reST" ; |
| 3749 | |
| 3750 | static const char AttrDoc_GuardedVar[] = R"reST(No documentation.)reST" ; |
| 3751 | |
| 3752 | static const char AttrDoc_HIPManaged[] = R"reST(The `__managed__` attribute can be applied to a global variable declaration in HIP. |
| 3753 | A managed variable is emitted as an undefined global symbol in the device binary and is |
| 3754 | registered by `__hipRegisterManagedVar` in init functions. The HIP runtime allocates |
| 3755 | managed memory and uses it to define the symbol when loading the device binary. |
| 3756 | A managed variable can be accessed in both device and host code.)reST" ; |
| 3757 | |
| 3758 | static const char AttrDoc_HLSLAppliedSemantic[] = R"reST()reST" ; |
| 3759 | |
| 3760 | static const char AttrDoc_HLSLAssociatedResourceDecl[] = R"reST()reST" ; |
| 3761 | |
| 3762 | static const char AttrDoc_HLSLColumnMajor[] = R"reST(The `row_major` and `column_major` keywords specify the memory layout |
| 3763 | of an HLSL matrix type. |
| 3764 | |
| 3765 | - `row_major`: Matrices are stored in memory row-by-row. |
| 3766 | - `column_major`: Matrices are stored in memory column-by-column (default). |
| 3767 | |
| 3768 | Example: |
| 3769 | |
| 3770 | ```hlsl |
| 3771 | row_major float2x2 myMatrix; |
| 3772 | ```)reST" ; |
| 3773 | |
| 3774 | static const char AttrDoc_HLSLContainedType[] = R"reST(The ``hlsl::contained_type`` attribute specifies the type of the HLSL resource |
| 3775 | represented by a member variable of type ``__hlsl_resource_t``. |
| 3776 | |
| 3777 | This attribute is only valid for resource handles, and is an implementation |
| 3778 | detail of clang's HLSL implementation. For more information see `HLSL Resource |
| 3779 | Types`_ |
| 3780 | |
| 3781 | .. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST" ; |
| 3782 | |
| 3783 | static const char AttrDoc_HLSLControlFlowHint[] = R"reST(The ``branch`` and ``flatten`` attributes can be applied to *if* and *switch* |
| 3784 | statements in the HLSL language mode to provide hints for how the backend |
| 3785 | should execute them. |
| 3786 | |
| 3787 | - ``branch`` means that control flow is preferred. The condition should be |
| 3788 | evaluated first and we should only execute the block guarded by it. |
| 3789 | |
| 3790 | - ``flatten`` means that control flow should be avoided. All blocks should be |
| 3791 | executed and variables that are modified should be conditionally assigned. |
| 3792 | |
| 3793 | These control flow hints are preserved through the compilation and emitted in a |
| 3794 | backend-specific way. |
| 3795 | |
| 3796 | For details, see the Direct3D documentation for `if Statement`_ and `switch Statement`_. |
| 3797 | |
| 3798 | .. _`if Statement`: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-if |
| 3799 | .. _`switch Statement`: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-switchhttps://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-switch)reST" ; |
| 3800 | |
| 3801 | static const char AttrDoc_HLSLGroupSharedAddressSpace[] = R"reST(HLSL enables threads of a compute shader to exchange values via shared memory. |
| 3802 | HLSL provides barrier primitives such as GroupMemoryBarrierWithGroupSync, |
| 3803 | and so on to ensure the correct ordering of reads and writes to shared memory |
| 3804 | in the shader and to avoid data races. |
| 3805 | Here's an example to declare a groupshared variable. |
| 3806 | |
| 3807 | ```c++ |
| 3808 | groupshared GSData data[5*5*1]; |
| 3809 | ``` |
| 3810 | |
| 3811 | The full documentation is available here: <https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-syntax#group-shared>)reST" ; |
| 3812 | |
| 3813 | static const char AttrDoc_HLSLIsArray[] = R"reST(The ``hlsl::is_array`` attribute specifies that the HLSL resource represented |
| 3814 | by a member variable of type ``__hlsl_resource_t`` has array dimensions. |
| 3815 | |
| 3816 | This attribute is only valid for resource handles, and is an implementation |
| 3817 | detail of clang's HLSL implementation. For more information see `HLSL Resource |
| 3818 | Types`_ |
| 3819 | |
| 3820 | .. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST" ; |
| 3821 | |
| 3822 | static const char AttrDoc_HLSLIsCounter[] = R"reST(The ``hlsl::is_counter`` attribute specifies that the HLSL resource represented |
| 3823 | by a member variable of type ``__hlsl_resource_t`` is a counter buffer. |
| 3824 | |
| 3825 | This attribute is only valid for resource handles, and is an implementation |
| 3826 | detail of clang's HLSL implementation. For more information see `HLSL Resource |
| 3827 | Types`_ |
| 3828 | |
| 3829 | .. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST" ; |
| 3830 | |
| 3831 | static const char AttrDoc_HLSLIsMultiSampled[] = R"reST(The ``hlsl::is_array`` attribute specifies that the HLSL resource represented |
| 3832 | by a member variable of type ``__hlsl_resource_t`` is multisampled. |
| 3833 | |
| 3834 | This attribute is only valid for resource handles, and is an implementation |
| 3835 | detail of clang's HLSL implementation. For more information see `HLSL Resource |
| 3836 | Types`_ |
| 3837 | |
| 3838 | .. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST" ; |
| 3839 | |
| 3840 | static const char AttrDoc_HLSLIsROV[] = R"reST(The ``hlsl::is_rov`` attribute specifies that the HLSL resource represented by |
| 3841 | a member variable of type ``__hlsl_resource_t`` is a rasterizer ordered view. |
| 3842 | |
| 3843 | This attribute is only valid for resource handles, and is an implementation |
| 3844 | detail of clang's HLSL implementation. For more information see `HLSL Resource |
| 3845 | Types`_ |
| 3846 | |
| 3847 | .. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST" ; |
| 3848 | |
| 3849 | static const char AttrDoc_HLSLLoopHint[] = R"reST(The `[loop]` directive allows loop optimization hints to be |
| 3850 | specified for the subsequent loop. The directive allows unrolling to |
| 3851 | be disabled and is not compatible with [unroll(x)]. |
| 3852 | |
| 3853 | Specifying the parameter, `[loop]`, directs the |
| 3854 | unroller to not unroll the loop. |
| 3855 | |
| 3856 | ```hlsl |
| 3857 | [loop] |
| 3858 | for (...) { |
| 3859 | ... |
| 3860 | } |
| 3861 | ``` |
| 3862 | |
| 3863 | ```hlsl |
| 3864 | [loop] |
| 3865 | while (...) { |
| 3866 | ... |
| 3867 | } |
| 3868 | ``` |
| 3869 | |
| 3870 | ```hlsl |
| 3871 | [loop] |
| 3872 | do { |
| 3873 | ... |
| 3874 | } while (...) |
| 3875 | ``` |
| 3876 | |
| 3877 | See [hlsl loop extensions](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-for) |
| 3878 | for details.)reST" ; |
| 3879 | |
| 3880 | static const char AttrDoc_HLSLNumThreads[] = R"reST(The `numthreads` attribute applies to HLSL shaders where explcit thread counts |
| 3881 | are required. The `X`, `Y`, and `Z` values provided to the attribute |
| 3882 | dictate the thread id. Total number of threads executed is `X * Y * Z`. |
| 3883 | |
| 3884 | The full documentation is available here: <https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-numthreads>)reST" ; |
| 3885 | |
| 3886 | static const char AttrDoc_HLSLPackOffset[] = R"reST(The packoffset attribute is used to change the layout of a cbuffer. |
| 3887 | Attribute spelling in HLSL is: `packoffset( c[Subcomponent][.component] )`. |
| 3888 | A subcomponent is a register number, which is an integer. A component is in the form of [.xyzw]. |
| 3889 | |
| 3890 | Examples: |
| 3891 | |
| 3892 | ```hlsl |
| 3893 | cbuffer A { |
| 3894 | float3 a : packoffset(c0.y); |
| 3895 | float4 b : packoffset(c4); |
| 3896 | } |
| 3897 | ``` |
| 3898 | |
| 3899 | The full documentation is available here: <https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-packoffset>)reST" ; |
| 3900 | |
| 3901 | static const char AttrDoc_HLSLParamModifier[] = R"reST(HLSL function parameters are passed by value. Parameter declarations support |
| 3902 | three qualifiers to denote parameter passing behavior. The three qualifiers are |
| 3903 | `in`, `out` and `inout`. |
| 3904 | |
| 3905 | Parameters annotated with `in` or with no annotation are passed by value from |
| 3906 | the caller to the callee. |
| 3907 | |
| 3908 | Parameters annotated with `out` are written to the argument after the callee |
| 3909 | returns (Note: arguments values passed into `out` parameters *are not* copied |
| 3910 | into the callee). |
| 3911 | |
| 3912 | Parameters annotated with `inout` are copied into the callee via a temporary, |
| 3913 | and copied back to the argument after the callee returns.)reST" ; |
| 3914 | |
| 3915 | static const char AttrDoc_HLSLParsedSemantic[] = R"reST()reST" ; |
| 3916 | |
| 3917 | static const char AttrDoc_HLSLRawBuffer[] = R"reST(The ``hlsl::raw_buffer`` attribute specifies that the HLSL resource represented |
| 3918 | by a member variable of type ``__hlsl_resource_t`` has raw buffer semantics. |
| 3919 | |
| 3920 | This attribute is only valid for resource handles, and is an implementation |
| 3921 | detail of clang's HLSL implementation. For more information see `HLSL Resource |
| 3922 | Types`_ |
| 3923 | |
| 3924 | .. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST" ; |
| 3925 | |
| 3926 | static const char AttrDoc_HLSLResourceBinding[] = R"reST(The resource binding attribute sets the virtual register and logical register space for a resource. |
| 3927 | Attribute spelling in HLSL is: `register(slot [, space])`. |
| 3928 | `slot` takes the format `[type][number]`, |
| 3929 | where `type` is a single character specifying the resource type and `number` is the virtual register number. |
| 3930 | |
| 3931 | Register types are: |
| 3932 | t for shader resource views (SRV), |
| 3933 | s for samplers, |
| 3934 | u for unordered access views (UAV), |
| 3935 | b for constant buffer views (CBV). |
| 3936 | |
| 3937 | Register space is specified in the format `space[number]` and defaults to `space0` if omitted. |
| 3938 | Here're resource binding examples with and without space: |
| 3939 | |
| 3940 | ```hlsl |
| 3941 | RWBuffer<float> Uav : register(u3, space1); |
| 3942 | Buffer<float> Buf : register(t1); |
| 3943 | ``` |
| 3944 | |
| 3945 | The full documentation is available here: <https://docs.microsoft.com/en-us/windows/win32/direct3d12/resource-binding-in-hlsl>)reST" ; |
| 3946 | |
| 3947 | static const char AttrDoc_HLSLResourceClass[] = R"reST(The ``hlsl::resource_class`` attribute specifies the resource class of the HLSL |
| 3948 | resource represented by a member variable of type ``__hlsl_resource_t``, |
| 3949 | declaring it to be an SRV, UAV, CBuffer, or Sampler resource. |
| 3950 | |
| 3951 | This attribute is only valid for resource handles, and is an implementation |
| 3952 | detail of clang's HLSL implementation. For more information see `HLSL Resource |
| 3953 | Types`_ |
| 3954 | |
| 3955 | .. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST" ; |
| 3956 | |
| 3957 | static const char AttrDoc_HLSLResourceDimension[] = R"reST(The ``hlsl::dimension`` attribute specifies the dimensions of the HLSL resource |
| 3958 | represented by a member variable of type ``__hlsl_resource_t``, declaring the |
| 3959 | resource to have Unknown, 1D, 2D, 3D, or Cube dimension. |
| 3960 | |
| 3961 | This attribute is only valid for resource handles, and is an implementation |
| 3962 | detail of clang's HLSL implementation. For more information see `HLSL Resource |
| 3963 | Types`_ |
| 3964 | |
| 3965 | .. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST" ; |
| 3966 | |
| 3967 | static const char AttrDoc_HLSLRowMajor[] = R"reST(The `row_major` and `column_major` keywords specify the memory layout |
| 3968 | of an HLSL matrix type. |
| 3969 | |
| 3970 | - `row_major`: Matrices are stored in memory row-by-row. |
| 3971 | - `column_major`: Matrices are stored in memory column-by-column (default). |
| 3972 | |
| 3973 | Example: |
| 3974 | |
| 3975 | ```hlsl |
| 3976 | row_major float2x2 myMatrix; |
| 3977 | ```)reST" ; |
| 3978 | |
| 3979 | static const char AttrDoc_HLSLShader[] = R"reST(The `shader` type attribute applies to HLSL shader entry functions to |
| 3980 | identify the shader type for the entry function. |
| 3981 | The syntax is: |
| 3982 | |
| 3983 | ```text |
| 3984 | ``[shader(string-literal)]`` |
| 3985 | ``` |
| 3986 | |
| 3987 | where the string literal is one of: "pixel", "vertex", "geometry", "hull", |
| 3988 | "domain", "compute", "raygeneration", "intersection", "anyhit", "closesthit", |
| 3989 | "miss", "callable", "mesh", "amplification". Normally the shader type is set |
| 3990 | by shader target with the `-T` option like `-Tps_6_1`. When compiling to a |
| 3991 | library target like `lib_6_3`, the shader type attribute can help the |
| 3992 | compiler to identify the shader type. It is mostly used by Raytracing shaders |
| 3993 | where shaders must be compiled into a library and linked at runtime.)reST" ; |
| 3994 | |
| 3995 | static const char AttrDoc_HLSLUnparsedSemantic[] = R"reST()reST" ; |
| 3996 | |
| 3997 | static const char AttrDoc_HLSLVkBinding[] = R"reST(The `[[vk::binding]]` attribute allows you to explicitly specify the descriptor |
| 3998 | set and binding for a resource when targeting SPIR-V. This is particularly |
| 3999 | useful when you need different bindings for SPIR-V and DXIL, as the `register` |
| 4000 | attribute can be used for DXIL-specific bindings. |
| 4001 | |
| 4002 | The attribute takes two integer arguments: the binding and the descriptor set. |
| 4003 | The descriptor set is optional and defaults to 0 if not provided. |
| 4004 | |
| 4005 | ```c++ |
| 4006 | // A structured buffer with binding 23 in descriptor set 102. |
| 4007 | [[vk::binding(23, 102)]] StructuredBuffer<float> Buf; |
| 4008 | |
| 4009 | // A structured buffer with binding 14 in descriptor set 0. |
| 4010 | [[vk::binding(14)]] StructuredBuffer<float> Buf2; |
| 4011 | |
| 4012 | // A cbuffer with binding 1 in descriptor set 2. |
| 4013 | [[vk::binding(1, 2)]] cbuffer MyCBuffer { |
| 4014 | float4x4 worldViewProj; |
| 4015 | }; |
| 4016 | ```)reST" ; |
| 4017 | |
| 4018 | static const char AttrDoc_HLSLVkConstantId[] = R"reST(The `vk::constant_id` attribute specifies the id for a SPIR-V specialization |
| 4019 | constant. The attribute applies to const global scalar variables. The variable must be initialized with a C++11 constexpr. |
| 4020 | In SPIR-V, the |
| 4021 | variable will be replaced with an `OpSpecConstant` with the given id. |
| 4022 | The syntax is: |
| 4023 | |
| 4024 | ```text |
| 4025 | ``[[vk::constant_id(<Id>)]] const T Name = <Init>`` |
| 4026 | ```)reST" ; |
| 4027 | |
| 4028 | static const char AttrDoc_HLSLVkExtBuiltinInput[] = R"reST(Vulkan shaders have `Input` builtins. Those variables are externally |
| 4029 | initialized by the driver/pipeline, but each copy is private to the current |
| 4030 | lane. |
| 4031 | |
| 4032 | Those builtins can be declared using the `[[vk::ext_builtin_input]]` attribute |
| 4033 | like follows: |
| 4034 | |
| 4035 | ```c++ |
| 4036 | [[vk::ext_builtin_input(/* WorkgroupId */ 26)]] |
| 4037 | static const uint3 groupid; |
| 4038 | ``` |
| 4039 | |
| 4040 | This variable will be lowered into a module-level variable, with the `Input` |
| 4041 | storage class, and the `BuiltIn 26` decoration. |
| 4042 | |
| 4043 | The full documentation for this inline SPIR-V attribute can be found here: |
| 4044 | <https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md>)reST" ; |
| 4045 | |
| 4046 | static const char AttrDoc_HLSLVkExtBuiltinOutput[] = R"reST(Vulkan shaders have `Output` builtins. Those variables are externally |
| 4047 | visible to the driver/pipeline, but each copy is private to the current |
| 4048 | lane. |
| 4049 | |
| 4050 | Those builtins can be declared using the `[[vk::ext_builtin_output]]` |
| 4051 | attribute like follows: |
| 4052 | |
| 4053 | ```c++ |
| 4054 | [[vk::ext_builtin_output(/* Position */ 0)]] |
| 4055 | static float4 position; |
| 4056 | ``` |
| 4057 | |
| 4058 | This variable will be lowered into a module-level variable, with the `Output` |
| 4059 | storage class, and the `BuiltIn 0` decoration. |
| 4060 | |
| 4061 | The full documentation for this inline SPIR-V attribute can be found here: |
| 4062 | <https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md>)reST" ; |
| 4063 | |
| 4064 | static const char AttrDoc_HLSLVkLocation[] = R"reST(Attribute used for specifying the location number for the stage input/output |
| 4065 | variables. Allowed on function parameters, function returns, and struct |
| 4066 | fields. This parameter has no effect when used outside of an entrypoint |
| 4067 | parameter/parameter field/return value. |
| 4068 | |
| 4069 | This attribute maps to the 'Location' SPIR-V decoration.)reST" ; |
| 4070 | |
| 4071 | static const char AttrDoc_HLSLVkPushConstant[] = R"reST(Vulkan shaders have `PushConstants` |
| 4072 | |
| 4073 | The `[[vk::push_constant]]` attribute allows you to declare this |
| 4074 | global variable as a push constant when targeting Vulkan. |
| 4075 | This attribute is ignored otherwise. |
| 4076 | |
| 4077 | This attribute must be applied to the variable, not underlying type. |
| 4078 | The variable type must be a struct, per the requirements of Vulkan, "there |
| 4079 | must be no more than one push constant block statically used per shader entry |
| 4080 | point.")reST" ; |
| 4081 | |
| 4082 | static const char AttrDoc_HLSLWaveSize[] = R"reST(The `WaveSize` attribute specify a wave size on a shader entry point in order |
| 4083 | to indicate either that a shader depends on or strongly prefers a specific wave |
| 4084 | size. |
| 4085 | There're 2 versions of the attribute: `WaveSize` and `RangedWaveSize`. |
| 4086 | The syntax for `WaveSize` is: |
| 4087 | |
| 4088 | ```text |
| 4089 | ``[WaveSize(<numLanes>)]`` |
| 4090 | ``` |
| 4091 | |
| 4092 | The allowed wave sizes that an HLSL shader may specify are the powers of 2 |
| 4093 | between 4 and 128, inclusive. |
| 4094 | In other words, the set: [4, 8, 16, 32, 64, 128]. |
| 4095 | |
| 4096 | The syntax for `RangedWaveSize` is: |
| 4097 | |
| 4098 | ```text |
| 4099 | ``[WaveSize(<minWaveSize>, <maxWaveSize>, [prefWaveSize])]`` |
| 4100 | ``` |
| 4101 | |
| 4102 | Where minWaveSize is the minimum wave size supported by the shader representing |
| 4103 | the beginning of the allowed range, maxWaveSize is the maximum wave size |
| 4104 | supported by the shader representing the end of the allowed range, and |
| 4105 | prefWaveSize is the optional preferred wave size representing the size expected |
| 4106 | to be the most optimal for this shader. |
| 4107 | |
| 4108 | `WaveSize` is available for HLSL shader model 6.6 and later. |
| 4109 | `RangedWaveSize` available for HLSL shader model 6.8 and later. |
| 4110 | |
| 4111 | The full documentation is available here: <https://microsoft.github.io/DirectX-Specs/d3d/HLSL_SM_6_6_WaveSize.html> |
| 4112 | and <https://microsoft.github.io/hlsl-specs/proposals/0013-wave-size-range.html>)reST" ; |
| 4113 | |
| 4114 | static const char AttrDoc_Hot[] = R"reST(`__attribute__((hot))` marks a function as hot, as a manual alternative to PGO hotness data. |
| 4115 | If PGO data is available, the annotation `__attribute__((hot))` overrides the profile count based hotness (unlike `__attribute__((cold))`).)reST" ; |
| 4116 | |
| 4117 | static const char AttrDoc_HybridPatchable[] = R"reST(The `hybrid_patchable` attribute declares an ARM64EC function with an additional |
| 4118 | x86-64 thunk, which may be patched at runtime. |
| 4119 | |
| 4120 | For more information see |
| 4121 | [ARM64EC ABI documentation](https://learn.microsoft.com/en-us/windows/arm/arm64ec-abi).)reST" ; |
| 4122 | |
| 4123 | static const char AttrDoc_IBAction[] = R"reST(No documentation.)reST" ; |
| 4124 | |
| 4125 | static const char AttrDoc_IBOutlet[] = R"reST(No documentation.)reST" ; |
| 4126 | |
| 4127 | static const char AttrDoc_IBOutletCollection[] = R"reST(No documentation.)reST" ; |
| 4128 | |
| 4129 | static const char AttrDoc_IFunc[] = R"reST(`__attribute__((ifunc("resolver")))` is used to mark that the address of a |
| 4130 | declaration should be resolved at runtime by calling a resolver function. |
| 4131 | |
| 4132 | The symbol name of the resolver function is given in quotes. A function with |
| 4133 | this name (after mangling) must be defined in the current translation unit; it |
| 4134 | may be `static`. The resolver function should return a pointer. |
| 4135 | |
| 4136 | The `ifunc` attribute may only be used on a function declaration. A function |
| 4137 | declaration with an `ifunc` attribute is considered to be a definition of the |
| 4138 | declared entity. The entity must not have weak linkage; for example, in C++, |
| 4139 | it cannot be applied to a declaration if a definition at that location would be |
| 4140 | considered inline. |
| 4141 | |
| 4142 | Not all targets support this attribute: |
| 4143 | |
| 4144 | - ELF target support depends on both the linker and runtime linker, and is |
| 4145 | available in at least lld 4.0 and later, binutils 2.20.1 and later, glibc |
| 4146 | v2.11.1 and later, and FreeBSD 9.1 and later. |
| 4147 | - Mach-O targets support it, but with slightly different semantics: the resolver |
| 4148 | is run at first call, instead of at load time by the runtime linker. |
| 4149 | - Windows target supports it on AArch64, but with different semantics: the |
| 4150 | `ifunc` is replaced with a global function pointer, and the call is replaced |
| 4151 | with an indirect call. The function pointer is initialized by a constructor |
| 4152 | that calls the resolver. |
| 4153 | - Baremetal target supports it on AVR. |
| 4154 | - AIX/XCOFF supports it via a compiler-only solution. An ifunc appears as a |
| 4155 | regular function (has an entry point `.foo[PR]` and a function descriptor |
| 4156 | `foo[DS]`). The entry point is a stub that branches to the function address |
| 4157 | in the descriptor, and the descriptor is initialized via a constructor |
| 4158 | function (`__init_ifuncs`) that is linked into every shared object and |
| 4159 | executable. `__init_ifuncs` calls the resolver of each ifunc and stores the |
| 4160 | result in the corresponding descriptor. |
| 4161 | - Other targets currently do not support this attribute.)reST" ; |
| 4162 | |
| 4163 | static const char AttrDoc_InferredNoReturn[] = R"reST()reST" ; |
| 4164 | |
| 4165 | static const char AttrDoc_InitPriority[] = R"reST(In C++, the order in which global variables are initialized across translation |
| 4166 | units is unspecified, unlike the ordering within a single translation unit. The |
| 4167 | `init_priority` attribute allows you to specify a relative ordering for the |
| 4168 | initialization of objects declared at namespace scope in C++ within a single |
| 4169 | linked image on supported platforms. The priority is given as an integer constant |
| 4170 | expression between 101 and 65535 (inclusive). Priorities outside of that range are |
| 4171 | reserved for use by the implementation. A lower value indicates a higher priority |
| 4172 | of initialization. Note that only the relative ordering of values is important. |
| 4173 | For example: |
| 4174 | |
| 4175 | ```c++ |
| 4176 | struct SomeType { SomeType(); }; |
| 4177 | __attribute__((init_priority(200))) SomeType Obj1; |
| 4178 | __attribute__((init_priority(101))) SomeType Obj2; |
| 4179 | ``` |
| 4180 | |
| 4181 | `Obj2` will be initialized *before* `Obj1` despite the usual order of |
| 4182 | initialization being the opposite. |
| 4183 | |
| 4184 | Note that this attribute does not control the initialization order of objects |
| 4185 | across final linked image boundaries like shared objects and executables. |
| 4186 | |
| 4187 | On Windows, `init_seg(compiler)` is represented with a priority of 200 and |
| 4188 | `init_seg(library)` is represented with a priority of 400. `init_seg(user)` |
| 4189 | uses the default 65535 priority. |
| 4190 | |
| 4191 | On MachO platforms, this attribute also does not control the order of initialization |
| 4192 | across translation units, where it only affects the order within a single TU. |
| 4193 | |
| 4194 | This attribute is only supported for C++ and Objective-C++ and is ignored in |
| 4195 | other language modes.)reST" ; |
| 4196 | |
| 4197 | static const char AttrDoc_InitSeg[] = R"reST(The attribute applied by `pragma init_seg()` controls the section into |
| 4198 | which global initialization function pointers are emitted. It is only |
| 4199 | available with `-fms-extensions`. Typically, this function pointer is |
| 4200 | emitted into `.CRT$XCU` on Windows. The user can change the order of |
| 4201 | initialization by using a different section name with the same |
| 4202 | `.CRT$XC` prefix and a suffix that sorts lexicographically before or |
| 4203 | after the standard `.CRT$XCU` sections. See the [init_seg][init_seg] |
| 4204 | documentation on MSDN for more information. |
| 4205 | |
| 4206 | [init_seg]: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx)reST" ; |
| 4207 | |
| 4208 | static const char AttrDoc_IntelOclBicc[] = R"reST(No documentation.)reST" ; |
| 4209 | |
| 4210 | static const char AttrDoc_InternalLinkage[] = R"reST(The `internal_linkage` attribute changes the linkage type of the declaration |
| 4211 | to internal. This is similar to C-style `static`, but can be used on classes |
| 4212 | and class methods. When applied to a class definition, this attribute affects |
| 4213 | all methods and static data members of that class. This can be used to contain |
| 4214 | the ABI of a C++ library by excluding unwanted class methods from the export |
| 4215 | tables.)reST" ; |
| 4216 | |
| 4217 | static const char AttrDoc_LTOVisibilityPublic[] = R"reST(See {doc}`LTOVisibility`.)reST" ; |
| 4218 | |
| 4219 | static const char AttrDoc_LayoutVersion[] = R"reST(The layout_version attribute requests that the compiler utilize the class |
| 4220 | layout rules of a particular compiler version. |
| 4221 | This attribute only applies to struct, class, and union types. |
| 4222 | It is only supported when using the Microsoft C++ ABI.)reST" ; |
| 4223 | |
| 4224 | static const char AttrDoc_Leaf[] = R"reST(The `leaf` attribute is used as a compiler hint to improve dataflow analysis |
| 4225 | in library functions. Functions marked with the `leaf` attribute are not allowed |
| 4226 | to jump back into the caller's translation unit, whether through invoking a |
| 4227 | callback function, an external function call, use of `longjmp`, or other means. |
| 4228 | Therefore, they cannot use or modify any data that does not escape the caller function's |
| 4229 | compilation unit. |
| 4230 | |
| 4231 | For more information see |
| 4232 | `gcc documentation <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html>`)reST" ; |
| 4233 | |
| 4234 | static const char AttrDoc_LifetimeBound[] = R"reST(The `lifetimebound` attribute on a function parameter or implicit object |
| 4235 | parameter indicates that objects that are referred to by that parameter may |
| 4236 | also be referred to by the return value of the annotated function (or, for a |
| 4237 | parameter of a constructor, by the value of the constructed object). |
| 4238 | |
| 4239 | By default, a reference is considered to refer to its referenced object, a |
| 4240 | pointer is considered to refer to its pointee, a `std::initializer_list<T>` |
| 4241 | is considered to refer to its underlying array, and aggregates (arrays and |
| 4242 | simple `struct`s) are considered to refer to all objects that their |
| 4243 | transitive subobjects refer to. |
| 4244 | |
| 4245 | Clang warns if it is able to detect that an object or reference refers to |
| 4246 | another object with a shorter lifetime. For example, Clang will warn if a |
| 4247 | function returns a reference to a local variable, or if a reference is bound to |
| 4248 | a temporary object whose lifetime is not extended. By using the |
| 4249 | `lifetimebound` attribute, this determination can be extended to look through |
| 4250 | user-declared functions. For example: |
| 4251 | |
| 4252 | ```c++ |
| 4253 | #include <map> |
| 4254 | #include <string> |
| 4255 | |
| 4256 | using namespace std::literals; |
| 4257 | |
| 4258 | // Returns m[key] if key is present, or default_value if not. |
| 4259 | template<typename T, typename U> |
| 4260 | const U &get_or_default(const std::map<T, U> &m [[clang::lifetimebound]], |
| 4261 | const T &key, /* note, not lifetimebound */ |
| 4262 | const U &default_value [[clang::lifetimebound]]) { |
| 4263 | if (auto iter = m.find(key); iter != m.end()) return iter->second; |
| 4264 | else return default_value; |
| 4265 | } |
| 4266 | |
| 4267 | int main() { |
| 4268 | std::map<std::string, std::string> m; |
| 4269 | // warning: temporary bound to local reference 'val1' will be destroyed |
| 4270 | // at the end of the full-expression |
| 4271 | const std::string &val1 = get_or_default(m, "foo"s, "bar"s); |
| 4272 | |
| 4273 | // No warning in this case. |
| 4274 | std::string def_val = "bar"s; |
| 4275 | const std::string &val2 = get_or_default(m, "foo"s, def_val); |
| 4276 | |
| 4277 | return 0; |
| 4278 | } |
| 4279 | ``` |
| 4280 | |
| 4281 | The attribute can be applied to the implicit `this` parameter of a member |
| 4282 | function by writing the attribute after the function type: |
| 4283 | |
| 4284 | ```c++ |
| 4285 | struct string { |
| 4286 | // The returned pointer should not outlive ``*this``. |
| 4287 | const char *data() const [[clang::lifetimebound]]; |
| 4288 | }; |
| 4289 | ``` |
| 4290 | |
| 4291 | This attribute is inspired by the C++ committee paper [P0936R0](http://wg21.link/p0936r0), but does not affect whether temporary objects |
| 4292 | have their lifetimes extended.)reST" ; |
| 4293 | |
| 4294 | static const char AttrDoc_LifetimeCaptureBy[] = R"reST(Similar to [lifetimebound], the `lifetime_capture_by` attribute family on a |
| 4295 | function parameter or implicit object parameter indicates that a capturing |
| 4296 | entity may refer to the object referred to by that parameter. The capturing |
| 4297 | entity can be named in `lifetime_capture_by(X)` or selected by one of the |
| 4298 | standalone special forms listed below. |
| 4299 | |
| 4300 | Below is a list of types of the parameters and what they're considered to refer to: |
| 4301 | |
| 4302 | - A reference param (of non-view type) is considered to refer to its referenced object. |
| 4303 | - A pointer param (of non-view type) is considered to refer to its pointee. |
| 4304 | - View type param (type annotated with `[[gsl::Pointer()]]`) is considered to refer |
| 4305 | to its pointee (gsl owner). This holds true even if the view type appears as a reference |
| 4306 | in the parameter. For example, both `std::string_view` and |
| 4307 | `const std::string_view &` are considered to refer to a `std::string`. |
| 4308 | - A `std::initializer_list<T>` is considered to refer to its underlying array. |
| 4309 | - Aggregates (arrays and simple `struct`s) are considered to refer to all |
| 4310 | objects that their transitive subobjects refer to. |
| 4311 | |
| 4312 | Clang would diagnose when a temporary object is used as an argument to such an |
| 4313 | annotated parameter. |
| 4314 | In this case, the capturing entity `X` could capture a dangling reference to this |
| 4315 | temporary object. |
| 4316 | |
| 4317 | ```c++ |
| 4318 | void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) { |
| 4319 | s.insert(a); |
| 4320 | } |
| 4321 | void use() { |
| 4322 | std::set<std::string_view> s; |
| 4323 | addToSet(std::string(), s); // Warning: object whose reference is captured by 's' will be destroyed at the end of the full-expression. |
| 4324 | // ^^^^^^^^^^^^^ |
| 4325 | std::string local; |
| 4326 | addToSet(local, s); // Ok. |
| 4327 | } |
| 4328 | ``` |
| 4329 | |
| 4330 | The capturing entity can be one of the following: |
| 4331 | |
| 4332 | - Another (named) function parameter. |
| 4333 | |
| 4334 | ```c++ |
| 4335 | void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) { |
| 4336 | s.insert(a); |
| 4337 | } |
| 4338 | ``` |
| 4339 | |
| 4340 | - `this` (in case of member functions), written as |
| 4341 | `lifetime_capture_by_this`. |
| 4342 | |
| 4343 | ```c++ |
| 4344 | class S { |
| 4345 | void addToSet(std::string_view a [[clang::lifetime_capture_by_this]]) { |
| 4346 | s.insert(a); |
| 4347 | } |
| 4348 | std::set<std::string_view> s; |
| 4349 | }; |
| 4350 | ``` |
| 4351 | |
| 4352 | Note: When applied to a constructor parameter, `[[clang::lifetime_capture_by_this]]` is just an alias of `[[clang::lifetimebound]]`. |
| 4353 | |
| 4354 | - `global` and `unknown`, written as `lifetime_capture_by_global` and |
| 4355 | `lifetime_capture_by_unknown` respectively. |
| 4356 | |
| 4357 | ```c++ |
| 4358 | std::set<std::string_view> s; |
| 4359 | void addToSet(std::string_view a [[clang::lifetime_capture_by_global]]) { |
| 4360 | s.insert(a); |
| 4361 | } |
| 4362 | void addSomewhere(std::string_view a [[clang::lifetime_capture_by_unknown]]); |
| 4363 | ``` |
| 4364 | |
| 4365 | The attribute can be applied to the implicit `this` parameter of a member |
| 4366 | function by writing the attribute after the function type: |
| 4367 | |
| 4368 | ```c++ |
| 4369 | struct S { |
| 4370 | const char *data(std::set<S*>& s) [[clang::lifetime_capture_by(s)]] { |
| 4371 | s.insert(this); |
| 4372 | } |
| 4373 | }; |
| 4374 | ``` |
| 4375 | |
| 4376 | The parameter-list form supports specifying more than one capturing entity: |
| 4377 | |
| 4378 | ```c++ |
| 4379 | void addToSets(std::string_view a [[clang::lifetime_capture_by(s1, s2)]], |
| 4380 | std::set<std::string_view>& s1, |
| 4381 | std::set<std::string_view>& s2) { |
| 4382 | s1.insert(a); |
| 4383 | s2.insert(a); |
| 4384 | } |
| 4385 | ``` |
| 4386 | |
| 4387 | Distinct `lifetime_capture_by` forms can also be combined on the same |
| 4388 | declaration, but each form can appear at most once. For example, |
| 4389 | `[[clang::lifetime_capture_by(s), clang::lifetime_capture_by_this]]` is |
| 4390 | allowed, but two `[[clang::lifetime_capture_by(...)]]` attributes or two |
| 4391 | `[[clang::lifetime_capture_by_this]]` attributes on the same declaration are |
| 4392 | rejected. |
| 4393 | |
| 4394 | Limitation: The capturing entity `X` is not used by the analysis and is |
| 4395 | used for documentation purposes only. This is because the analysis is |
| 4396 | statement-local and only detects use of a temporary as an argument to the |
| 4397 | annotated parameter. |
| 4398 | |
| 4399 | ```c++ |
| 4400 | void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s); |
| 4401 | void use() { |
| 4402 | std::set<std::string_view> s; |
| 4403 | if (foo()) { |
| 4404 | std::string str; |
| 4405 | addToSet(str, s); // Not detected. |
| 4406 | } |
| 4407 | } |
| 4408 | ```)reST" ; |
| 4409 | |
| 4410 | static const char AttrDoc_Likely[] = R"reST(The `likely` and `unlikely` attributes are used as compiler hints. |
| 4411 | The attributes are used to aid the compiler to determine which branch is |
| 4412 | likely or unlikely to be taken. This is done by marking the branch substatement |
| 4413 | with one of the two attributes. |
| 4414 | |
| 4415 | It isn't allowed to annotate a single statement with both `likely` and |
| 4416 | `unlikely`. Annotating the `true` and `false` branch of an `if` |
| 4417 | statement with the same likelihood attribute will result in a diagnostic and |
| 4418 | the attributes are ignored on both branches. |
| 4419 | |
| 4420 | In a `switch` statement it's allowed to annotate multiple `case` labels |
| 4421 | or the `default` label with the same likelihood attribute. This makes |
| 4422 | \* all labels without an attribute have a neutral likelihood, |
| 4423 | \* all labels marked `[[likely]]` have an equally positive likelihood, and |
| 4424 | \* all labels marked `[[unlikely]]` have an equally negative likelihood. |
| 4425 | The neutral likelihood is the more likely of path execution than the negative |
| 4426 | likelihood. The positive likelihood is the more likely of path of execution |
| 4427 | than the neutral likelihood. |
| 4428 | |
| 4429 | These attributes have no effect on the generated code when using |
| 4430 | PGO (Profile-Guided Optimization) or at optimization level 0. |
| 4431 | |
| 4432 | In Clang, the attributes will be ignored if they're not placed on |
| 4433 | \* the `case` or `default` label of a `switch` statement, |
| 4434 | \* or on the substatement of an `if` or `else` statement, |
| 4435 | \* or on the substatement of an `for` or `while` statement. |
| 4436 | The C++ Standard recommends to honor them on every statement in the |
| 4437 | path of execution, but that can be confusing: |
| 4438 | |
| 4439 | ```c++ |
| 4440 | if (b) { |
| 4441 | [[unlikely]] --b; // Per the standard this is in the path of |
| 4442 | // execution, so this branch should be considered |
| 4443 | // unlikely. However, Clang ignores the attribute |
| 4444 | // here since it is not on the substatement. |
| 4445 | } |
| 4446 | |
| 4447 | if (b) { |
| 4448 | --b; |
| 4449 | if(b) |
| 4450 | return; |
| 4451 | [[unlikely]] --b; // Not in the path of execution, |
| 4452 | } // the branch has no likelihood information. |
| 4453 | |
| 4454 | if (b) { |
| 4455 | --b; |
| 4456 | foo(b); |
| 4457 | // Whether or not the next statement is in the path of execution depends |
| 4458 | // on the declaration of foo(): |
| 4459 | // In the path of execution: void foo(int); |
| 4460 | // Not in the path of execution: [[noreturn]] void foo(int); |
| 4461 | // This means the likelihood of the branch depends on the declaration |
| 4462 | // of foo(). |
| 4463 | [[unlikely]] --b; |
| 4464 | } |
| 4465 | ``` |
| 4466 | |
| 4467 | Below are some example usages of the likelihood attributes and their effects: |
| 4468 | |
| 4469 | ```c++ |
| 4470 | if (b) [[likely]] { // Placement on the first statement in the branch. |
| 4471 | // The compiler will optimize to execute the code here. |
| 4472 | } else { |
| 4473 | } |
| 4474 | |
| 4475 | if (b) |
| 4476 | [[unlikely]] b++; // Placement on the first statement in the branch. |
| 4477 | else { |
| 4478 | // The compiler will optimize to execute the code here. |
| 4479 | } |
| 4480 | |
| 4481 | if (b) { |
| 4482 | [[unlikely]] b++; // Placement on the second statement in the branch. |
| 4483 | } // The attribute will be ignored. |
| 4484 | |
| 4485 | if (b) [[likely]] { |
| 4486 | [[unlikely]] b++; // No contradiction since the second attribute |
| 4487 | } // is ignored. |
| 4488 | |
| 4489 | if (b) |
| 4490 | ; |
| 4491 | else [[likely]] { |
| 4492 | // The compiler will optimize to execute the code here. |
| 4493 | } |
| 4494 | |
| 4495 | if (b) |
| 4496 | ; |
| 4497 | else |
| 4498 | // The compiler will optimize to execute the next statement. |
| 4499 | [[likely]] b = f(); |
| 4500 | |
| 4501 | if (b) [[likely]]; // Both branches are likely. A diagnostic is issued |
| 4502 | else [[likely]]; // and the attributes are ignored. |
| 4503 | |
| 4504 | if (b) |
| 4505 | [[likely]] int i = 5; // Issues a diagnostic since the attribute |
| 4506 | // isn't allowed on a declaration. |
| 4507 | |
| 4508 | switch (i) { |
| 4509 | [[likely]] case 1: // This value is likely |
| 4510 | ... |
| 4511 | break; |
| 4512 | |
| 4513 | [[unlikely]] case 2: // This value is unlikely |
| 4514 | ... |
| 4515 | [[fallthrough]]; |
| 4516 | |
| 4517 | case 3: // No likelihood attribute |
| 4518 | ... |
| 4519 | [[likely]] break; // No effect |
| 4520 | |
| 4521 | case 4: [[likely]] { // attribute on substatement has no effect |
| 4522 | ... |
| 4523 | break; |
| 4524 | } |
| 4525 | |
| 4526 | [[unlikely]] default: // All other values are unlikely |
| 4527 | ... |
| 4528 | break; |
| 4529 | } |
| 4530 | |
| 4531 | switch (i) { |
| 4532 | [[likely]] case 0: // This value and code path is likely |
| 4533 | ... |
| 4534 | [[fallthrough]]; |
| 4535 | |
| 4536 | case 1: // No likelihood attribute, code path is neutral |
| 4537 | break; // falling through has no effect on the likelihood |
| 4538 | |
| 4539 | case 2: // No likelihood attribute, code path is neutral |
| 4540 | [[fallthrough]]; |
| 4541 | |
| 4542 | [[unlikely]] default: // This value and code path are both unlikely |
| 4543 | break; |
| 4544 | } |
| 4545 | |
| 4546 | for(int i = 0; i != size; ++i) [[likely]] { |
| 4547 | ... // The loop is the likely path of execution |
| 4548 | } |
| 4549 | |
| 4550 | for(const auto &E : Elements) [[likely]] { |
| 4551 | ... // The loop is the likely path of execution |
| 4552 | } |
| 4553 | |
| 4554 | while(i != size) [[unlikely]] { |
| 4555 | ... // The loop is the unlikely path of execution |
| 4556 | } // The generated code will optimize to skip the loop body |
| 4557 | |
| 4558 | while(true) [[unlikely]] { |
| 4559 | ... // The attribute has no effect |
| 4560 | } // Clang elides the comparison and generates an infinite |
| 4561 | // loop |
| 4562 | ```)reST" ; |
| 4563 | |
| 4564 | static const char AttrDoc_LoaderUninitialized[] = R"reST(The `loader_uninitialized` attribute can be placed on global variables to |
| 4565 | indicate that the variable does not need to be zero initialized by the loader. |
| 4566 | On most targets, zero-initialization does not incur any additional cost. |
| 4567 | For example, most general purpose operating systems deliberately ensure |
| 4568 | that all memory is properly initialized in order to avoid leaking privileged |
| 4569 | information from the kernel or other programs. However, some targets |
| 4570 | do not make this guarantee, and on these targets, avoiding an unnecessary |
| 4571 | zero-initialization can have a significant impact on load times and/or code |
| 4572 | size. |
| 4573 | |
| 4574 | A declaration with this attribute is a non-tentative definition just as if it |
| 4575 | provided an initializer. Variables with this attribute are considered to be |
| 4576 | uninitialized in the same sense as a local variable, and the programs must |
| 4577 | write to them before reading from them. If the variable's type is a C++ class |
| 4578 | type with a non-trivial default constructor, or an array thereof, this attribute |
| 4579 | only suppresses the static zero-initialization of the variable, not the dynamic |
| 4580 | initialization provided by executing the default constructor.)reST" ; |
| 4581 | |
| 4582 | static const char AttrDoc_LockReturned[] = R"reST(No documentation.)reST" ; |
| 4583 | |
| 4584 | static const char AttrDoc_LocksExcluded[] = R"reST(No documentation.)reST" ; |
| 4585 | |
| 4586 | static const char AttrDoc_LoopHint[] = R"reST(The `#pragma clang loop` directive allows loop optimization hints to be |
| 4587 | specified for the subsequent loop. The directive allows pipelining to be |
| 4588 | disabled, or vectorization, vector predication, interleaving, and unrolling to |
| 4589 | be enabled or disabled. Vector width, vector predication, interleave count, |
| 4590 | unrolling count, and the initiation interval for pipelining can be explicitly |
| 4591 | specified. See |
| 4592 | {ref}`loop hint optimizations <langext-loop-hint-optimizations>` for details.)reST" ; |
| 4593 | |
| 4594 | static const char AttrDoc_M68kInterrupt[] = R"reST(No documentation.)reST" ; |
| 4595 | |
| 4596 | static const char AttrDoc_M68kRTD[] = R"reST(On M68k targets, this attribute changes the calling convention of a function |
| 4597 | to clear parameters off the stack on return. In other words, callee is |
| 4598 | responsible for cleaning out the stack space allocated for incoming paramters. |
| 4599 | This convention does not support variadic calls or unprototyped functions in C. |
| 4600 | When targeting M68010 or newer CPUs, this calling convention is implemented |
| 4601 | using the `rtd` instruction.)reST" ; |
| 4602 | |
| 4603 | static const char AttrDoc_MIGServerRoutine[] = R"reST(The Mach Interface Generator release-on-success convention dictates |
| 4604 | |
| 4605 | functions that follow it to only release arguments passed to them when they |
| 4606 | return "success" (a `kern_return_t` error code that indicates that |
| 4607 | no errors have occurred). Otherwise the release is performed by the MIG client |
| 4608 | that called the function. The annotation `__attribute__((mig_server_routine))` |
| 4609 | is applied in order to specify which functions are expected to follow the |
| 4610 | convention. This allows the Static Analyzer to find bugs caused by violations of |
| 4611 | that convention. The attribute would normally appear on the forward declaration |
| 4612 | of the actual server routine in the MIG server header, but it may also be |
| 4613 | added to arbitrary functions that need to follow the same convention - for |
| 4614 | example, a user can add them to auxiliary functions called by the server routine |
| 4615 | that have their return value of type `kern_return_t` unconditionally returned |
| 4616 | from the routine. The attribute can be applied to C++ methods, and in this case |
| 4617 | it will be automatically applied to overrides if the method is virtual. The |
| 4618 | attribute can also be written using C++11 syntax: `[[mig::server_routine]]`.)reST" ; |
| 4619 | |
| 4620 | static const char AttrDoc_MSABI[] = R"reST(On non-Windows x86_64 and aarch64 targets, this attribute changes the calling convention of |
| 4621 | a function to match the default convention used on Windows. This |
| 4622 | attribute has no effect on Windows targets or non-x86_64, non-aarch64 targets.)reST" ; |
| 4623 | |
| 4624 | static const char AttrDoc_MSAllocator[] = R"reST(The `__declspec(allocator)` attribute is applied to functions that allocate |
| 4625 | memory, such as operator new in C++. When CodeView debug information is emitted |
| 4626 | (enabled by `clang -gcodeview` or `clang-cl /Z7`), Clang will attempt to |
| 4627 | record the code offset of heap allocation call sites in the debug info. It will |
| 4628 | also record the type being allocated using some local heuristics. The Visual |
| 4629 | Studio debugger uses this information to [profile memory usage][profile memory usage]. |
| 4630 | |
| 4631 | This attribute does not affect optimizations in any way, unlike GCC's |
| 4632 | `__attribute__((malloc))`. |
| 4633 | |
| 4634 | [profile memory usage]: https://docs.microsoft.com/en-us/visualstudio/profiling/memory-usage)reST" ; |
| 4635 | |
| 4636 | static const char AttrDoc_MSConstexpr[] = R"reST(The `[[msvc::constexpr]]` attribute can be applied only to a function |
| 4637 | definition or a `return` statement. It does not impact function declarations. |
| 4638 | A `[[msvc::constexpr]]` function cannot be `constexpr` or `consteval`. |
| 4639 | A `[[msvc::constexpr]]` function is treated as if it were a `constexpr` function |
| 4640 | when it is evaluated in a constant context of `[[msvc::constexpr]] return` statement. |
| 4641 | Otherwise, it is treated as a regular function. |
| 4642 | |
| 4643 | Semantics of this attribute are enabled only under MSVC compatibility |
| 4644 | (`-fms-compatibility-version`) 19.33 and later.)reST" ; |
| 4645 | |
| 4646 | static const char AttrDoc_MSInheritance[] = R"reST(This collection of keywords is enabled under `-fms-extensions` and controls |
| 4647 | the pointer-to-member representation used on `*-*-win32` targets. |
| 4648 | |
| 4649 | The `*-*-win32` targets utilize a pointer-to-member representation which |
| 4650 | varies in size and alignment depending on the definition of the underlying |
| 4651 | class. |
| 4652 | |
| 4653 | However, this is problematic when a forward declaration is only available and |
| 4654 | no definition has been made yet. In such cases, Clang is forced to utilize the |
| 4655 | most general representation that is available to it. |
| 4656 | |
| 4657 | These keywords make it possible to use a pointer-to-member representation other |
| 4658 | than the most general one regardless of whether or not the definition will ever |
| 4659 | be present in the current translation unit. |
| 4660 | |
| 4661 | This family of keywords belong between the `class-key` and `class-name`: |
| 4662 | |
| 4663 | ```c++ |
| 4664 | struct __single_inheritance S; |
| 4665 | int S::*i; |
| 4666 | struct S {}; |
| 4667 | ``` |
| 4668 | |
| 4669 | This keyword can be applied to class templates but only has an effect when used |
| 4670 | on full specializations: |
| 4671 | |
| 4672 | ```c++ |
| 4673 | template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template |
| 4674 | template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization |
| 4675 | template <> struct __single_inheritance A<int, float>; |
| 4676 | ``` |
| 4677 | |
| 4678 | Note that choosing an inheritance model less general than strictly necessary is |
| 4679 | an error: |
| 4680 | |
| 4681 | ```c++ |
| 4682 | struct __multiple_inheritance S; // error: inheritance model does not match definition |
| 4683 | int S::*i; |
| 4684 | struct S {}; |
| 4685 | ```)reST" ; |
| 4686 | |
| 4687 | static const char AttrDoc_MSNoVTable[] = R"reST(This attribute can be added to a class declaration or definition to signal to |
| 4688 | the compiler that constructors and destructors will not reference the virtual |
| 4689 | function table. It is only supported when using the Microsoft C++ ABI.)reST" ; |
| 4690 | |
| 4691 | static const char AttrDoc_MSP430Interrupt[] = R"reST(No documentation.)reST" ; |
| 4692 | |
| 4693 | static const char AttrDoc_MSStruct[] = R"reST(The `ms_struct` and `gcc_struct` attributes request the compiler to enter a |
| 4694 | special record layout compatibility mode which mimics the layout of Microsoft or |
| 4695 | Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the |
| 4696 | requested ABI, the attribute does nothing. However, if it does not, annotated |
| 4697 | structure or class is laid out in a special compatibility mode, which slightly |
| 4698 | changes offsets for fields and bit-fields. The intention is to match the layout |
| 4699 | of the requested ABI for structures which only use C features. |
| 4700 | |
| 4701 | Note that the default behavior can be controlled by `-mms-bitfields` and |
| 4702 | `-mno-ms-bitfields` switches and via `#pragma ms_struct`. |
| 4703 | |
| 4704 | The primary difference is for bitfields, where the MS variant only packs |
| 4705 | adjacent fields into the same allocation unit if they have integral types |
| 4706 | of the same size, while the GCC/Itanium variant packs all fields in a bitfield |
| 4707 | tightly.)reST" ; |
| 4708 | |
| 4709 | static const char AttrDoc_MSVtorDisp[] = R"reST()reST" ; |
| 4710 | |
| 4711 | static const char AttrDoc_MallocSpan[] = R"reST(The `malloc_span` attribute can be used to mark that a function which acts |
| 4712 | like a system memory allocation function and returns a span-like structure, |
| 4713 | where the returned memory range does not alias storage from any other object |
| 4714 | accessible to the caller. |
| 4715 | |
| 4716 | In this context, a span-like structure is assumed to have two non-static data |
| 4717 | members, one of which is a pointer to the start of the allocated memory and |
| 4718 | the other one is either an integer type containing the size of the actually |
| 4719 | allocated memory or a pointer to the end of the allocated region. Note, static |
| 4720 | data members do not impact whether a type is span-like or not.)reST" ; |
| 4721 | |
| 4722 | static const char AttrDoc_MaxFieldAlignment[] = R"reST()reST" ; |
| 4723 | |
| 4724 | static const char AttrDoc_MayAlias[] = R"reST(No documentation.)reST" ; |
| 4725 | |
| 4726 | static const char AttrDoc_MaybeUndef[] = R"reST(The `maybe_undef` attribute can be placed on a function parameter. It indicates |
| 4727 | that the parameter is allowed to use undef values. It informs the compiler |
| 4728 | to insert a freeze LLVM IR instruction on the function parameter. |
| 4729 | Please note that this is an attribute that is used as an internal |
| 4730 | implementation detail and not intended to be used by external users. |
| 4731 | |
| 4732 | In languages HIP, CUDA etc., some functions have multi-threaded semantics and |
| 4733 | it is enough for only one or some threads to provide defined arguments. |
| 4734 | Depending on semantics, undef arguments in some threads don't produce |
| 4735 | undefined results in the function call. Since, these functions accept undefined |
| 4736 | arguments, `maybe_undef` attribute can be placed. |
| 4737 | |
| 4738 | Sample usage: |
| 4739 | |
| 4740 | ```c |
| 4741 | void maybeundeffunc(int __attribute__((maybe_undef))param); |
| 4742 | ```)reST" ; |
| 4743 | |
| 4744 | static const char AttrDoc_MicroMips[] = R"reST(Clang supports the GNU style `__attribute__((micromips))` and |
| 4745 | `__attribute__((nomicromips))` attributes on MIPS targets. These attributes |
| 4746 | may be attached to a function definition and instructs the backend to generate |
| 4747 | or not to generate microMIPS code for that function. |
| 4748 | |
| 4749 | These attributes override the `-mmicromips` and `-mno-micromips` options |
| 4750 | on the command line.)reST" ; |
| 4751 | |
| 4752 | static const char AttrDoc_MinSize[] = R"reST(This function attribute indicates that optimization passes and code generator passes |
| 4753 | make choices that keep the function code size as small as possible. Optimizations may |
| 4754 | also sacrifice runtime performance in order to minimize the size of the generated code.)reST" ; |
| 4755 | |
| 4756 | static const char AttrDoc_MinVectorWidth[] = R"reST(Clang supports the `__attribute__((min_vector_width(width)))` attribute. This |
| 4757 | attribute may be attached to a function and informs the backend that this |
| 4758 | function desires vectors of at least this width to be generated. Target-specific |
| 4759 | maximum vector widths still apply. This means even if you ask for something |
| 4760 | larger than the target supports, you will only get what the target supports. |
| 4761 | This attribute is meant to be a hint to control target heuristics that may |
| 4762 | generate narrower vectors than what the target hardware supports. |
| 4763 | |
| 4764 | This is currently used by the X86 target to allow some CPUs that support 512-bit |
| 4765 | vectors to be limited to using 256-bit vectors to avoid frequency penalties. |
| 4766 | This is currently enabled with the `-prefer-vector-width=256` command line |
| 4767 | option. The `min_vector_width` attribute can be used to prevent the backend |
| 4768 | from trying to split vector operations to match the `prefer-vector-width`. All |
| 4769 | X86 vector intrinsics from x86intrin.h already set this attribute. Additionally, |
| 4770 | use of any of the X86-specific vector builtins will implicitly set this |
| 4771 | attribute on the calling function. The intent is that explicitly writing vector |
| 4772 | code using the X86 intrinsics will prevent `prefer-vector-width` from |
| 4773 | affecting the code.)reST" ; |
| 4774 | |
| 4775 | static const char AttrDoc_Mips16[] = R"reST(No documentation.)reST" ; |
| 4776 | |
| 4777 | static const char AttrDoc_MipsInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt("ARGUMENT")))` attribute on |
| 4778 | MIPS targets. This attribute may be attached to a function definition and instructs |
| 4779 | the backend to generate appropriate function entry/exit code so that it can be used |
| 4780 | directly as an interrupt service routine. |
| 4781 | |
| 4782 | By default, the compiler will produce a function prologue and epilogue suitable for |
| 4783 | an interrupt service routine that handles an External Interrupt Controller (eic) |
| 4784 | generated interrupt. This behavior can be explicitly requested with the "eic" |
| 4785 | argument. |
| 4786 | |
| 4787 | Otherwise, for use with vectored interrupt mode, the argument passed should be |
| 4788 | of the form "vector=LEVEL" where LEVEL is one of the following values: |
| 4789 | "sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will |
| 4790 | then set the interrupt mask to the corresponding level which will mask all |
| 4791 | interrupts up to and including the argument. |
| 4792 | |
| 4793 | The semantics are as follows: |
| 4794 | |
| 4795 | - The prologue is modified so that the Exception Program Counter (EPC) and |
| 4796 | Status coprocessor registers are saved to the stack. The interrupt mask is |
| 4797 | set so that the function can only be interrupted by a higher priority |
| 4798 | interrupt. The epilogue will restore the previous values of EPC and Status. |
| 4799 | - The prologue and epilogue are modified to save and restore all non-kernel |
| 4800 | registers as necessary. |
| 4801 | - The FPU is disabled in the prologue, as the floating pointer registers are not |
| 4802 | spilled to the stack. |
| 4803 | - The function return sequence is changed to use an exception return instruction. |
| 4804 | - The parameter sets the interrupt mask for the function corresponding to the |
| 4805 | interrupt level specified. If no mask is specified the interrupt mask |
| 4806 | defaults to "eic".)reST" ; |
| 4807 | |
| 4808 | static const char AttrDoc_MipsLongCall[] = R"reST(Clang supports the `__attribute__((long_call))`, `__attribute__((far))`, |
| 4809 | and `__attribute__((near))` attributes on MIPS targets. These attributes may |
| 4810 | only be added to function declarations and change the code generated |
| 4811 | by the compiler when directly calling the function. The `near` attribute |
| 4812 | allows calls to the function to be made using the `jal` instruction, which |
| 4813 | requires the function to be located in the same naturally aligned 256MB |
| 4814 | segment as the caller. The `long_call` and `far` attributes are synonyms |
| 4815 | and require the use of a different call sequence that works regardless |
| 4816 | of the distance between the functions. |
| 4817 | |
| 4818 | These attributes have no effect for position-independent code. |
| 4819 | |
| 4820 | These attributes take priority over command line switches such |
| 4821 | as `-mlong-calls` and `-mno-long-calls`.)reST" ; |
| 4822 | |
| 4823 | static const char AttrDoc_MipsShortCall[] = R"reST(Clang supports the `__attribute__((long_call))`, `__attribute__((far))`, |
| 4824 | `__attribute__((short__call))`, and `__attribute__((near))` attributes |
| 4825 | on MIPS targets. These attributes may only be added to function declarations |
| 4826 | and change the code generated by the compiler when directly calling |
| 4827 | the function. The `short_call` and `near` attributes are synonyms and |
| 4828 | allow calls to the function to be made using the `jal` instruction, which |
| 4829 | requires the function to be located in the same naturally aligned 256MB segment |
| 4830 | as the caller. The `long_call` and `far` attributes are synonyms and |
| 4831 | require the use of a different call sequence that works regardless |
| 4832 | of the distance between the functions. |
| 4833 | |
| 4834 | These attributes have no effect for position-independent code. |
| 4835 | |
| 4836 | These attributes take priority over command line switches such |
| 4837 | as `-mlong-calls` and `-mno-long-calls`.)reST" ; |
| 4838 | |
| 4839 | static const char AttrDoc_Mode[] = R"reST(No documentation.)reST" ; |
| 4840 | |
| 4841 | static const char AttrDoc_ModularFormat[] = R"reST(The `modular_format` attribute can be applied to a function that bears the |
| 4842 | `format` attribute (or standard library functions) to indicate that the |
| 4843 | implementation is "modular", that is, that the implementation is logically |
| 4844 | divided into a number of named aspects. When the compiler can determine that |
| 4845 | not all aspects of the implementation are needed for a given call, the compiler |
| 4846 | may redirect the call to the identifier given as the first argument to the |
| 4847 | attribute (the modular implementation function). |
| 4848 | |
| 4849 | The second argument is an implementation name, and the remaining arguments are |
| 4850 | aspects of the format string for the compiler to report. The implementation |
| 4851 | name is an unevaluated identifier in the C namespace. |
| 4852 | |
| 4853 | The compiler reports that a call requires an aspect by issuing a relocation for |
| 4854 | the symbol `<impl_name>_<aspect>` at the point of the call. This arranges for |
| 4855 | code and data needed to support the aspect of the implementation to be brought |
| 4856 | into the link to satisfy weak references in the modular implemenation function. |
| 4857 | If the compiler does not understand an aspect, it must summarily consider any |
| 4858 | call to require that aspect. |
| 4859 | |
| 4860 | For example, say `printf` is annotated with |
| 4861 | `modular_format(__modular_printf, "__printf", "float")`. Then, a call to |
| 4862 | `printf(var, 42)` would be untouched. A call to `printf("%d", 42)` would |
| 4863 | become a call to `__modular_printf` with the same arguments, as would |
| 4864 | `printf("%f", 42.0)`. The latter would be accompanied with a strong |
| 4865 | relocation against the symbol `__printf_float`, which would bring floating |
| 4866 | point support for `printf` into the link. |
| 4867 | |
| 4868 | If the attribute appears more than once on a declaration, or across a chain of |
| 4869 | redeclarations, it is an error for the attributes to have different arguments, |
| 4870 | excepting that the aspects may be in any order. |
| 4871 | |
| 4872 | The following aspects are currently supported: |
| 4873 | |
| 4874 | - `fixed`: The call has a C ISO 18037 fixed-point argument. |
| 4875 | - `float`: The call has a floating-point argument.)reST" ; |
| 4876 | |
| 4877 | static const char AttrDoc_MustTail[] = R"reST(If a `return` statement is marked `musttail`, this indicates that the |
| 4878 | compiler must generate a tail call for the program to be correct, even when |
| 4879 | optimizations are disabled. This guarantees that the call will not cause |
| 4880 | unbounded stack growth if it is part of a recursive cycle in the call graph. |
| 4881 | |
| 4882 | If the callee is a virtual function that is implemented by a thunk, there is |
| 4883 | no guarantee in general that the thunk tail-calls the implementation of the |
| 4884 | virtual function, so such a call in a recursive cycle can still result in |
| 4885 | unbounded stack growth. |
| 4886 | |
| 4887 | `clang::musttail` can only be applied to a `return` statement whose value |
| 4888 | is the result of a function call (even functions returning void must use |
| 4889 | `return`, although no value is returned). The target function must have the |
| 4890 | same number of arguments as the caller. The types of the return value and all |
| 4891 | arguments must be similar according to C++ rules (differing only in cv |
| 4892 | qualifiers or array size), including the implicit "this" argument, if any. |
| 4893 | Any variables in scope, including all arguments to the function and the |
| 4894 | return value must be trivially destructible. The calling convention of the |
| 4895 | caller and callee must match, and they must not be variadic functions or have |
| 4896 | old style K&R C function declarations. |
| 4897 | |
| 4898 | The lifetimes of all local variables and function parameters end immediately |
| 4899 | before the call to the function. This means that it is undefined behaviour to |
| 4900 | pass a pointer or reference to a local variable to the called function, which |
| 4901 | is not the case without the attribute. Clang will emit a warning in common |
| 4902 | cases where this happens. |
| 4903 | |
| 4904 | `clang::musttail` provides assurances that the tail call can be optimized on |
| 4905 | all targets, not just one.)reST" ; |
| 4906 | |
| 4907 | static const char AttrDoc_NSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation |
| 4908 | (Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming |
| 4909 | convention (e.g. functions starting with "get" are assumed to return at |
| 4910 | `+0`). |
| 4911 | |
| 4912 | It can be overridden using a family of the following attributes. In |
| 4913 | Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to |
| 4914 | a function communicates that the object is returned at `+1`, and the caller |
| 4915 | is responsible for freeing it. |
| 4916 | Similarly, the annotation `__attribute__((ns_returns_not_retained))` |
| 4917 | specifies that the object is returned at `+0` and the ownership remains with |
| 4918 | the callee. |
| 4919 | The annotation `__attribute__((ns_consumes_self))` specifies that |
| 4920 | the Objective-C method call consumes the reference to `self`, e.g. by |
| 4921 | attaching it to a supplied parameter. |
| 4922 | Additionally, parameters can have an annotation |
| 4923 | `__attribute__((ns_consumed))`, which specifies that passing an owned object |
| 4924 | as that parameter effectively transfers the ownership, and the caller is no |
| 4925 | longer responsible for it. |
| 4926 | These attributes affect code generation when interacting with ARC code, and |
| 4927 | they are used by the Clang Static Analyzer. |
| 4928 | |
| 4929 | In C programs using CoreFoundation, a similar set of attributes: |
| 4930 | `__attribute__((cf_returns_not_retained))`, |
| 4931 | `__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))` |
| 4932 | have the same respective semantics when applied to CoreFoundation objects. |
| 4933 | These attributes affect code generation when interacting with ARC code, and |
| 4934 | they are used by the Clang Static Analyzer. |
| 4935 | |
| 4936 | Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), |
| 4937 | the same attribute family is present: |
| 4938 | `__attribute__((os_returns_not_retained))`, |
| 4939 | `__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`, |
| 4940 | with the same respective semantics. |
| 4941 | Similar to `__attribute__((ns_consumes_self))`, |
| 4942 | `__attribute__((os_consumes_this))` specifies that the method call consumes |
| 4943 | the reference to "this" (e.g., when attaching it to a different object supplied |
| 4944 | as a parameter). |
| 4945 | Out parameters (parameters the function is meant to write into, |
| 4946 | either via pointers-to-pointers or references-to-pointers) |
| 4947 | may be annotated with `__attribute__((os_returns_retained))` |
| 4948 | or `__attribute__((os_returns_not_retained))` which specifies that the object |
| 4949 | written into the out parameter should (or respectively should not) be released |
| 4950 | after use. |
| 4951 | Since often out parameters may or may not be written depending on the exit |
| 4952 | code of the function, |
| 4953 | annotations `__attribute__((os_returns_retained_on_zero))` |
| 4954 | and `__attribute__((os_returns_retained_on_non_zero))` specify that |
| 4955 | an out parameter at `+1` is written if and only if the function returns a zero |
| 4956 | (respectively non-zero) error code. |
| 4957 | Observe that return-code-dependent out parameter annotations are only |
| 4958 | available for retained out parameters, as non-retained object do not have to be |
| 4959 | released by the callee. |
| 4960 | These attributes are only used by the Clang Static Analyzer. |
| 4961 | |
| 4962 | The family of attributes `X_returns_X_retained` can be added to functions, |
| 4963 | C++ methods, and Objective-C methods and properties. |
| 4964 | Attributes `X_consumed` can be added to parameters of methods, functions, |
| 4965 | and Objective-C methods.)reST" ; |
| 4966 | |
| 4967 | static const char AttrDoc_NSConsumesSelf[] = R"reST(The behavior of a function with respect to reference counting for Foundation |
| 4968 | (Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming |
| 4969 | convention (e.g. functions starting with "get" are assumed to return at |
| 4970 | `+0`). |
| 4971 | |
| 4972 | It can be overridden using a family of the following attributes. In |
| 4973 | Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to |
| 4974 | a function communicates that the object is returned at `+1`, and the caller |
| 4975 | is responsible for freeing it. |
| 4976 | Similarly, the annotation `__attribute__((ns_returns_not_retained))` |
| 4977 | specifies that the object is returned at `+0` and the ownership remains with |
| 4978 | the callee. |
| 4979 | The annotation `__attribute__((ns_consumes_self))` specifies that |
| 4980 | the Objective-C method call consumes the reference to `self`, e.g. by |
| 4981 | attaching it to a supplied parameter. |
| 4982 | Additionally, parameters can have an annotation |
| 4983 | `__attribute__((ns_consumed))`, which specifies that passing an owned object |
| 4984 | as that parameter effectively transfers the ownership, and the caller is no |
| 4985 | longer responsible for it. |
| 4986 | These attributes affect code generation when interacting with ARC code, and |
| 4987 | they are used by the Clang Static Analyzer. |
| 4988 | |
| 4989 | In C programs using CoreFoundation, a similar set of attributes: |
| 4990 | `__attribute__((cf_returns_not_retained))`, |
| 4991 | `__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))` |
| 4992 | have the same respective semantics when applied to CoreFoundation objects. |
| 4993 | These attributes affect code generation when interacting with ARC code, and |
| 4994 | they are used by the Clang Static Analyzer. |
| 4995 | |
| 4996 | Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), |
| 4997 | the same attribute family is present: |
| 4998 | `__attribute__((os_returns_not_retained))`, |
| 4999 | `__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`, |
| 5000 | with the same respective semantics. |
| 5001 | Similar to `__attribute__((ns_consumes_self))`, |
| 5002 | `__attribute__((os_consumes_this))` specifies that the method call consumes |
| 5003 | the reference to "this" (e.g., when attaching it to a different object supplied |
| 5004 | as a parameter). |
| 5005 | Out parameters (parameters the function is meant to write into, |
| 5006 | either via pointers-to-pointers or references-to-pointers) |
| 5007 | may be annotated with `__attribute__((os_returns_retained))` |
| 5008 | or `__attribute__((os_returns_not_retained))` which specifies that the object |
| 5009 | written into the out parameter should (or respectively should not) be released |
| 5010 | after use. |
| 5011 | Since often out parameters may or may not be written depending on the exit |
| 5012 | code of the function, |
| 5013 | annotations `__attribute__((os_returns_retained_on_zero))` |
| 5014 | and `__attribute__((os_returns_retained_on_non_zero))` specify that |
| 5015 | an out parameter at `+1` is written if and only if the function returns a zero |
| 5016 | (respectively non-zero) error code. |
| 5017 | Observe that return-code-dependent out parameter annotations are only |
| 5018 | available for retained out parameters, as non-retained object do not have to be |
| 5019 | released by the callee. |
| 5020 | These attributes are only used by the Clang Static Analyzer. |
| 5021 | |
| 5022 | The family of attributes `X_returns_X_retained` can be added to functions, |
| 5023 | C++ methods, and Objective-C methods and properties. |
| 5024 | Attributes `X_consumed` can be added to parameters of methods, functions, |
| 5025 | and Objective-C methods.)reST" ; |
| 5026 | |
| 5027 | static const char AttrDoc_NSErrorDomain[] = R"reST(In Cocoa frameworks in Objective-C, one can group related error codes in enums |
| 5028 | and categorize these enums with error domains. |
| 5029 | |
| 5030 | The `ns_error_domain` attribute indicates a global `NSString` or |
| 5031 | `CFString` constant representing the error domain that an error code belongs |
| 5032 | to. For pointer uniqueness and code size this is a constant symbol, not a |
| 5033 | literal. |
| 5034 | |
| 5035 | The domain and error code need to be used together. The `ns_error_domain` |
| 5036 | attribute links error codes to their domain at the source level. |
| 5037 | |
| 5038 | This metadata is useful for documentation purposes, for static analysis, and for |
| 5039 | improving interoperability between Objective-C and Swift. It is not used for |
| 5040 | code generation in Objective-C. |
| 5041 | |
| 5042 | For example: |
| 5043 | |
| 5044 | ```objc |
| 5045 | #define NS_ERROR_ENUM(_type, _name, _domain) \ |
| 5046 | enum _name : _type _name; enum __attribute__((ns_error_domain(_domain))) _name : _type |
| 5047 | |
| 5048 | extern NSString *const MyErrorDomain; |
| 5049 | typedef NS_ERROR_ENUM(unsigned char, MyErrorEnum, MyErrorDomain) { |
| 5050 | MyErrFirst, |
| 5051 | MyErrSecond, |
| 5052 | }; |
| 5053 | ```)reST" ; |
| 5054 | |
| 5055 | static const char AttrDoc_NSReturnsAutoreleased[] = R"reST(The behavior of a function with respect to reference counting for Foundation |
| 5056 | (Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming |
| 5057 | convention (e.g. functions starting with "get" are assumed to return at |
| 5058 | `+0`). |
| 5059 | |
| 5060 | It can be overridden using a family of the following attributes. In |
| 5061 | Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to |
| 5062 | a function communicates that the object is returned at `+1`, and the caller |
| 5063 | is responsible for freeing it. |
| 5064 | Similarly, the annotation `__attribute__((ns_returns_not_retained))` |
| 5065 | specifies that the object is returned at `+0` and the ownership remains with |
| 5066 | the callee. |
| 5067 | The annotation `__attribute__((ns_consumes_self))` specifies that |
| 5068 | the Objective-C method call consumes the reference to `self`, e.g. by |
| 5069 | attaching it to a supplied parameter. |
| 5070 | Additionally, parameters can have an annotation |
| 5071 | `__attribute__((ns_consumed))`, which specifies that passing an owned object |
| 5072 | as that parameter effectively transfers the ownership, and the caller is no |
| 5073 | longer responsible for it. |
| 5074 | These attributes affect code generation when interacting with ARC code, and |
| 5075 | they are used by the Clang Static Analyzer. |
| 5076 | |
| 5077 | In C programs using CoreFoundation, a similar set of attributes: |
| 5078 | `__attribute__((cf_returns_not_retained))`, |
| 5079 | `__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))` |
| 5080 | have the same respective semantics when applied to CoreFoundation objects. |
| 5081 | These attributes affect code generation when interacting with ARC code, and |
| 5082 | they are used by the Clang Static Analyzer. |
| 5083 | |
| 5084 | Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), |
| 5085 | the same attribute family is present: |
| 5086 | `__attribute__((os_returns_not_retained))`, |
| 5087 | `__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`, |
| 5088 | with the same respective semantics. |
| 5089 | Similar to `__attribute__((ns_consumes_self))`, |
| 5090 | `__attribute__((os_consumes_this))` specifies that the method call consumes |
| 5091 | the reference to "this" (e.g., when attaching it to a different object supplied |
| 5092 | as a parameter). |
| 5093 | Out parameters (parameters the function is meant to write into, |
| 5094 | either via pointers-to-pointers or references-to-pointers) |
| 5095 | may be annotated with `__attribute__((os_returns_retained))` |
| 5096 | or `__attribute__((os_returns_not_retained))` which specifies that the object |
| 5097 | written into the out parameter should (or respectively should not) be released |
| 5098 | after use. |
| 5099 | Since often out parameters may or may not be written depending on the exit |
| 5100 | code of the function, |
| 5101 | annotations `__attribute__((os_returns_retained_on_zero))` |
| 5102 | and `__attribute__((os_returns_retained_on_non_zero))` specify that |
| 5103 | an out parameter at `+1` is written if and only if the function returns a zero |
| 5104 | (respectively non-zero) error code. |
| 5105 | Observe that return-code-dependent out parameter annotations are only |
| 5106 | available for retained out parameters, as non-retained object do not have to be |
| 5107 | released by the callee. |
| 5108 | These attributes are only used by the Clang Static Analyzer. |
| 5109 | |
| 5110 | The family of attributes `X_returns_X_retained` can be added to functions, |
| 5111 | C++ methods, and Objective-C methods and properties. |
| 5112 | Attributes `X_consumed` can be added to parameters of methods, functions, |
| 5113 | and Objective-C methods.)reST" ; |
| 5114 | |
| 5115 | static const char AttrDoc_NSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation |
| 5116 | (Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming |
| 5117 | convention (e.g. functions starting with "get" are assumed to return at |
| 5118 | `+0`). |
| 5119 | |
| 5120 | It can be overridden using a family of the following attributes. In |
| 5121 | Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to |
| 5122 | a function communicates that the object is returned at `+1`, and the caller |
| 5123 | is responsible for freeing it. |
| 5124 | Similarly, the annotation `__attribute__((ns_returns_not_retained))` |
| 5125 | specifies that the object is returned at `+0` and the ownership remains with |
| 5126 | the callee. |
| 5127 | The annotation `__attribute__((ns_consumes_self))` specifies that |
| 5128 | the Objective-C method call consumes the reference to `self`, e.g. by |
| 5129 | attaching it to a supplied parameter. |
| 5130 | Additionally, parameters can have an annotation |
| 5131 | `__attribute__((ns_consumed))`, which specifies that passing an owned object |
| 5132 | as that parameter effectively transfers the ownership, and the caller is no |
| 5133 | longer responsible for it. |
| 5134 | These attributes affect code generation when interacting with ARC code, and |
| 5135 | they are used by the Clang Static Analyzer. |
| 5136 | |
| 5137 | In C programs using CoreFoundation, a similar set of attributes: |
| 5138 | `__attribute__((cf_returns_not_retained))`, |
| 5139 | `__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))` |
| 5140 | have the same respective semantics when applied to CoreFoundation objects. |
| 5141 | These attributes affect code generation when interacting with ARC code, and |
| 5142 | they are used by the Clang Static Analyzer. |
| 5143 | |
| 5144 | Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), |
| 5145 | the same attribute family is present: |
| 5146 | `__attribute__((os_returns_not_retained))`, |
| 5147 | `__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`, |
| 5148 | with the same respective semantics. |
| 5149 | Similar to `__attribute__((ns_consumes_self))`, |
| 5150 | `__attribute__((os_consumes_this))` specifies that the method call consumes |
| 5151 | the reference to "this" (e.g., when attaching it to a different object supplied |
| 5152 | as a parameter). |
| 5153 | Out parameters (parameters the function is meant to write into, |
| 5154 | either via pointers-to-pointers or references-to-pointers) |
| 5155 | may be annotated with `__attribute__((os_returns_retained))` |
| 5156 | or `__attribute__((os_returns_not_retained))` which specifies that the object |
| 5157 | written into the out parameter should (or respectively should not) be released |
| 5158 | after use. |
| 5159 | Since often out parameters may or may not be written depending on the exit |
| 5160 | code of the function, |
| 5161 | annotations `__attribute__((os_returns_retained_on_zero))` |
| 5162 | and `__attribute__((os_returns_retained_on_non_zero))` specify that |
| 5163 | an out parameter at `+1` is written if and only if the function returns a zero |
| 5164 | (respectively non-zero) error code. |
| 5165 | Observe that return-code-dependent out parameter annotations are only |
| 5166 | available for retained out parameters, as non-retained object do not have to be |
| 5167 | released by the callee. |
| 5168 | These attributes are only used by the Clang Static Analyzer. |
| 5169 | |
| 5170 | The family of attributes `X_returns_X_retained` can be added to functions, |
| 5171 | C++ methods, and Objective-C methods and properties. |
| 5172 | Attributes `X_consumed` can be added to parameters of methods, functions, |
| 5173 | and Objective-C methods.)reST" ; |
| 5174 | |
| 5175 | static const char AttrDoc_NSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation |
| 5176 | (Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming |
| 5177 | convention (e.g. functions starting with "get" are assumed to return at |
| 5178 | `+0`). |
| 5179 | |
| 5180 | It can be overridden using a family of the following attributes. In |
| 5181 | Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to |
| 5182 | a function communicates that the object is returned at `+1`, and the caller |
| 5183 | is responsible for freeing it. |
| 5184 | Similarly, the annotation `__attribute__((ns_returns_not_retained))` |
| 5185 | specifies that the object is returned at `+0` and the ownership remains with |
| 5186 | the callee. |
| 5187 | The annotation `__attribute__((ns_consumes_self))` specifies that |
| 5188 | the Objective-C method call consumes the reference to `self`, e.g. by |
| 5189 | attaching it to a supplied parameter. |
| 5190 | Additionally, parameters can have an annotation |
| 5191 | `__attribute__((ns_consumed))`, which specifies that passing an owned object |
| 5192 | as that parameter effectively transfers the ownership, and the caller is no |
| 5193 | longer responsible for it. |
| 5194 | These attributes affect code generation when interacting with ARC code, and |
| 5195 | they are used by the Clang Static Analyzer. |
| 5196 | |
| 5197 | In C programs using CoreFoundation, a similar set of attributes: |
| 5198 | `__attribute__((cf_returns_not_retained))`, |
| 5199 | `__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))` |
| 5200 | have the same respective semantics when applied to CoreFoundation objects. |
| 5201 | These attributes affect code generation when interacting with ARC code, and |
| 5202 | they are used by the Clang Static Analyzer. |
| 5203 | |
| 5204 | Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), |
| 5205 | the same attribute family is present: |
| 5206 | `__attribute__((os_returns_not_retained))`, |
| 5207 | `__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`, |
| 5208 | with the same respective semantics. |
| 5209 | Similar to `__attribute__((ns_consumes_self))`, |
| 5210 | `__attribute__((os_consumes_this))` specifies that the method call consumes |
| 5211 | the reference to "this" (e.g., when attaching it to a different object supplied |
| 5212 | as a parameter). |
| 5213 | Out parameters (parameters the function is meant to write into, |
| 5214 | either via pointers-to-pointers or references-to-pointers) |
| 5215 | may be annotated with `__attribute__((os_returns_retained))` |
| 5216 | or `__attribute__((os_returns_not_retained))` which specifies that the object |
| 5217 | written into the out parameter should (or respectively should not) be released |
| 5218 | after use. |
| 5219 | Since often out parameters may or may not be written depending on the exit |
| 5220 | code of the function, |
| 5221 | annotations `__attribute__((os_returns_retained_on_zero))` |
| 5222 | and `__attribute__((os_returns_retained_on_non_zero))` specify that |
| 5223 | an out parameter at `+1` is written if and only if the function returns a zero |
| 5224 | (respectively non-zero) error code. |
| 5225 | Observe that return-code-dependent out parameter annotations are only |
| 5226 | available for retained out parameters, as non-retained object do not have to be |
| 5227 | released by the callee. |
| 5228 | These attributes are only used by the Clang Static Analyzer. |
| 5229 | |
| 5230 | The family of attributes `X_returns_X_retained` can be added to functions, |
| 5231 | C++ methods, and Objective-C methods and properties. |
| 5232 | Attributes `X_consumed` can be added to parameters of methods, functions, |
| 5233 | and Objective-C methods.)reST" ; |
| 5234 | |
| 5235 | static const char AttrDoc_Naked[] = R"reST(No documentation.)reST" ; |
| 5236 | |
| 5237 | static const char AttrDoc_NoAlias[] = R"reST(The `noalias` attribute indicates that the only memory accesses inside |
| 5238 | function are loads and stores from objects pointed to by its pointer-typed |
| 5239 | arguments, with arbitrary offsets.)reST" ; |
| 5240 | |
| 5241 | static const char AttrDoc_NoBuiltin[] = R"reST(The `__attribute__((no_builtin))` is similar to the `-fno-builtin` flag |
| 5242 | except it is specific to the body of a function. The attribute may also be |
| 5243 | applied to a virtual function but has no effect on the behavior of overriding |
| 5244 | functions in a derived class. |
| 5245 | |
| 5246 | It accepts one or more strings corresponding to the specific names of the |
| 5247 | builtins to disable (e.g. "memcpy", "memset"). |
| 5248 | If the attribute is used without parameters it will disable all buitins at |
| 5249 | once. |
| 5250 | |
| 5251 | ```c++ |
| 5252 | // The compiler is not allowed to add any builtin to foo's body. |
| 5253 | void foo(char* data, size_t count) __attribute__((no_builtin)) { |
| 5254 | // The compiler is not allowed to convert the loop into |
| 5255 | // `__builtin_memset(data, 0xFE, count);`. |
| 5256 | for (size_t i = 0; i < count; ++i) |
| 5257 | data[i] = 0xFE; |
| 5258 | } |
| 5259 | |
| 5260 | // The compiler is not allowed to add the `memcpy` builtin to bar's body. |
| 5261 | void bar(char* data, size_t count) __attribute__((no_builtin("memcpy"))) { |
| 5262 | // The compiler is allowed to convert the loop into |
| 5263 | // `__builtin_memset(data, 0xFE, count);` but cannot generate any |
| 5264 | // `__builtin_memcpy` |
| 5265 | for (size_t i = 0; i < count; ++i) |
| 5266 | data[i] = 0xFE; |
| 5267 | } |
| 5268 | ```)reST" ; |
| 5269 | |
| 5270 | static const char AttrDoc_NoCommon[] = R"reST(No documentation.)reST" ; |
| 5271 | |
| 5272 | static const char AttrDoc_NoConvergent[] = R"reST(This attribute prevents a function from being treated as convergent; when a |
| 5273 | function is marked `noconvergent`, calls to that function are not |
| 5274 | automatically assumed to be convergent, unless such calls are explicitly marked |
| 5275 | as `convergent`. If a statement is marked as `noconvergent`, any calls to |
| 5276 | inline `asm` in that statement are no longer treated as convergent. |
| 5277 | |
| 5278 | In languages following SPMD/SIMT programming model, e.g., CUDA/HIP, function |
| 5279 | declarations and inline asm calls are treated as convergent by default for |
| 5280 | correctness. This `noconvergent` attribute is helpful for developers to |
| 5281 | prevent them from being treated as convergent when it's safe. |
| 5282 | |
| 5283 | ```c |
| 5284 | __device__ float bar(float); |
| 5285 | __device__ float foo(float) __attribute__((noconvergent)) {} |
| 5286 | |
| 5287 | __device__ int example(void) { |
| 5288 | float x; |
| 5289 | [[clang::noconvergent]] x = bar(x); // no effect on convergence |
| 5290 | [[clang::noconvergent]] { asm volatile ("nop"); } // the asm call is non-convergent |
| 5291 | } |
| 5292 | ```)reST" ; |
| 5293 | |
| 5294 | static const char AttrDoc_NoDebug[] = R"reST(The `nodebug` attribute allows you to suppress debugging information for a |
| 5295 | function or method, for a variable that is not a parameter or a non-static |
| 5296 | data member, or for a typedef or using declaration.)reST" ; |
| 5297 | |
| 5298 | static const char AttrDoc_NoDeref[] = R"reST(The `noderef` attribute causes clang to diagnose dereferences of annotated pointer types. |
| 5299 | This is ideally used with pointers that point to special memory which cannot be read |
| 5300 | from or written to, but allowing for the pointer to be used in pointer arithmetic. |
| 5301 | The following are examples of valid expressions where dereferences are diagnosed: |
| 5302 | |
| 5303 | ```c |
| 5304 | int __attribute__((noderef)) *p; |
| 5305 | int x = *p; // warning |
| 5306 | |
| 5307 | int __attribute__((noderef)) **p2; |
| 5308 | x = **p2; // warning |
| 5309 | |
| 5310 | int * __attribute__((noderef)) *p3; |
| 5311 | p = *p3; // warning |
| 5312 | |
| 5313 | struct S { |
| 5314 | int a; |
| 5315 | }; |
| 5316 | struct S __attribute__((noderef)) *s; |
| 5317 | x = s->a; // warning |
| 5318 | x = (*s).a; // warning |
| 5319 | ``` |
| 5320 | |
| 5321 | Not all dereferences may diagnose a warning if the value directed by the pointer may not be |
| 5322 | accessed. The following are examples of valid expressions where may not be diagnosed: |
| 5323 | |
| 5324 | ```c |
| 5325 | int *q; |
| 5326 | int __attribute__((noderef)) *p; |
| 5327 | q = &*p; |
| 5328 | q = *&p; |
| 5329 | |
| 5330 | struct S { |
| 5331 | int a; |
| 5332 | }; |
| 5333 | struct S __attribute__((noderef)) *s; |
| 5334 | p = &s->a; |
| 5335 | p = &(*s).a; |
| 5336 | ``` |
| 5337 | |
| 5338 | `noderef` is currently only supported for pointers and arrays and not usable |
| 5339 | for references or Objective-C object pointers. |
| 5340 | |
| 5341 | ```c++ |
| 5342 | int x = 2; |
| 5343 | int __attribute__((noderef)) &y = x; // warning: 'noderef' can only be used on an array or pointer type |
| 5344 | ``` |
| 5345 | |
| 5346 | ```objc |
| 5347 | id __attribute__((noderef)) obj = [NSObject new]; // warning: 'noderef' can only be used on an array or pointer type |
| 5348 | ```)reST" ; |
| 5349 | |
| 5350 | static const char AttrDoc_NoDestroy[] = R"reST(The `no_destroy` attribute specifies that a variable with static or thread |
| 5351 | storage duration shouldn't have its exit-time destructor run. Annotating every |
| 5352 | static and thread duration variable with this attribute is equivalent to |
| 5353 | invoking clang with -fno-c++-static-destructors. |
| 5354 | |
| 5355 | If a variable is declared with this attribute, clang doesn't access check or |
| 5356 | generate the type's destructor. If you have a type that you only want to be |
| 5357 | annotated with `no_destroy`, you can therefore declare the destructor private: |
| 5358 | |
| 5359 | ```c++ |
| 5360 | struct only_no_destroy { |
| 5361 | only_no_destroy(); |
| 5362 | private: |
| 5363 | ~only_no_destroy(); |
| 5364 | }; |
| 5365 | |
| 5366 | [[clang::no_destroy]] only_no_destroy global; // fine! |
| 5367 | ``` |
| 5368 | |
| 5369 | Note that destructors are still required for subobjects of aggregates annotated |
| 5370 | with this attribute. This is because previously constructed subobjects need to |
| 5371 | be destroyed if an exception gets thrown before the initialization of the |
| 5372 | complete object is complete. For instance: |
| 5373 | |
| 5374 | ```c++ |
| 5375 | void f() { |
| 5376 | try { |
| 5377 | [[clang::no_destroy]] |
| 5378 | static only_no_destroy array[10]; // error, only_no_destroy has a private destructor. |
| 5379 | } catch (...) { |
| 5380 | // Handle the error |
| 5381 | } |
| 5382 | } |
| 5383 | ``` |
| 5384 | |
| 5385 | Here, if the construction of `array[9]` fails with an exception, `array[0..8]` |
| 5386 | will be destroyed, so the element's destructor needs to be accessible.)reST" ; |
| 5387 | |
| 5388 | static const char AttrDoc_NoDuplicate[] = R"reST(The `noduplicate` attribute can be placed on function declarations to control |
| 5389 | whether function calls to this function can be duplicated or not as a result of |
| 5390 | optimizations. This is required for the implementation of functions with |
| 5391 | certain special requirements, like the OpenCL "barrier" function, that might |
| 5392 | need to be run concurrently by all the threads that are executing in lockstep |
| 5393 | on the hardware. For example this attribute applied on the function |
| 5394 | "nodupfunc" in the code below avoids that: |
| 5395 | |
| 5396 | ```c |
| 5397 | void nodupfunc() __attribute__((noduplicate)); |
| 5398 | // Setting it as a C++11 attribute is also valid |
| 5399 | // void nodupfunc() [[clang::noduplicate]]; |
| 5400 | void foo(); |
| 5401 | void bar(); |
| 5402 | |
| 5403 | nodupfunc(); |
| 5404 | if (a > n) { |
| 5405 | foo(); |
| 5406 | } else { |
| 5407 | bar(); |
| 5408 | } |
| 5409 | ``` |
| 5410 | |
| 5411 | gets possibly modified by some optimizations into code similar to this: |
| 5412 | |
| 5413 | ```c |
| 5414 | if (a > n) { |
| 5415 | nodupfunc(); |
| 5416 | foo(); |
| 5417 | } else { |
| 5418 | nodupfunc(); |
| 5419 | bar(); |
| 5420 | } |
| 5421 | ``` |
| 5422 | |
| 5423 | where the call to "nodupfunc" is duplicated and sunk into the two branches |
| 5424 | of the condition.)reST" ; |
| 5425 | |
| 5426 | static const char AttrDoc_NoEscape[] = R"reST(`noescape` placed on a function parameter of a pointer type is used to inform |
| 5427 | the compiler that the pointer cannot escape: that is, no reference to the object |
| 5428 | the pointer points to that is derived from the parameter value will survive |
| 5429 | after the function returns. Users are responsible for making sure parameters |
| 5430 | annotated with `noescape` do not actually escape. The optimizer may make |
| 5431 | assumptions based on the fact that it knows that a call to the function does |
| 5432 | not escape a certain parameter, so incorrectly annotating a parameter with |
| 5433 | `noescape` leads to undefined behavior. The callee is also not allowed to |
| 5434 | deallocate memory through a `noescape` parameter: the optimizer does not make |
| 5435 | assumptions based on this information at the moment, but may do so in the |
| 5436 | future. Some cases of invalid uses of `noescape` can be found with |
| 5437 | {ref}`-Wlifetime-safety-noescape <Wlifetime-safety-noescape>`. |
| 5438 | |
| 5439 | For example: |
| 5440 | |
| 5441 | ```c |
| 5442 | int *gp; |
| 5443 | |
| 5444 | void nonescapingFunc(__attribute__((noescape)) int *p) { |
| 5445 | *p += 100; // OK. |
| 5446 | } |
| 5447 | |
| 5448 | void escapingFunc(__attribute__((noescape)) int *p) { |
| 5449 | gp = p; // Not OK. |
| 5450 | } |
| 5451 | |
| 5452 | void freeingFunc(__attribute__((noescape)) int *p) { |
| 5453 | free(p); // Not OK. |
| 5454 | } |
| 5455 | ``` |
| 5456 | |
| 5457 | Since `noescape` is a parameter attribute and not a type attribute, it only |
| 5458 | applies to the outermost pointer level, regardless of where in the parameter |
| 5459 | declaration you place it: |
| 5460 | |
| 5461 | ```c |
| 5462 | int **gp; |
| 5463 | |
| 5464 | void nestingEscapes(__attribute__((noescape)) int **p) { |
| 5465 | gp = p; // Not OK. |
| 5466 | *gp = *p; // OK, p does not escape. |
| 5467 | } |
| 5468 | ``` |
| 5469 | |
| 5470 | Additionally, when the parameter is a |
| 5471 | {doc}`block pointer <BlockLanguageSpec>`, the same restriction applies to |
| 5472 | copies of the block. For example: |
| 5473 | |
| 5474 | ```c |
| 5475 | typedef void (^BlockTy)(); |
| 5476 | BlockTy g0, g1; |
| 5477 | |
| 5478 | void nonescapingFunc(__attribute__((noescape)) BlockTy block) { |
| 5479 | block(); // OK. |
| 5480 | } |
| 5481 | |
| 5482 | void escapingFunc(__attribute__((noescape)) BlockTy block) { |
| 5483 | g0 = block; // Not OK. |
| 5484 | g1 = Block_copy(block); // Not OK either. |
| 5485 | } |
| 5486 | ``` |
| 5487 | |
| 5488 | The function *is* allowed to leak information about the memory address of the |
| 5489 | pointer, but not any provenance of the allocation: |
| 5490 | |
| 5491 | ```c |
| 5492 | bool isNull(__attribute__((noescape)) void *p) { |
| 5493 | return !p; // OK. |
| 5494 | } |
| 5495 | |
| 5496 | uintptr_t gi; |
| 5497 | |
| 5498 | void escapingAddress(__attribute__((noescape)) int *p) { |
| 5499 | // OK *if and only if* gi is never casted back to a pointer. |
| 5500 | gi = (uintptr_t)p; |
| 5501 | } |
| 5502 | |
| 5503 | bool usingEscapedAddress(int *p) { |
| 5504 | return (uintptr_t)p > gi; // OK. |
| 5505 | } |
| 5506 | |
| 5507 | bool usingEscapedPointer(int *p) { |
| 5508 | return p > (int*)gi; // Not OK. |
| 5509 | } |
| 5510 | |
| 5511 | int *gp; |
| 5512 | |
| 5513 | void escapingEndFunc(__attribute__((noescape)) int *p, size_t len) { |
| 5514 | gp = p + len; // Not OK. |
| 5515 | } |
| 5516 | ```)reST" ; |
| 5517 | |
| 5518 | static const char AttrDoc_NoFieldProtection[] = R"reST(No documentation.)reST" ; |
| 5519 | |
| 5520 | static const char AttrDoc_NoInline[] = R"reST(This function attribute suppresses the inlining of a function at the call sites |
| 5521 | of the function. |
| 5522 | |
| 5523 | `[[clang::noinline]]` spelling can be used as a statement attribute; other |
| 5524 | spellings of the attribute are not supported on statements. If a statement is |
| 5525 | marked `[[clang::noinline]]` and contains calls, those calls inside the |
| 5526 | statement will not be inlined by the compiler. |
| 5527 | |
| 5528 | `__noinline__` can be used as a keyword in CUDA/HIP languages. This is to |
| 5529 | avoid diagnostics due to usage of `__attribute__((__noinline__))` |
| 5530 | with `__noinline__` defined as a macro as `__attribute__((noinline))`. |
| 5531 | |
| 5532 | ```c |
| 5533 | int example(void) { |
| 5534 | int r; |
| 5535 | [[clang::noinline]] foo(); |
| 5536 | [[clang::noinline]] r = bar(); |
| 5537 | return r; |
| 5538 | } |
| 5539 | ```)reST" ; |
| 5540 | |
| 5541 | static const char AttrDoc_NoInstrumentFunction[] = R"reST(No documentation.)reST" ; |
| 5542 | |
| 5543 | static const char AttrDoc_NoMerge[] = R"reST(If a statement is marked `nomerge` and contains call expressions, those call |
| 5544 | expressions inside the statement will not be merged during optimization. This |
| 5545 | attribute can be used to prevent the optimizer from obscuring the source |
| 5546 | location of certain calls. For example, it will prevent tail merging otherwise |
| 5547 | identical code sequences that raise an exception or terminate the program. Tail |
| 5548 | merging normally reduces the precision of source location information, making |
| 5549 | stack traces less useful for debugging. This attribute gives the user control |
| 5550 | over the tradeoff between code size and debug information precision. |
| 5551 | |
| 5552 | `nomerge` attribute can also be used as function attribute to prevent all |
| 5553 | calls to the specified function from merging. It has no effect on indirect |
| 5554 | calls to such functions. For example: |
| 5555 | |
| 5556 | ```c++ |
| 5557 | [[clang::nomerge]] void foo(int) {} |
| 5558 | |
| 5559 | void bar(int x) { |
| 5560 | auto *ptr = foo; |
| 5561 | if (x) foo(1); else foo(2); // will not be merged |
| 5562 | if (x) ptr(1); else ptr(2); // indirect call, can be merged |
| 5563 | } |
| 5564 | ``` |
| 5565 | |
| 5566 | `nomerge` attribute can also be used for pointers to functions to |
| 5567 | prevent calls through such pointer from merging. In such case the |
| 5568 | effect applies only to a specific function pointer. For example: |
| 5569 | |
| 5570 | ```c++ |
| 5571 | [[clang::nomerge]] void (*foo)(int); |
| 5572 | |
| 5573 | void bar(int x) { |
| 5574 | auto *ptr = foo; |
| 5575 | if (x) foo(1); else foo(2); // will not be merged |
| 5576 | if (x) ptr(1); else ptr(2); // 'ptr' has no 'nomerge' attribute, can be merged |
| 5577 | } |
| 5578 | ```)reST" ; |
| 5579 | |
| 5580 | static const char AttrDoc_NoMicroMips[] = R"reST(Clang supports the GNU style `__attribute__((micromips))` and |
| 5581 | `__attribute__((nomicromips))` attributes on MIPS targets. These attributes |
| 5582 | may be attached to a function definition and instructs the backend to generate |
| 5583 | or not to generate microMIPS code for that function. |
| 5584 | |
| 5585 | These attributes override the `-mmicromips` and `-mno-micromips` options |
| 5586 | on the command line.)reST" ; |
| 5587 | |
| 5588 | static const char AttrDoc_NoMips16[] = R"reST(No documentation.)reST" ; |
| 5589 | |
| 5590 | static const char AttrDoc_NoOutline[] = R"reST(This function attribute suppresses outlining from the annotated function. |
| 5591 | |
| 5592 | Outlining is the process where common parts of separate functions are extracted |
| 5593 | into a separate function (or assembly snippet), and calls to that function or |
| 5594 | snippet are inserted in the original functions. In this way, it can be seen as |
| 5595 | the opposite of inlining. It can help to reduce code size.)reST" ; |
| 5596 | |
| 5597 | static const char AttrDoc_NoProfileFunction[] = R"reST(Use the `no_profile_instrument_function` attribute on a function declaration |
| 5598 | to denote that the compiler should not instrument the function with |
| 5599 | profile-related instrumentation, such as via the |
| 5600 | `-fprofile-generate` / `-fprofile-instr-generate` / |
| 5601 | `-fcs-profile-generate` / `-fprofile-arcs` flags.)reST" ; |
| 5602 | |
| 5603 | static const char AttrDoc_NoRandomizeLayout[] = R"reST(The attribute `randomize_layout`, when attached to a C structure, selects it |
| 5604 | for structure layout field randomization; a compile-time hardening technique. A |
| 5605 | "seed" value, is specified via the `-frandomize-layout-seed=` command line flag. |
| 5606 | For example: |
| 5607 | |
| 5608 | ```bash |
| 5609 | SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'` |
| 5610 | make ... CFLAGS="-frandomize-layout-seed=$SEED" ... |
| 5611 | ``` |
| 5612 | |
| 5613 | You can also supply the seed in a file with `-frandomize-layout-seed-file=`. |
| 5614 | For example: |
| 5615 | |
| 5616 | ```bash |
| 5617 | od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt |
| 5618 | make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ... |
| 5619 | ``` |
| 5620 | |
| 5621 | The randomization is deterministic based for a given seed, so the entire |
| 5622 | program should be compiled with the same seed, but keep the seed safe |
| 5623 | otherwise. |
| 5624 | |
| 5625 | The attribute `no_randomize_layout`, when attached to a C structure, |
| 5626 | instructs the compiler that this structure should not have its field layout |
| 5627 | randomized.)reST" ; |
| 5628 | |
| 5629 | static const char AttrDoc_NoReturn[] = R"reST(No documentation.)reST" ; |
| 5630 | |
| 5631 | static const char AttrDoc_NoSanitize[] = R"reST(Use the `no_sanitize` attribute on a function or a global variable |
| 5632 | declaration to specify that a particular instrumentation or set of |
| 5633 | instrumentations should not be applied. |
| 5634 | |
| 5635 | The attribute takes a list of string literals with the following accepted |
| 5636 | values: |
| 5637 | |
| 5638 | - all values accepted by `-fno-sanitize=`; |
| 5639 | - `coverage`, to disable SanitizerCoverage instrumentation. |
| 5640 | |
| 5641 | For example, `__attribute__((no_sanitize("address", "thread")))` specifies |
| 5642 | that AddressSanitizer and ThreadSanitizer should not be applied to the function |
| 5643 | or variable. Using `__attribute__((no_sanitize("coverage")))` specifies that |
| 5644 | SanitizerCoverage should not be applied to the function. |
| 5645 | |
| 5646 | See {ref}`Controlling Code Generation <controlling-code-generation>` for a |
| 5647 | full list of supported sanitizer flags.)reST" ; |
| 5648 | |
| 5649 | static const char AttrDoc_NoSpecializations[] = R"reST(``[[clang::no_specializations]]`` can be applied to function, class, or variable |
| 5650 | templates for which neither an explicit specialization nor a partial specialization should be declared by users. This is primarily |
| 5651 | used to diagnose user specializations of standard library type traits.)reST" ; |
| 5652 | |
| 5653 | static const char AttrDoc_NoSpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate |
| 5654 | that [Speculative Load Hardening][slh] is *not* needed for the function body. |
| 5655 | This can also be applied to a method in Objective C. This attribute will take |
| 5656 | precedence over the command line flag in the case where |
| 5657 | {option}`-mspeculative-load-hardening` is specified. |
| 5658 | |
| 5659 | Warning: This attribute may not prevent Speculative Load Hardening from being |
| 5660 | enabled for a function which inlines a function that has the |
| 5661 | 'speculative_load_hardening' attribute. This is intended to provide a |
| 5662 | maximally conservative model where the code that is marked with the |
| 5663 | 'speculative_load_hardening' attribute will always (even when inlined) |
| 5664 | be hardened. A user of this attribute may want to mark functions called by |
| 5665 | a function they do not want to be hardened with the 'noinline' attribute. |
| 5666 | |
| 5667 | For example: |
| 5668 | |
| 5669 | ```c |
| 5670 | __attribute__((speculative_load_hardening)) |
| 5671 | int foo(int i) { |
| 5672 | return i; |
| 5673 | } |
| 5674 | |
| 5675 | // Note: bar() may still have speculative load hardening enabled if |
| 5676 | // foo() is inlined into bar(). Mark foo() with __attribute__((noinline)) |
| 5677 | // to avoid this situation. |
| 5678 | __attribute__((no_speculative_load_hardening)) |
| 5679 | int bar(int i) { |
| 5680 | return foo(i); |
| 5681 | } |
| 5682 | ```)reST" ; |
| 5683 | |
| 5684 | static const char AttrDoc_NoSplitStack[] = R"reST(The `no_split_stack` attribute disables the emission of the split stack |
| 5685 | preamble for a particular function. It has no effect if `-fsplit-stack` |
| 5686 | is not specified.)reST" ; |
| 5687 | |
| 5688 | static const char AttrDoc_NoStackProtector[] = R"reST(Clang supports the GNU style `__attribute__((no_stack_protector))` and Microsoft |
| 5689 | style `__declspec(safebuffers)` attribute which disables |
| 5690 | the stack protector on the specified function. This attribute is useful for |
| 5691 | selectively disabling the stack protector on some functions when building with |
| 5692 | `-fstack-protector` compiler option. |
| 5693 | |
| 5694 | For example, it disables the stack protector for the function `foo` but function |
| 5695 | `bar` will still be built with the stack protector with the `-fstack-protector` |
| 5696 | option. |
| 5697 | |
| 5698 | ```c |
| 5699 | int __attribute__((no_stack_protector)) |
| 5700 | foo (int x); // stack protection will be disabled for foo. |
| 5701 | |
| 5702 | int bar(int y); // bar can be built with the stack protector. |
| 5703 | ```)reST" ; |
| 5704 | |
| 5705 | static const char AttrDoc_NoThreadSafetyAnalysis[] = R"reST(No documentation.)reST" ; |
| 5706 | |
| 5707 | static const char AttrDoc_NoThrow[] = R"reST(Clang supports the GNU style `__attribute__((nothrow))` and Microsoft style |
| 5708 | `__declspec(nothrow)` attribute as an equivalent of `noexcept` on function |
| 5709 | declarations. This attribute informs the compiler that the annotated function |
| 5710 | does not throw an exception. This prevents exception-unwinding. This attribute |
| 5711 | is particularly useful on functions in the C Standard Library that are |
| 5712 | guaranteed to not throw an exception.)reST" ; |
| 5713 | |
| 5714 | static const char AttrDoc_NoTrivialAutoVarInit[] = R"reST(The `__declspec(no_init_all)` attribute disables the automatic initialization |
| 5715 | that the {option}`-ftrivial-auto-var-init` flag would have applied to locals in |
| 5716 | a marked function, or instances of a marked type. Note that this attribute has |
| 5717 | no effect for locals that are automatically initialized without the |
| 5718 | {option}`-ftrivial-auto-var-init` flag.)reST" ; |
| 5719 | |
| 5720 | static const char AttrDoc_NoUniqueAddress[] = R"reST(The `no_unique_address` attribute allows tail padding in a non-static data |
| 5721 | member to overlap other members of the enclosing class (and in the special |
| 5722 | case when the type is empty, permits it to fully overlap other members). |
| 5723 | The field is laid out as if a base class were encountered at the corresponding |
| 5724 | point within the class (except that it does not share a vptr with the enclosing |
| 5725 | object). |
| 5726 | |
| 5727 | Example usage: |
| 5728 | |
| 5729 | ```c++ |
| 5730 | template<typename T, typename Alloc> struct my_vector { |
| 5731 | T *p; |
| 5732 | [[no_unique_address]] Alloc alloc; |
| 5733 | // ... |
| 5734 | }; |
| 5735 | static_assert(sizeof(my_vector<int, std::allocator<int>>) == sizeof(int*)); |
| 5736 | ``` |
| 5737 | |
| 5738 | `[[no_unique_address]]` is a standard C++20 attribute. Clang supports its use |
| 5739 | in C++11 onwards. |
| 5740 | |
| 5741 | On MSVC targets, `[[no_unique_address]]` is ignored; use |
| 5742 | `[[msvc::no_unique_address]]` instead. Currently there is no guarantee of ABI |
| 5743 | compatibility or stability with MSVC.)reST" ; |
| 5744 | |
| 5745 | static const char AttrDoc_NoUwtable[] = R"reST(Clang supports the `nouwtable` attribute which skips emitting |
| 5746 | the unwind table entry for the specified function. This attribute is useful for |
| 5747 | selectively emitting the unwind table entry on some functions when building with |
| 5748 | `-funwind-tables` compiler option.)reST" ; |
| 5749 | |
| 5750 | static const char AttrDoc_NonAllocating[] = R"reST(Declares that a function or function type either does or does not allocate heap memory, according |
| 5751 | to the optional, compile-time constant boolean argument, which defaults to true. When the argument |
| 5752 | is false, the attribute is equivalent to `allocating`.)reST" ; |
| 5753 | |
| 5754 | static const char AttrDoc_NonBlocking[] = R"reST(Declares that a function or function type either does or does not block in any way, according |
| 5755 | to the optional, compile-time constant boolean argument, which defaults to true. When the argument |
| 5756 | is false, the attribute is equivalent to `blocking`. |
| 5757 | |
| 5758 | For the purposes of diagnostics, `nonblocking` is considered to include the |
| 5759 | `nonallocating` guarantee and is therefore a "stronger" constraint or attribute.)reST" ; |
| 5760 | |
| 5761 | static const char AttrDoc_NonNull[] = R"reST(The `nonnull` attribute indicates that some function parameters must not be |
| 5762 | null, and can be used in several different ways. It's original usage |
| 5763 | ([from GCC](https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes)) |
| 5764 | is as a function (or Objective-C method) attribute that specifies which |
| 5765 | parameters of the function are nonnull in a comma-separated list. For example: |
| 5766 | |
| 5767 | ```c |
| 5768 | extern void * my_memcpy (void *dest, const void *src, size_t len) |
| 5769 | __attribute__((nonnull (1, 2))); |
| 5770 | ``` |
| 5771 | |
| 5772 | Here, the `nonnull` attribute indicates that parameters 1 and 2 |
| 5773 | cannot have a null value. Omitting the parenthesized list of parameter indices |
| 5774 | means that all parameters of pointer type cannot be null: |
| 5775 | |
| 5776 | ```c |
| 5777 | extern void * my_memcpy (void *dest, const void *src, size_t len) |
| 5778 | __attribute__((nonnull)); |
| 5779 | ``` |
| 5780 | |
| 5781 | Clang also allows the `nonnull` attribute to be placed directly on a function |
| 5782 | (or Objective-C method) parameter, eliminating the need to specify the |
| 5783 | parameter index ahead of type. For example: |
| 5784 | |
| 5785 | ```c |
| 5786 | extern void * my_memcpy (void *dest __attribute__((nonnull)), |
| 5787 | const void *src __attribute__((nonnull)), size_t len); |
| 5788 | ``` |
| 5789 | |
| 5790 | Note that the `nonnull` attribute indicates that passing null to a non-null |
| 5791 | parameter is undefined behavior, which the optimizer may take advantage of to, |
| 5792 | e.g., remove null checks. The `_Nonnull` type qualifier indicates that a |
| 5793 | pointer cannot be null in a more general manner (because it is part of the type |
| 5794 | system) and does not imply undefined behavior, making it more widely applicable.)reST" ; |
| 5795 | |
| 5796 | static const char AttrDoc_NonString[] = R"reST(The `nonstring` attribute can be applied to the declaration of a variable or |
| 5797 | a field whose type is a character pointer or character array to specify that |
| 5798 | the buffer is not intended to behave like a null-terminated string. This will |
| 5799 | silence diagnostics with code like: |
| 5800 | |
| 5801 | ```c |
| 5802 | char BadStr[3] = "foo"; // No space for the null terminator, diagnosed |
| 5803 | __attribute__((nonstring)) char NotAStr[3] = "foo"; // Not diagnosed |
| 5804 | ```)reST" ; |
| 5805 | |
| 5806 | static const char AttrDoc_NotTailCalled[] = R"reST(The `not_tail_called` attribute prevents tail-call optimization on statically |
| 5807 | bound calls. Objective-c methods, and functions marked as `always_inline` |
| 5808 | cannot be marked as `not_tail_called`. |
| 5809 | |
| 5810 | For example, it prevents tail-call optimization in the following case: |
| 5811 | |
| 5812 | ```c |
| 5813 | int __attribute__((not_tail_called)) foo1(int); |
| 5814 | |
| 5815 | int foo2(int a) { |
| 5816 | return foo1(a); // No tail-call optimization on direct calls. |
| 5817 | } |
| 5818 | ``` |
| 5819 | |
| 5820 | However, it doesn't prevent tail-call optimization in this case: |
| 5821 | |
| 5822 | ```c |
| 5823 | int __attribute__((not_tail_called)) foo1(int); |
| 5824 | |
| 5825 | int foo2(int a) { |
| 5826 | int (*fn)(int) = &foo1; |
| 5827 | |
| 5828 | // not_tail_called has no effect on an indirect call even if the call can |
| 5829 | // be resolved at compile time. |
| 5830 | return (*fn)(a); |
| 5831 | } |
| 5832 | ``` |
| 5833 | |
| 5834 | Generally, marking an overriding virtual function as `not_tail_called` is |
| 5835 | not useful, because this attribute is a property of the static type. Calls |
| 5836 | made through a pointer or reference to the base class type will respect |
| 5837 | the `not_tail_called` attribute of the base class's member function, |
| 5838 | regardless of the runtime destination of the call: |
| 5839 | |
| 5840 | ```c++ |
| 5841 | struct Foo { virtual void f(); }; |
| 5842 | struct Bar : Foo { |
| 5843 | [[clang::not_tail_called]] void f() override; |
| 5844 | }; |
| 5845 | void callera(Bar& bar) { |
| 5846 | Foo& foo = bar; |
| 5847 | // not_tail_called has no effect on here, even though the |
| 5848 | // underlying method is f from Bar. |
| 5849 | foo.f(); |
| 5850 | bar.f(); // No tail-call optimization on here. |
| 5851 | } |
| 5852 | ```)reST" ; |
| 5853 | |
| 5854 | static const char AttrDoc_OMPAllocateDecl[] = R"reST()reST" ; |
| 5855 | |
| 5856 | static const char AttrDoc_OMPAssume[] = R"reST(Clang supports the `[[omp::assume("assumption")]]` attribute to |
| 5857 | provide additional information to the optimizer. The string-literal, here |
| 5858 | "assumption", will be attached to the function declaration such that later |
| 5859 | analysis and optimization passes can assume the "assumption" to hold. |
| 5860 | This is similar to {ref}`__builtin_assume <langext-__builtin_assume>` but |
| 5861 | instead of an expression that can be assumed to be non-zero, the assumption is |
| 5862 | expressed as a string and it holds for the entire function. |
| 5863 | |
| 5864 | A function can have multiple assume attributes and they propagate from prior |
| 5865 | declarations to later definitions. Multiple assumptions are aggregated into a |
| 5866 | single comma separated string. Thus, one can provide multiple assumptions via |
| 5867 | a comma separated string, i.a., |
| 5868 | `[[omp::assume("assumption1,assumption2")]]`. |
| 5869 | |
| 5870 | While LLVM plugins might provide more assumption strings, the default LLVM |
| 5871 | optimization passes are aware of the following assumptions: |
| 5872 | |
| 5873 | ```none |
| 5874 | "omp_no_openmp" |
| 5875 | "omp_no_openmp_routines" |
| 5876 | "omp_no_parallelism" |
| 5877 | "omp_no_openmp_constructs" |
| 5878 | ``` |
| 5879 | |
| 5880 | The OpenMP standard defines the meaning of OpenMP assumptions ("omp_XYZ" is |
| 5881 | spelled "XYZ" in the [OpenMP 5.1 Standard][openmp 5.1 standard]). |
| 5882 | |
| 5883 | [openmp 5.1 standard]: https://www.openmp.org/spec-html/5.1/openmpsu37.html#x56-560002.5.2)reST" ; |
| 5884 | |
| 5885 | static const char AttrDoc_OMPCaptureKind[] = R"reST()reST" ; |
| 5886 | |
| 5887 | static const char AttrDoc_OMPCaptureNoInit[] = R"reST()reST" ; |
| 5888 | |
| 5889 | static const char AttrDoc_OMPDeclareSimdDecl[] = R"reST(The `declare simd` construct can be applied to a function to enable the creation |
| 5890 | of one or more versions that can process multiple arguments using SIMD |
| 5891 | instructions from a single invocation in a SIMD loop. The `declare simd` |
| 5892 | directive is a declarative directive. There may be multiple `declare simd` |
| 5893 | directives for a function. The use of a `declare simd` construct on a function |
| 5894 | enables the creation of SIMD versions of the associated function that can be |
| 5895 | used to process multiple arguments from a single invocation from a SIMD loop |
| 5896 | concurrently. |
| 5897 | The syntax of the `declare simd` construct is as follows: |
| 5898 | |
| 5899 | ```none |
| 5900 | #pragma omp declare simd [clause[[,] clause] ...] new-line |
| 5901 | [#pragma omp declare simd [clause[[,] clause] ...] new-line] |
| 5902 | [...] |
| 5903 | function definition or declaration |
| 5904 | ``` |
| 5905 | |
| 5906 | where clause is one of the following: |
| 5907 | |
| 5908 | ```none |
| 5909 | simdlen(length) |
| 5910 | linear(argument-list[:constant-linear-step]) |
| 5911 | aligned(argument-list[:alignment]) |
| 5912 | uniform(argument-list) |
| 5913 | inbranch |
| 5914 | notinbranch |
| 5915 | ```)reST" ; |
| 5916 | |
| 5917 | static const char AttrDoc_OMPDeclareTargetDecl[] = R"reST(The `declare target` directive specifies that variables and functions are mapped |
| 5918 | to a device for OpenMP offload mechanism. |
| 5919 | |
| 5920 | The syntax of the declare target directive is as follows: |
| 5921 | |
| 5922 | ```c |
| 5923 | #pragma omp declare target new-line |
| 5924 | declarations-definition-seq |
| 5925 | #pragma omp end declare target new-line |
| 5926 | ``` |
| 5927 | |
| 5928 | or |
| 5929 | |
| 5930 | ```c |
| 5931 | #pragma omp declare target (extended-list) new-line |
| 5932 | ``` |
| 5933 | |
| 5934 | or |
| 5935 | |
| 5936 | ```c |
| 5937 | #pragma omp declare target clause[ [,] clause ... ] new-line |
| 5938 | ``` |
| 5939 | |
| 5940 | where clause is one of the following: |
| 5941 | |
| 5942 | ```c |
| 5943 | to(extended-list) |
| 5944 | link(list) |
| 5945 | device_type(host | nohost | any) |
| 5946 | ```)reST" ; |
| 5947 | |
| 5948 | static const char AttrDoc_OMPDeclareVariant[] = R"reST(The `declare variant` directive declares a specialized variant of a base |
| 5949 | function and specifies the context in which that specialized variant is used. |
| 5950 | The declare variant directive is a declarative directive. |
| 5951 | The syntax of the `declare variant` construct is as follows: |
| 5952 | |
| 5953 | ```none |
| 5954 | #pragma omp declare variant(variant-func-id) clause new-line |
| 5955 | [#pragma omp declare variant(variant-func-id) clause new-line] |
| 5956 | [...] |
| 5957 | function definition or declaration |
| 5958 | ``` |
| 5959 | |
| 5960 | where clause is one of the following: |
| 5961 | |
| 5962 | ```none |
| 5963 | match(context-selector-specification) |
| 5964 | ``` |
| 5965 | |
| 5966 | and where `variant-func-id` is the name of a function variant that is either a |
| 5967 | base language identifier or, for C++, a template-id. |
| 5968 | |
| 5969 | Clang provides the following context selector extensions, used via |
| 5970 | `implementation={extension(EXTENSION)}`: |
| 5971 | |
| 5972 | ```none |
| 5973 | match_all |
| 5974 | match_any |
| 5975 | match_none |
| 5976 | disable_implicit_base |
| 5977 | allow_templates |
| 5978 | bind_to_declaration |
| 5979 | ``` |
| 5980 | |
| 5981 | The match extensions change when the *entire* context selector is considered a |
| 5982 | match for an OpenMP context. The default is `all`, with `none` no trait in the |
| 5983 | selector is allowed to be in the OpenMP context, with `any` a single trait in |
| 5984 | both the selector and OpenMP context is sufficient. Only a single match |
| 5985 | extension trait is allowed per context selector. |
| 5986 | The disable extensions remove default effects of the `begin declare variant` |
| 5987 | applied to a definition. If `disable_implicit_base` is given, we will not |
| 5988 | introduce an implicit base function for a variant if no base function was |
| 5989 | found. The variant is still generated but will never be called, due to the |
| 5990 | absence of a base function and consequently calls to a base function. |
| 5991 | The allow extensions change when the `begin declare variant` effect is |
| 5992 | applied to a definition. If `allow_templates` is given, template function |
| 5993 | definitions are considered as specializations of existing or assumed template |
| 5994 | declarations with the same name. The template parameters for the base functions |
| 5995 | are used to instantiate the specialization. If `bind_to_declaration` is given, |
| 5996 | apply the same variant rules to function declarations. This allows the user to |
| 5997 | override declarations with only a function declaration.)reST" ; |
| 5998 | |
| 5999 | static const char AttrDoc_OMPGroupPrivateDecl[] = R"reST()reST" ; |
| 6000 | |
| 6001 | static const char AttrDoc_OMPReferencedVar[] = R"reST()reST" ; |
| 6002 | |
| 6003 | static const char AttrDoc_OMPTargetIndirectCall[] = R"reST()reST" ; |
| 6004 | |
| 6005 | static const char AttrDoc_OMPThreadPrivateDecl[] = R"reST()reST" ; |
| 6006 | |
| 6007 | static const char AttrDoc_OSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation |
| 6008 | (Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming |
| 6009 | convention (e.g. functions starting with "get" are assumed to return at |
| 6010 | `+0`). |
| 6011 | |
| 6012 | It can be overridden using a family of the following attributes. In |
| 6013 | Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to |
| 6014 | a function communicates that the object is returned at `+1`, and the caller |
| 6015 | is responsible for freeing it. |
| 6016 | Similarly, the annotation `__attribute__((ns_returns_not_retained))` |
| 6017 | specifies that the object is returned at `+0` and the ownership remains with |
| 6018 | the callee. |
| 6019 | The annotation `__attribute__((ns_consumes_self))` specifies that |
| 6020 | the Objective-C method call consumes the reference to `self`, e.g. by |
| 6021 | attaching it to a supplied parameter. |
| 6022 | Additionally, parameters can have an annotation |
| 6023 | `__attribute__((ns_consumed))`, which specifies that passing an owned object |
| 6024 | as that parameter effectively transfers the ownership, and the caller is no |
| 6025 | longer responsible for it. |
| 6026 | These attributes affect code generation when interacting with ARC code, and |
| 6027 | they are used by the Clang Static Analyzer. |
| 6028 | |
| 6029 | In C programs using CoreFoundation, a similar set of attributes: |
| 6030 | `__attribute__((cf_returns_not_retained))`, |
| 6031 | `__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))` |
| 6032 | have the same respective semantics when applied to CoreFoundation objects. |
| 6033 | These attributes affect code generation when interacting with ARC code, and |
| 6034 | they are used by the Clang Static Analyzer. |
| 6035 | |
| 6036 | Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), |
| 6037 | the same attribute family is present: |
| 6038 | `__attribute__((os_returns_not_retained))`, |
| 6039 | `__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`, |
| 6040 | with the same respective semantics. |
| 6041 | Similar to `__attribute__((ns_consumes_self))`, |
| 6042 | `__attribute__((os_consumes_this))` specifies that the method call consumes |
| 6043 | the reference to "this" (e.g., when attaching it to a different object supplied |
| 6044 | as a parameter). |
| 6045 | Out parameters (parameters the function is meant to write into, |
| 6046 | either via pointers-to-pointers or references-to-pointers) |
| 6047 | may be annotated with `__attribute__((os_returns_retained))` |
| 6048 | or `__attribute__((os_returns_not_retained))` which specifies that the object |
| 6049 | written into the out parameter should (or respectively should not) be released |
| 6050 | after use. |
| 6051 | Since often out parameters may or may not be written depending on the exit |
| 6052 | code of the function, |
| 6053 | annotations `__attribute__((os_returns_retained_on_zero))` |
| 6054 | and `__attribute__((os_returns_retained_on_non_zero))` specify that |
| 6055 | an out parameter at `+1` is written if and only if the function returns a zero |
| 6056 | (respectively non-zero) error code. |
| 6057 | Observe that return-code-dependent out parameter annotations are only |
| 6058 | available for retained out parameters, as non-retained object do not have to be |
| 6059 | released by the callee. |
| 6060 | These attributes are only used by the Clang Static Analyzer. |
| 6061 | |
| 6062 | The family of attributes `X_returns_X_retained` can be added to functions, |
| 6063 | C++ methods, and Objective-C methods and properties. |
| 6064 | Attributes `X_consumed` can be added to parameters of methods, functions, |
| 6065 | and Objective-C methods.)reST" ; |
| 6066 | |
| 6067 | static const char AttrDoc_OSConsumesThis[] = R"reST(The behavior of a function with respect to reference counting for Foundation |
| 6068 | (Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming |
| 6069 | convention (e.g. functions starting with "get" are assumed to return at |
| 6070 | `+0`). |
| 6071 | |
| 6072 | It can be overridden using a family of the following attributes. In |
| 6073 | Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to |
| 6074 | a function communicates that the object is returned at `+1`, and the caller |
| 6075 | is responsible for freeing it. |
| 6076 | Similarly, the annotation `__attribute__((ns_returns_not_retained))` |
| 6077 | specifies that the object is returned at `+0` and the ownership remains with |
| 6078 | the callee. |
| 6079 | The annotation `__attribute__((ns_consumes_self))` specifies that |
| 6080 | the Objective-C method call consumes the reference to `self`, e.g. by |
| 6081 | attaching it to a supplied parameter. |
| 6082 | Additionally, parameters can have an annotation |
| 6083 | `__attribute__((ns_consumed))`, which specifies that passing an owned object |
| 6084 | as that parameter effectively transfers the ownership, and the caller is no |
| 6085 | longer responsible for it. |
| 6086 | These attributes affect code generation when interacting with ARC code, and |
| 6087 | they are used by the Clang Static Analyzer. |
| 6088 | |
| 6089 | In C programs using CoreFoundation, a similar set of attributes: |
| 6090 | `__attribute__((cf_returns_not_retained))`, |
| 6091 | `__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))` |
| 6092 | have the same respective semantics when applied to CoreFoundation objects. |
| 6093 | These attributes affect code generation when interacting with ARC code, and |
| 6094 | they are used by the Clang Static Analyzer. |
| 6095 | |
| 6096 | Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), |
| 6097 | the same attribute family is present: |
| 6098 | `__attribute__((os_returns_not_retained))`, |
| 6099 | `__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`, |
| 6100 | with the same respective semantics. |
| 6101 | Similar to `__attribute__((ns_consumes_self))`, |
| 6102 | `__attribute__((os_consumes_this))` specifies that the method call consumes |
| 6103 | the reference to "this" (e.g., when attaching it to a different object supplied |
| 6104 | as a parameter). |
| 6105 | Out parameters (parameters the function is meant to write into, |
| 6106 | either via pointers-to-pointers or references-to-pointers) |
| 6107 | may be annotated with `__attribute__((os_returns_retained))` |
| 6108 | or `__attribute__((os_returns_not_retained))` which specifies that the object |
| 6109 | written into the out parameter should (or respectively should not) be released |
| 6110 | after use. |
| 6111 | Since often out parameters may or may not be written depending on the exit |
| 6112 | code of the function, |
| 6113 | annotations `__attribute__((os_returns_retained_on_zero))` |
| 6114 | and `__attribute__((os_returns_retained_on_non_zero))` specify that |
| 6115 | an out parameter at `+1` is written if and only if the function returns a zero |
| 6116 | (respectively non-zero) error code. |
| 6117 | Observe that return-code-dependent out parameter annotations are only |
| 6118 | available for retained out parameters, as non-retained object do not have to be |
| 6119 | released by the callee. |
| 6120 | These attributes are only used by the Clang Static Analyzer. |
| 6121 | |
| 6122 | The family of attributes `X_returns_X_retained` can be added to functions, |
| 6123 | C++ methods, and Objective-C methods and properties. |
| 6124 | Attributes `X_consumed` can be added to parameters of methods, functions, |
| 6125 | and Objective-C methods.)reST" ; |
| 6126 | |
| 6127 | static const char AttrDoc_OSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation |
| 6128 | (Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming |
| 6129 | convention (e.g. functions starting with "get" are assumed to return at |
| 6130 | `+0`). |
| 6131 | |
| 6132 | It can be overridden using a family of the following attributes. In |
| 6133 | Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to |
| 6134 | a function communicates that the object is returned at `+1`, and the caller |
| 6135 | is responsible for freeing it. |
| 6136 | Similarly, the annotation `__attribute__((ns_returns_not_retained))` |
| 6137 | specifies that the object is returned at `+0` and the ownership remains with |
| 6138 | the callee. |
| 6139 | The annotation `__attribute__((ns_consumes_self))` specifies that |
| 6140 | the Objective-C method call consumes the reference to `self`, e.g. by |
| 6141 | attaching it to a supplied parameter. |
| 6142 | Additionally, parameters can have an annotation |
| 6143 | `__attribute__((ns_consumed))`, which specifies that passing an owned object |
| 6144 | as that parameter effectively transfers the ownership, and the caller is no |
| 6145 | longer responsible for it. |
| 6146 | These attributes affect code generation when interacting with ARC code, and |
| 6147 | they are used by the Clang Static Analyzer. |
| 6148 | |
| 6149 | In C programs using CoreFoundation, a similar set of attributes: |
| 6150 | `__attribute__((cf_returns_not_retained))`, |
| 6151 | `__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))` |
| 6152 | have the same respective semantics when applied to CoreFoundation objects. |
| 6153 | These attributes affect code generation when interacting with ARC code, and |
| 6154 | they are used by the Clang Static Analyzer. |
| 6155 | |
| 6156 | Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), |
| 6157 | the same attribute family is present: |
| 6158 | `__attribute__((os_returns_not_retained))`, |
| 6159 | `__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`, |
| 6160 | with the same respective semantics. |
| 6161 | Similar to `__attribute__((ns_consumes_self))`, |
| 6162 | `__attribute__((os_consumes_this))` specifies that the method call consumes |
| 6163 | the reference to "this" (e.g., when attaching it to a different object supplied |
| 6164 | as a parameter). |
| 6165 | Out parameters (parameters the function is meant to write into, |
| 6166 | either via pointers-to-pointers or references-to-pointers) |
| 6167 | may be annotated with `__attribute__((os_returns_retained))` |
| 6168 | or `__attribute__((os_returns_not_retained))` which specifies that the object |
| 6169 | written into the out parameter should (or respectively should not) be released |
| 6170 | after use. |
| 6171 | Since often out parameters may or may not be written depending on the exit |
| 6172 | code of the function, |
| 6173 | annotations `__attribute__((os_returns_retained_on_zero))` |
| 6174 | and `__attribute__((os_returns_retained_on_non_zero))` specify that |
| 6175 | an out parameter at `+1` is written if and only if the function returns a zero |
| 6176 | (respectively non-zero) error code. |
| 6177 | Observe that return-code-dependent out parameter annotations are only |
| 6178 | available for retained out parameters, as non-retained object do not have to be |
| 6179 | released by the callee. |
| 6180 | These attributes are only used by the Clang Static Analyzer. |
| 6181 | |
| 6182 | The family of attributes `X_returns_X_retained` can be added to functions, |
| 6183 | C++ methods, and Objective-C methods and properties. |
| 6184 | Attributes `X_consumed` can be added to parameters of methods, functions, |
| 6185 | and Objective-C methods.)reST" ; |
| 6186 | |
| 6187 | static const char AttrDoc_OSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation |
| 6188 | (Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming |
| 6189 | convention (e.g. functions starting with "get" are assumed to return at |
| 6190 | `+0`). |
| 6191 | |
| 6192 | It can be overridden using a family of the following attributes. In |
| 6193 | Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to |
| 6194 | a function communicates that the object is returned at `+1`, and the caller |
| 6195 | is responsible for freeing it. |
| 6196 | Similarly, the annotation `__attribute__((ns_returns_not_retained))` |
| 6197 | specifies that the object is returned at `+0` and the ownership remains with |
| 6198 | the callee. |
| 6199 | The annotation `__attribute__((ns_consumes_self))` specifies that |
| 6200 | the Objective-C method call consumes the reference to `self`, e.g. by |
| 6201 | attaching it to a supplied parameter. |
| 6202 | Additionally, parameters can have an annotation |
| 6203 | `__attribute__((ns_consumed))`, which specifies that passing an owned object |
| 6204 | as that parameter effectively transfers the ownership, and the caller is no |
| 6205 | longer responsible for it. |
| 6206 | These attributes affect code generation when interacting with ARC code, and |
| 6207 | they are used by the Clang Static Analyzer. |
| 6208 | |
| 6209 | In C programs using CoreFoundation, a similar set of attributes: |
| 6210 | `__attribute__((cf_returns_not_retained))`, |
| 6211 | `__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))` |
| 6212 | have the same respective semantics when applied to CoreFoundation objects. |
| 6213 | These attributes affect code generation when interacting with ARC code, and |
| 6214 | they are used by the Clang Static Analyzer. |
| 6215 | |
| 6216 | Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), |
| 6217 | the same attribute family is present: |
| 6218 | `__attribute__((os_returns_not_retained))`, |
| 6219 | `__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`, |
| 6220 | with the same respective semantics. |
| 6221 | Similar to `__attribute__((ns_consumes_self))`, |
| 6222 | `__attribute__((os_consumes_this))` specifies that the method call consumes |
| 6223 | the reference to "this" (e.g., when attaching it to a different object supplied |
| 6224 | as a parameter). |
| 6225 | Out parameters (parameters the function is meant to write into, |
| 6226 | either via pointers-to-pointers or references-to-pointers) |
| 6227 | may be annotated with `__attribute__((os_returns_retained))` |
| 6228 | or `__attribute__((os_returns_not_retained))` which specifies that the object |
| 6229 | written into the out parameter should (or respectively should not) be released |
| 6230 | after use. |
| 6231 | Since often out parameters may or may not be written depending on the exit |
| 6232 | code of the function, |
| 6233 | annotations `__attribute__((os_returns_retained_on_zero))` |
| 6234 | and `__attribute__((os_returns_retained_on_non_zero))` specify that |
| 6235 | an out parameter at `+1` is written if and only if the function returns a zero |
| 6236 | (respectively non-zero) error code. |
| 6237 | Observe that return-code-dependent out parameter annotations are only |
| 6238 | available for retained out parameters, as non-retained object do not have to be |
| 6239 | released by the callee. |
| 6240 | These attributes are only used by the Clang Static Analyzer. |
| 6241 | |
| 6242 | The family of attributes `X_returns_X_retained` can be added to functions, |
| 6243 | C++ methods, and Objective-C methods and properties. |
| 6244 | Attributes `X_consumed` can be added to parameters of methods, functions, |
| 6245 | and Objective-C methods.)reST" ; |
| 6246 | |
| 6247 | static const char AttrDoc_OSReturnsRetainedOnNonZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation |
| 6248 | (Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming |
| 6249 | convention (e.g. functions starting with "get" are assumed to return at |
| 6250 | `+0`). |
| 6251 | |
| 6252 | It can be overridden using a family of the following attributes. In |
| 6253 | Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to |
| 6254 | a function communicates that the object is returned at `+1`, and the caller |
| 6255 | is responsible for freeing it. |
| 6256 | Similarly, the annotation `__attribute__((ns_returns_not_retained))` |
| 6257 | specifies that the object is returned at `+0` and the ownership remains with |
| 6258 | the callee. |
| 6259 | The annotation `__attribute__((ns_consumes_self))` specifies that |
| 6260 | the Objective-C method call consumes the reference to `self`, e.g. by |
| 6261 | attaching it to a supplied parameter. |
| 6262 | Additionally, parameters can have an annotation |
| 6263 | `__attribute__((ns_consumed))`, which specifies that passing an owned object |
| 6264 | as that parameter effectively transfers the ownership, and the caller is no |
| 6265 | longer responsible for it. |
| 6266 | These attributes affect code generation when interacting with ARC code, and |
| 6267 | they are used by the Clang Static Analyzer. |
| 6268 | |
| 6269 | In C programs using CoreFoundation, a similar set of attributes: |
| 6270 | `__attribute__((cf_returns_not_retained))`, |
| 6271 | `__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))` |
| 6272 | have the same respective semantics when applied to CoreFoundation objects. |
| 6273 | These attributes affect code generation when interacting with ARC code, and |
| 6274 | they are used by the Clang Static Analyzer. |
| 6275 | |
| 6276 | Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), |
| 6277 | the same attribute family is present: |
| 6278 | `__attribute__((os_returns_not_retained))`, |
| 6279 | `__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`, |
| 6280 | with the same respective semantics. |
| 6281 | Similar to `__attribute__((ns_consumes_self))`, |
| 6282 | `__attribute__((os_consumes_this))` specifies that the method call consumes |
| 6283 | the reference to "this" (e.g., when attaching it to a different object supplied |
| 6284 | as a parameter). |
| 6285 | Out parameters (parameters the function is meant to write into, |
| 6286 | either via pointers-to-pointers or references-to-pointers) |
| 6287 | may be annotated with `__attribute__((os_returns_retained))` |
| 6288 | or `__attribute__((os_returns_not_retained))` which specifies that the object |
| 6289 | written into the out parameter should (or respectively should not) be released |
| 6290 | after use. |
| 6291 | Since often out parameters may or may not be written depending on the exit |
| 6292 | code of the function, |
| 6293 | annotations `__attribute__((os_returns_retained_on_zero))` |
| 6294 | and `__attribute__((os_returns_retained_on_non_zero))` specify that |
| 6295 | an out parameter at `+1` is written if and only if the function returns a zero |
| 6296 | (respectively non-zero) error code. |
| 6297 | Observe that return-code-dependent out parameter annotations are only |
| 6298 | available for retained out parameters, as non-retained object do not have to be |
| 6299 | released by the callee. |
| 6300 | These attributes are only used by the Clang Static Analyzer. |
| 6301 | |
| 6302 | The family of attributes `X_returns_X_retained` can be added to functions, |
| 6303 | C++ methods, and Objective-C methods and properties. |
| 6304 | Attributes `X_consumed` can be added to parameters of methods, functions, |
| 6305 | and Objective-C methods.)reST" ; |
| 6306 | |
| 6307 | static const char AttrDoc_OSReturnsRetainedOnZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation |
| 6308 | (Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming |
| 6309 | convention (e.g. functions starting with "get" are assumed to return at |
| 6310 | `+0`). |
| 6311 | |
| 6312 | It can be overridden using a family of the following attributes. In |
| 6313 | Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to |
| 6314 | a function communicates that the object is returned at `+1`, and the caller |
| 6315 | is responsible for freeing it. |
| 6316 | Similarly, the annotation `__attribute__((ns_returns_not_retained))` |
| 6317 | specifies that the object is returned at `+0` and the ownership remains with |
| 6318 | the callee. |
| 6319 | The annotation `__attribute__((ns_consumes_self))` specifies that |
| 6320 | the Objective-C method call consumes the reference to `self`, e.g. by |
| 6321 | attaching it to a supplied parameter. |
| 6322 | Additionally, parameters can have an annotation |
| 6323 | `__attribute__((ns_consumed))`, which specifies that passing an owned object |
| 6324 | as that parameter effectively transfers the ownership, and the caller is no |
| 6325 | longer responsible for it. |
| 6326 | These attributes affect code generation when interacting with ARC code, and |
| 6327 | they are used by the Clang Static Analyzer. |
| 6328 | |
| 6329 | In C programs using CoreFoundation, a similar set of attributes: |
| 6330 | `__attribute__((cf_returns_not_retained))`, |
| 6331 | `__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))` |
| 6332 | have the same respective semantics when applied to CoreFoundation objects. |
| 6333 | These attributes affect code generation when interacting with ARC code, and |
| 6334 | they are used by the Clang Static Analyzer. |
| 6335 | |
| 6336 | Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject), |
| 6337 | the same attribute family is present: |
| 6338 | `__attribute__((os_returns_not_retained))`, |
| 6339 | `__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`, |
| 6340 | with the same respective semantics. |
| 6341 | Similar to `__attribute__((ns_consumes_self))`, |
| 6342 | `__attribute__((os_consumes_this))` specifies that the method call consumes |
| 6343 | the reference to "this" (e.g., when attaching it to a different object supplied |
| 6344 | as a parameter). |
| 6345 | Out parameters (parameters the function is meant to write into, |
| 6346 | either via pointers-to-pointers or references-to-pointers) |
| 6347 | may be annotated with `__attribute__((os_returns_retained))` |
| 6348 | or `__attribute__((os_returns_not_retained))` which specifies that the object |
| 6349 | written into the out parameter should (or respectively should not) be released |
| 6350 | after use. |
| 6351 | Since often out parameters may or may not be written depending on the exit |
| 6352 | code of the function, |
| 6353 | annotations `__attribute__((os_returns_retained_on_zero))` |
| 6354 | and `__attribute__((os_returns_retained_on_non_zero))` specify that |
| 6355 | an out parameter at `+1` is written if and only if the function returns a zero |
| 6356 | (respectively non-zero) error code. |
| 6357 | Observe that return-code-dependent out parameter annotations are only |
| 6358 | available for retained out parameters, as non-retained object do not have to be |
| 6359 | released by the callee. |
| 6360 | These attributes are only used by the Clang Static Analyzer. |
| 6361 | |
| 6362 | The family of attributes `X_returns_X_retained` can be added to functions, |
| 6363 | C++ methods, and Objective-C methods and properties. |
| 6364 | Attributes `X_consumed` can be added to parameters of methods, functions, |
| 6365 | and Objective-C methods.)reST" ; |
| 6366 | |
| 6367 | static const char AttrDoc_ObjCBoxable[] = R"reST(Structs and unions marked with the `objc_boxable` attribute can be used |
| 6368 | with the Objective-C boxed expression syntax, `@(...)`. |
| 6369 | |
| 6370 | **Usage**: `__attribute__((objc_boxable))`. This attribute |
| 6371 | can only be placed on a declaration of a trivially-copyable struct or union: |
| 6372 | |
| 6373 | ```objc |
| 6374 | struct __attribute__((objc_boxable)) some_struct { |
| 6375 | int i; |
| 6376 | }; |
| 6377 | union __attribute__((objc_boxable)) some_union { |
| 6378 | int i; |
| 6379 | float f; |
| 6380 | }; |
| 6381 | typedef struct __attribute__((objc_boxable)) _some_struct some_struct; |
| 6382 | |
| 6383 | // ... |
| 6384 | |
| 6385 | some_struct ss; |
| 6386 | NSValue *boxed = @(ss); |
| 6387 | ```)reST" ; |
| 6388 | |
| 6389 | static const char AttrDoc_ObjCBridge[] = R"reST(No documentation.)reST" ; |
| 6390 | |
| 6391 | static const char AttrDoc_ObjCBridgeMutable[] = R"reST(No documentation.)reST" ; |
| 6392 | |
| 6393 | static const char AttrDoc_ObjCBridgeRelated[] = R"reST(No documentation.)reST" ; |
| 6394 | |
| 6395 | static const char AttrDoc_ObjCClassStub[] = R"reST(This attribute specifies that the Objective-C class to which it applies is |
| 6396 | instantiated at runtime. |
| 6397 | |
| 6398 | Unlike `__attribute__((objc_runtime_visible))`, a class having this attribute |
| 6399 | still has a "class stub" that is visible to the linker. This allows categories |
| 6400 | to be defined. Static message sends with the class as a receiver use a special |
| 6401 | access pattern to ensure the class is lazily instantiated from the class stub. |
| 6402 | |
| 6403 | Classes annotated with this attribute cannot be subclassed and cannot have |
| 6404 | implementations defined for them. This attribute is intended for use in |
| 6405 | Swift-generated headers for classes defined in Swift. |
| 6406 | |
| 6407 | Adding or removing this attribute to a class is an ABI-breaking change.)reST" ; |
| 6408 | |
| 6409 | static const char AttrDoc_ObjCDesignatedInitializer[] = R"reST(No documentation.)reST" ; |
| 6410 | |
| 6411 | static const char AttrDoc_ObjCDirect[] = R"reST(The `objc_direct` attribute can be used to mark an Objective-C method as |
| 6412 | being *direct*. A direct method is treated statically like an ordinary method, |
| 6413 | but dynamically it behaves more like a C function. This lowers some of the costs |
| 6414 | associated with the method but also sacrifices some of the ordinary capabilities |
| 6415 | of Objective-C methods. |
| 6416 | |
| 6417 | A message send of a direct method calls the implementation directly, as if it |
| 6418 | were a C function, rather than using ordinary Objective-C method dispatch. This |
| 6419 | is substantially faster and potentially allows the implementation to be inlined, |
| 6420 | but it also means the method cannot be overridden in subclasses or replaced |
| 6421 | dynamically, as ordinary Objective-C methods can. |
| 6422 | |
| 6423 | Furthermore, a direct method is not listed in the class's method lists. This |
| 6424 | substantially reduces the code-size overhead of the method but also means it |
| 6425 | cannot be called dynamically using ordinary Objective-C method dispatch at all; |
| 6426 | in particular, this means that it cannot override a superclass method or satisfy |
| 6427 | a protocol requirement. |
| 6428 | |
| 6429 | Because a direct method cannot be overridden, it is an error to perform |
| 6430 | a `super` message send of one. |
| 6431 | |
| 6432 | Although a message send of a direct method causes the method to be called |
| 6433 | directly as if it were a C function, it still obeys Objective-C semantics in other |
| 6434 | ways: |
| 6435 | |
| 6436 | - If the receiver is `nil`, the message send does nothing and returns the zero value |
| 6437 | for the return type. |
| 6438 | - A message send of a direct class method will cause the class to be initialized, |
| 6439 | including calling the `+initialize` method if present. |
| 6440 | - The implicit `_cmd` parameter containing the method's selector is still defined. |
| 6441 | In order to minimize code-size costs, the implementation will not emit a reference |
| 6442 | to the selector if the parameter is unused within the method. |
| 6443 | |
| 6444 | Symbols for direct method implementations are implicitly given hidden |
| 6445 | visibility, meaning that they can only be called within the same linkage unit. |
| 6446 | |
| 6447 | It is an error to do any of the following: |
| 6448 | |
| 6449 | - declare a direct method in a protocol, |
| 6450 | - declare an override of a direct method with a method in a subclass, |
| 6451 | - declare an override of a non-direct method with a direct method in a subclass, |
| 6452 | - declare a method with different directness in different class interfaces, or |
| 6453 | - implement a non-direct method (as declared in any class interface) with a direct method. |
| 6454 | |
| 6455 | If any of these rules would be violated if every method defined in an |
| 6456 | `@implementation` within a single linkage unit were declared in an |
| 6457 | appropriate class interface, the program is ill-formed with no diagnostic |
| 6458 | required. If a violation of this rule is not diagnosed, behavior remains |
| 6459 | well-defined; this paragraph is simply reserving the right to diagnose such |
| 6460 | conflicts in the future, not to treat them as undefined behavior. |
| 6461 | |
| 6462 | Additionally, Clang will warn about any `@selector` expression that |
| 6463 | names a selector that is only known to be used for direct methods. |
| 6464 | |
| 6465 | For the purpose of these rules, a "class interface" includes a class's primary |
| 6466 | `@interface` block, its class extensions, its categories, its declared protocols, |
| 6467 | and all the class interfaces of its superclasses. |
| 6468 | |
| 6469 | An Objective-C property can be declared with the `direct` property |
| 6470 | attribute. If a direct property declaration causes an implicit declaration of |
| 6471 | a getter or setter method (that is, if the given method is not explicitly |
| 6472 | declared elsewhere), the method is declared to be direct. |
| 6473 | |
| 6474 | Some programmers may wish to make many methods direct at once. In order |
| 6475 | to simplify this, the `objc_direct_members` attribute is provided; see its |
| 6476 | documentation for more information.)reST" ; |
| 6477 | |
| 6478 | static const char AttrDoc_ObjCDirectMembers[] = R"reST(The `objc_direct_members` attribute can be placed on an Objective-C |
| 6479 | `@interface` or `@implementation` to mark that methods declared |
| 6480 | therein should be considered direct by default. See the documentation |
| 6481 | for `objc_direct` for more information about direct methods. |
| 6482 | |
| 6483 | When `objc_direct_members` is placed on an `@interface` block, every |
| 6484 | method in the block is considered to be declared as direct. This includes any |
| 6485 | implicit method declarations introduced by property declarations. If the method |
| 6486 | redeclares a non-direct method, the declaration is ill-formed, exactly as if the |
| 6487 | method was annotated with the `objc_direct` attribute. |
| 6488 | |
| 6489 | When `objc_direct_members` is placed on an `@implementation` block, |
| 6490 | methods defined in the block are considered to be declared as direct unless |
| 6491 | they have been previously declared as non-direct in any interface of the class. |
| 6492 | This includes the implicit method definitions introduced by synthesized |
| 6493 | properties, including auto-synthesized properties.)reST" ; |
| 6494 | |
| 6495 | static const char AttrDoc_ObjCException[] = R"reST(No documentation.)reST" ; |
| 6496 | |
| 6497 | static const char AttrDoc_ObjCExplicitProtocolImpl[] = R"reST(No documentation.)reST" ; |
| 6498 | |
| 6499 | static const char AttrDoc_ObjCExternallyRetained[] = R"reST(The `objc_externally_retained` attribute can be applied to strong local |
| 6500 | variables, functions, methods, or blocks to opt into |
| 6501 | {ref}`externally-retained semantics <arc.misc.externally_retained>`. |
| 6502 | |
| 6503 | When applied to the definition of a function, method, or block, every parameter |
| 6504 | of the function with implicit strong retainable object pointer type is |
| 6505 | considered externally-retained, and becomes `const`. By explicitly annotating |
| 6506 | a parameter with `__strong`, you can opt back into the default |
| 6507 | non-externally-retained behavior for that parameter. For instance, |
| 6508 | `first_param` is externally-retained below, but not `second_param`: |
| 6509 | |
| 6510 | ```objc |
| 6511 | __attribute__((objc_externally_retained)) |
| 6512 | void f(NSArray *first_param, __strong NSArray *second_param) { |
| 6513 | // ... |
| 6514 | } |
| 6515 | ``` |
| 6516 | |
| 6517 | Likewise, when applied to a strong local variable, that variable becomes |
| 6518 | `const` and is considered externally-retained. |
| 6519 | |
| 6520 | When compiled without `-fobjc-arc`, this attribute is ignored.)reST" ; |
| 6521 | |
| 6522 | static const char AttrDoc_ObjCGC[] = R"reST(No documentation.)reST" ; |
| 6523 | |
| 6524 | static const char AttrDoc_ObjCIndependentClass[] = R"reST(No documentation.)reST" ; |
| 6525 | |
| 6526 | static const char AttrDoc_ObjCInertUnsafeUnretained[] = R"reST()reST" ; |
| 6527 | |
| 6528 | static const char AttrDoc_ObjCKindOf[] = R"reST(No documentation.)reST" ; |
| 6529 | |
| 6530 | static const char AttrDoc_ObjCMethodFamily[] = R"reST(Many methods in Objective-C have conventional meanings determined by their |
| 6531 | selectors. It is sometimes useful to be able to mark a method as having a |
| 6532 | particular conventional meaning despite not having the right selector, or as |
| 6533 | not having the conventional meaning that its selector would suggest. For these |
| 6534 | use cases, we provide an attribute to specifically describe the "method family" |
| 6535 | that a method belongs to. |
| 6536 | |
| 6537 | **Usage**: `__attribute__((objc_method_family(X)))`, where `X` is one of |
| 6538 | `none`, `alloc`, `copy`, `init`, `mutableCopy`, or `new`. This |
| 6539 | attribute can only be placed at the end of a method declaration: |
| 6540 | |
| 6541 | ```objc |
| 6542 | - (NSString *)initMyStringValue __attribute__((objc_method_family(none))); |
| 6543 | ``` |
| 6544 | |
| 6545 | Users who do not wish to change the conventional meaning of a method, and who |
| 6546 | merely want to document its non-standard retain and release semantics, should |
| 6547 | use the retaining behavior attributes (`ns_returns_retained`, |
| 6548 | `ns_returns_not_retained`, etc). |
| 6549 | |
| 6550 | Query for this feature with `__has_attribute(objc_method_family)`.)reST" ; |
| 6551 | |
| 6552 | static const char AttrDoc_ObjCNSObject[] = R"reST(No documentation.)reST" ; |
| 6553 | |
| 6554 | static const char AttrDoc_ObjCNonLazyClass[] = R"reST(This attribute can be added to an Objective-C `@interface` or |
| 6555 | `@implementation` declaration to add the class to the list of non-lazily |
| 6556 | initialized classes. A non-lazy class will be initialized eagerly when the |
| 6557 | Objective-C runtime is loaded. This is required for certain system classes which |
| 6558 | have instances allocated in non-standard ways, such as the classes for blocks |
| 6559 | and constant strings. Adding this attribute is essentially equivalent to |
| 6560 | providing a trivial `+load` method but avoids the (fairly small) load-time |
| 6561 | overheads associated with defining and calling such a method.)reST" ; |
| 6562 | |
| 6563 | static const char AttrDoc_ObjCNonRuntimeProtocol[] = R"reST(The `objc_non_runtime_protocol` attribute can be used to mark that an |
| 6564 | Objective-C protocol is only used during static type-checking and doesn't need |
| 6565 | to be represented dynamically. This avoids several small code-size and run-time |
| 6566 | overheads associated with handling the protocol's metadata. A non-runtime |
| 6567 | protocol cannot be used as the operand of a `@protocol` expression, and |
| 6568 | dynamic attempts to find it with `objc_getProtocol` will fail. |
| 6569 | |
| 6570 | If a non-runtime protocol inherits from any ordinary protocols, classes and |
| 6571 | derived protocols that declare conformance to the non-runtime protocol will |
| 6572 | dynamically list their conformance to those bare protocols.)reST" ; |
| 6573 | |
| 6574 | static const char AttrDoc_ObjCOwnership[] = R"reST(No documentation.)reST" ; |
| 6575 | |
| 6576 | static const char AttrDoc_ObjCPreciseLifetime[] = R"reST(No documentation.)reST" ; |
| 6577 | |
| 6578 | static const char AttrDoc_ObjCRequiresPropertyDefs[] = R"reST(No documentation.)reST" ; |
| 6579 | |
| 6580 | static const char AttrDoc_ObjCRequiresSuper[] = R"reST(Some Objective-C classes allow a subclass to override a particular method in a |
| 6581 | parent class but expect that the overriding method also calls the overridden |
| 6582 | method in the parent class. For these cases, we provide an attribute to |
| 6583 | designate that a method requires a "call to `super`" in the overriding |
| 6584 | method in the subclass. |
| 6585 | |
| 6586 | **Usage**: `__attribute__((objc_requires_super))`. This attribute can only |
| 6587 | be placed at the end of a method declaration: |
| 6588 | |
| 6589 | ```objc |
| 6590 | - (void)foo __attribute__((objc_requires_super)); |
| 6591 | ``` |
| 6592 | |
| 6593 | This attribute can only be applied the method declarations within a class, and |
| 6594 | not a protocol. Currently this attribute does not enforce any placement of |
| 6595 | where the call occurs in the overriding method (such as in the case of |
| 6596 | `-dealloc` where the call must appear at the end). It checks only that it |
| 6597 | exists. |
| 6598 | |
| 6599 | Note that on both OS X and iOS that the Foundation framework provides a |
| 6600 | convenience macro `NS_REQUIRES_SUPER` that provides syntactic sugar for this |
| 6601 | attribute: |
| 6602 | |
| 6603 | ```objc |
| 6604 | - (void)foo NS_REQUIRES_SUPER; |
| 6605 | ``` |
| 6606 | |
| 6607 | This macro is conditionally defined depending on the compiler's support for |
| 6608 | this attribute. If the compiler does not support the attribute the macro |
| 6609 | expands to nothing. |
| 6610 | |
| 6611 | Operationally, when a method has this annotation the compiler will warn if the |
| 6612 | implementation of an override in a subclass does not call super. For example: |
| 6613 | |
| 6614 | ```objc |
| 6615 | warning: method possibly missing a [super AnnotMeth] call |
| 6616 | - (void) AnnotMeth{}; |
| 6617 | ^ |
| 6618 | ```)reST" ; |
| 6619 | |
| 6620 | static const char AttrDoc_ObjCReturnsInnerPointer[] = R"reST(No documentation.)reST" ; |
| 6621 | |
| 6622 | static const char AttrDoc_ObjCRootClass[] = R"reST(No documentation.)reST" ; |
| 6623 | |
| 6624 | static const char AttrDoc_ObjCRuntimeName[] = R"reST(By default, the Objective-C interface or protocol identifier is used |
| 6625 | in the metadata name for that object. The `objc_runtime_name` |
| 6626 | attribute allows annotated interfaces or protocols to use the |
| 6627 | specified string argument in the object's metadata name instead of the |
| 6628 | default name. |
| 6629 | |
| 6630 | **Usage**: `__attribute__((objc_runtime_name("MyLocalName")))`. This attribute |
| 6631 | can only be placed before an @protocol or @interface declaration: |
| 6632 | |
| 6633 | ```objc |
| 6634 | __attribute__((objc_runtime_name("MyLocalName"))) |
| 6635 | @interface Message |
| 6636 | @end |
| 6637 | ```)reST" ; |
| 6638 | |
| 6639 | static const char AttrDoc_ObjCRuntimeVisible[] = R"reST(This attribute specifies that the Objective-C class to which it applies is |
| 6640 | visible to the Objective-C runtime but not to the linker. Classes annotated |
| 6641 | with this attribute cannot be subclassed and cannot have categories defined for |
| 6642 | them.)reST" ; |
| 6643 | |
| 6644 | static const char AttrDoc_ObjCSubclassingRestricted[] = R"reST(This attribute can be added to an Objective-C `@interface` declaration to |
| 6645 | ensure that this class cannot be subclassed.)reST" ; |
| 6646 | |
| 6647 | static const char AttrDoc_OpenACCRoutineAnnot[] = R"reST()reST" ; |
| 6648 | |
| 6649 | static const char AttrDoc_OpenACCRoutineDecl[] = R"reST()reST" ; |
| 6650 | |
| 6651 | static const char AttrDoc_OpenCLAccess[] = R"reST(The access qualifiers must be used with image object arguments or pipe arguments |
| 6652 | to declare if they are being read or written by a kernel or function. |
| 6653 | |
| 6654 | The read_only/\_\_read_only, write_only/\_\_write_only and read_write/\_\_read_write |
| 6655 | names are reserved for use as access qualifiers and shall not be used otherwise. |
| 6656 | |
| 6657 | ```c |
| 6658 | kernel void |
| 6659 | foo (read_only image2d_t imageA, |
| 6660 | write_only image2d_t imageB) { |
| 6661 | ... |
| 6662 | } |
| 6663 | ``` |
| 6664 | |
| 6665 | In the above example imageA is a read-only 2D image object, and imageB is a |
| 6666 | write-only 2D image object. |
| 6667 | |
| 6668 | The read_write (or \_\_read_write) qualifier can not be used with pipe. |
| 6669 | |
| 6670 | More details can be found in the OpenCL C language Spec v2.0, Section 6.6.)reST" ; |
| 6671 | |
| 6672 | static const char AttrDoc_OpenCLConstantAddressSpace[] = R"reST(The constant address space attribute signals that an object is located in |
| 6673 | a constant (non-modifiable) memory region. It is available to all work items. |
| 6674 | Any type can be annotated with the constant address space attribute. Objects |
| 6675 | with the constant address space qualifier can be declared in any scope and must |
| 6676 | have an initializer.)reST" ; |
| 6677 | |
| 6678 | static const char AttrDoc_OpenCLGenericAddressSpace[] = R"reST(The generic address space attribute is only available with OpenCL v2.0 and later. |
| 6679 | It can be used with pointer types. Variables in global and local scope and |
| 6680 | function parameters in non-kernel functions can have the generic address space |
| 6681 | type attribute. It is intended to be a placeholder for any other address space |
| 6682 | except for '\_\_constant' in OpenCL code which can be used with multiple address |
| 6683 | spaces.)reST" ; |
| 6684 | |
| 6685 | static const char AttrDoc_OpenCLGlobalAddressSpace[] = R"reST(The global address space attribute specifies that an object is allocated in |
| 6686 | global memory, which is accessible by all work items. The content stored in this |
| 6687 | memory area persists between kernel executions. Pointer types to the global |
| 6688 | address space are allowed as function parameters or local variables. Starting |
| 6689 | with OpenCL v2.0, the global address space can be used with global (program |
| 6690 | scope) variables and static local variable as well.)reST" ; |
| 6691 | |
| 6692 | static const char AttrDoc_OpenCLGlobalDeviceAddressSpace[] = R"reST(The `global_device` and `global_host` address space attributes specify that |
| 6693 | an object is allocated in global memory on the device/host. It helps to |
| 6694 | distinguish USM (Unified Shared Memory) pointers that access global device |
| 6695 | memory from those that access global host memory. These new address spaces are |
| 6696 | a subset of the `__global/opencl_global` address space, the full address space |
| 6697 | set model for OpenCL 2.0 with the extension looks as follows: |
| 6698 | |
| 6699 | ```text |
| 6700 | generic->global->host |
| 6701 | ->device |
| 6702 | ->private |
| 6703 | ->local |
| 6704 | constant |
| 6705 | ``` |
| 6706 | |
| 6707 | As `global_device` and `global_host` are a subset of |
| 6708 | `__global/opencl_global` address spaces it is allowed to convert |
| 6709 | `global_device` and `global_host` address spaces to |
| 6710 | `__global/opencl_global` address spaces (following ISO/IEC TR 18037 5.1.3 |
| 6711 | "Address space nesting and rules for pointers"). |
| 6712 | |
| 6713 | These attributes are deprecated and may be removed in a future version of Clang.)reST" ; |
| 6714 | |
| 6715 | static const char AttrDoc_OpenCLGlobalHostAddressSpace[] = R"reST(The `global_device` and `global_host` address space attributes specify that |
| 6716 | an object is allocated in global memory on the device/host. It helps to |
| 6717 | distinguish USM (Unified Shared Memory) pointers that access global device |
| 6718 | memory from those that access global host memory. These new address spaces are |
| 6719 | a subset of the `__global/opencl_global` address space, the full address space |
| 6720 | set model for OpenCL 2.0 with the extension looks as follows: |
| 6721 | |
| 6722 | ```text |
| 6723 | generic->global->host |
| 6724 | ->device |
| 6725 | ->private |
| 6726 | ->local |
| 6727 | constant |
| 6728 | ``` |
| 6729 | |
| 6730 | As `global_device` and `global_host` are a subset of |
| 6731 | `__global/opencl_global` address spaces it is allowed to convert |
| 6732 | `global_device` and `global_host` address spaces to |
| 6733 | `__global/opencl_global` address spaces (following ISO/IEC TR 18037 5.1.3 |
| 6734 | "Address space nesting and rules for pointers"). |
| 6735 | |
| 6736 | These attributes are deprecated and may be removed in a future version of Clang.)reST" ; |
| 6737 | |
| 6738 | static const char AttrDoc_OpenCLIntelReqdSubGroupSize[] = R"reST(The optional attribute intel_reqd_sub_group_size can be used to indicate that |
| 6739 | the kernel must be compiled and executed with the specified subgroup size. When |
| 6740 | this attribute is present, get_max_sub_group_size() is guaranteed to return the |
| 6741 | specified integer value. This is important for the correctness of many subgroup |
| 6742 | algorithms, and in some cases may be used by the compiler to generate more optimal |
| 6743 | code. See `cl_intel_required_subgroup_size |
| 6744 | <https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.txt>` |
| 6745 | for details.)reST" ; |
| 6746 | |
| 6747 | static const char AttrDoc_OpenCLLocalAddressSpace[] = R"reST(The local address space specifies that an object is allocated in the local (work |
| 6748 | group) memory area, which is accessible to all work items in the same work |
| 6749 | group. The content stored in this memory region is not accessible after |
| 6750 | the kernel execution ends. In a kernel function scope, any variable can be in |
| 6751 | the local address space. In other scopes, only pointer types to the local address |
| 6752 | space are allowed. Local address space variables cannot have an initializer.)reST" ; |
| 6753 | |
| 6754 | static const char AttrDoc_OpenCLPrivateAddressSpace[] = R"reST(The private address space specifies that an object is allocated in the private |
| 6755 | (work item) memory. Other work items cannot access the same memory area and its |
| 6756 | content is destroyed after work item execution ends. Local variables can be |
| 6757 | declared in the private address space. Function arguments are always in the |
| 6758 | private address space. Kernel function arguments of a pointer or an array type |
| 6759 | cannot point to the private address space.)reST" ; |
| 6760 | |
| 6761 | static const char AttrDoc_OpenCLUnrollHint[] = R"reST(The opencl_unroll_hint attribute qualifier can be used to specify that a loop |
| 6762 | (for, while and do loops) can be unrolled. This attribute qualifier can be |
| 6763 | used to specify full unrolling or partial unrolling by a specified amount. |
| 6764 | This is a compiler hint and the compiler may ignore this directive. See |
| 6765 | [OpenCL v2.0](https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf) |
| 6766 | s6.11.5 for details.)reST" ; |
| 6767 | |
| 6768 | static const char AttrDoc_OptimizeNone[] = R"reST(The `optnone` attribute suppresses essentially all optimizations |
| 6769 | on a function or method, regardless of the optimization level applied to |
| 6770 | the compilation unit as a whole. This is particularly useful when you |
| 6771 | need to debug a particular function, but it is infeasible to build the |
| 6772 | entire application without optimization. Avoiding optimization on the |
| 6773 | specified function can improve the quality of the debugging information |
| 6774 | for that function. |
| 6775 | |
| 6776 | This attribute is incompatible with the `always_inline` and `minsize` |
| 6777 | attributes. |
| 6778 | |
| 6779 | Note that this attribute does not apply recursively to nested functions such as |
| 6780 | lambdas or blocks when using declaration-specific attribute syntaxes such as double |
| 6781 | square brackets (`[[]]`) or `__attribute__`. The `#pragma` syntax can be |
| 6782 | used to apply the attribute to all functions, including nested functions, in a |
| 6783 | range of source code.)reST" ; |
| 6784 | |
| 6785 | static const char AttrDoc_OverflowBehavior[] = R"reST(The `overflow_behavior` attribute provides fine-grained, type-level control |
| 6786 | over how arithmetic operations on an integer type behave on overflow. It may be |
| 6787 | applied to a `typedef`, to a variable or data member, or to an integer type |
| 6788 | directly, and accepts one of two behaviors as its argument: |
| 6789 | |
| 6790 | - `wrap`: arithmetic on the attributed type wraps on overflow, using two's |
| 6791 | complement semantics. This is equivalent to `-fwrapv` but scoped to the |
| 6792 | attributed type, and works for both signed and unsigned types. UBSan's |
| 6793 | `signed-integer-overflow`, `unsigned-integer-overflow`, |
| 6794 | `implicit-signed-integer-truncation`, and |
| 6795 | `implicit-unsigned-integer-truncation` checks are suppressed for the type. |
| 6796 | - `trap`: arithmetic on the attributed type is checked for overflow, enabling |
| 6797 | overflow checks for the type even when `-fwrapv` is in effect globally. |
| 6798 | |
| 6799 | ```c++ |
| 6800 | typedef unsigned int __attribute__((overflow_behavior(trap))) non_wrapping_uint; |
| 6801 | |
| 6802 | non_wrapping_uint add_one(non_wrapping_uint a) { |
| 6803 | return a + 1; // Overflow is checked for this operation. |
| 6804 | } |
| 6805 | |
| 6806 | int mul_alot(int n) { |
| 6807 | int __attribute__((overflow_behavior(wrap))) a = n; |
| 6808 | return a * 1337; // Overflow is not checked and is well-defined. |
| 6809 | } |
| 6810 | ``` |
| 6811 | |
| 6812 | The keyword spellings `__ob_wrap` and `__ob_trap` are equivalent to |
| 6813 | `overflow_behavior(wrap)` and `overflow_behavior(trap)` respectively. |
| 6814 | |
| 6815 | The attribute wholly overrides global flags (`-ftrapv`, `-fwrapv`, |
| 6816 | sanitizers, and Sanitizer Special Case Lists) for the attributed type. It can |
| 6817 | only be applied to integer types. |
| 6818 | |
| 6819 | This feature is experimental and must be enabled with the `-cc1` option |
| 6820 | `-fexperimental-overflow-behavior-types`. For full details on promotion and |
| 6821 | conversion rules, pointer semantics, diagnostics, and interaction with |
| 6822 | sanitizers, see {doc}`OverflowBehaviorTypes`.)reST" ; |
| 6823 | |
| 6824 | static const char AttrDoc_Overloadable[] = R"reST(Clang provides support for C++ function overloading in C. Function overloading |
| 6825 | in C is introduced using the `overloadable` attribute. For example, one |
| 6826 | might provide several overloaded versions of a `tgsin` function that invokes |
| 6827 | the appropriate standard function computing the sine of a value with `float`, |
| 6828 | `double`, or `long double` precision: |
| 6829 | |
| 6830 | ```c |
| 6831 | #include <math.h> |
| 6832 | float __attribute__((overloadable)) tgsin(float x) { return sinf(x); } |
| 6833 | double __attribute__((overloadable)) tgsin(double x) { return sin(x); } |
| 6834 | long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); } |
| 6835 | ``` |
| 6836 | |
| 6837 | Given these declarations, one can call `tgsin` with a `float` value to |
| 6838 | receive a `float` result, with a `double` to receive a `double` result, |
| 6839 | etc. Function overloading in C follows the rules of C++ function overloading |
| 6840 | to pick the best overload given the call arguments, with a few C-specific |
| 6841 | semantics: |
| 6842 | |
| 6843 | - Conversion from `float` or `double` to `long double` is ranked as a |
| 6844 | floating-point promotion (per C99) rather than as a floating-point conversion |
| 6845 | (as in C++). |
| 6846 | - A conversion from a pointer of type `T*` to a pointer of type `U*` is |
| 6847 | considered a pointer conversion (with conversion rank) if `T` and `U` are |
| 6848 | compatible types. |
| 6849 | - A conversion from type `T` to a value of type `U` is permitted if `T` |
| 6850 | and `U` are compatible types. This conversion is given "conversion" rank. |
| 6851 | - If no viable candidates are otherwise available, we allow a conversion from a |
| 6852 | pointer of type `T*` to a pointer of type `U*`, where `T` and `U` are |
| 6853 | incompatible. This conversion is ranked below all other types of conversions. |
| 6854 | Please note: `U` lacking qualifiers that are present on `T` is sufficient |
| 6855 | for `T` and `U` to be incompatible. |
| 6856 | |
| 6857 | The declaration of `overloadable` functions is restricted to function |
| 6858 | declarations and definitions. If a function is marked with the `overloadable` |
| 6859 | attribute, then all declarations and definitions of functions with that name, |
| 6860 | except for at most one (see the note below about unmarked overloads), must have |
| 6861 | the `overloadable` attribute. In addition, redeclarations of a function with |
| 6862 | the `overloadable` attribute must have the `overloadable` attribute, and |
| 6863 | redeclarations of a function without the `overloadable` attribute must *not* |
| 6864 | have the `overloadable` attribute. e.g., |
| 6865 | |
| 6866 | ```c |
| 6867 | int f(int) __attribute__((overloadable)); |
| 6868 | float f(float); // error: declaration of "f" must have the "overloadable" attribute |
| 6869 | int f(int); // error: redeclaration of "f" must have the "overloadable" attribute |
| 6870 | |
| 6871 | int g(int) __attribute__((overloadable)); |
| 6872 | int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute |
| 6873 | |
| 6874 | int h(int); |
| 6875 | int h(int) __attribute__((overloadable)); // error: declaration of "h" must not |
| 6876 | // have the "overloadable" attribute |
| 6877 | ``` |
| 6878 | |
| 6879 | Functions marked `overloadable` must have prototypes. Therefore, the |
| 6880 | following code is ill-formed: |
| 6881 | |
| 6882 | ```c |
| 6883 | int h() __attribute__((overloadable)); // error: h does not have a prototype |
| 6884 | ``` |
| 6885 | |
| 6886 | However, `overloadable` functions are allowed to use a ellipsis even if there |
| 6887 | are no named parameters (as is permitted in C++). This feature is particularly |
| 6888 | useful when combined with the `unavailable` attribute: |
| 6889 | |
| 6890 | ```c++ |
| 6891 | void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error |
| 6892 | ``` |
| 6893 | |
| 6894 | Functions declared with the `overloadable` attribute have their names mangled |
| 6895 | according to the same rules as C++ function names. For example, the three |
| 6896 | `tgsin` functions in our motivating example get the mangled names |
| 6897 | `_Z5tgsinf`, `_Z5tgsind`, and `_Z5tgsine`, respectively. There are two |
| 6898 | caveats to this use of name mangling: |
| 6899 | |
| 6900 | - Future versions of Clang may change the name mangling of functions overloaded |
| 6901 | in C, so you should not depend on an specific mangling. To be completely |
| 6902 | safe, we strongly urge the use of `static inline` with `overloadable` |
| 6903 | functions. |
| 6904 | - The `overloadable` attribute has almost no meaning when used in C++, |
| 6905 | because names will already be mangled and functions are already overloadable. |
| 6906 | However, when an `overloadable` function occurs within an `extern "C"` |
| 6907 | linkage specification, its name *will* be mangled in the same way as it |
| 6908 | would in C. |
| 6909 | |
| 6910 | For the purpose of backwards compatibility, at most one function with the same |
| 6911 | name as other `overloadable` functions may omit the `overloadable` |
| 6912 | attribute. In this case, the function without the `overloadable` attribute |
| 6913 | will not have its name mangled. |
| 6914 | |
| 6915 | For example: |
| 6916 | |
| 6917 | ```c |
| 6918 | // Notes with mangled names assume Itanium mangling. |
| 6919 | int f(int); |
| 6920 | int f(double) __attribute__((overloadable)); |
| 6921 | void foo() { |
| 6922 | f(5); // Emits a call to f (not _Z1fi, as it would with an overload that |
| 6923 | // was marked with overloadable). |
| 6924 | f(1.0); // Emits a call to _Z1fd. |
| 6925 | } |
| 6926 | ``` |
| 6927 | |
| 6928 | Support for unmarked overloads is not present in some versions of clang. You may |
| 6929 | query for it using `__has_extension(overloadable_unmarked)`. |
| 6930 | |
| 6931 | Query for this attribute with `__has_attribute(overloadable)`.)reST" ; |
| 6932 | |
| 6933 | static const char AttrDoc_Override[] = R"reST()reST" ; |
| 6934 | |
| 6935 | static const char AttrDoc_Owner[] = R"reST(:::{Note} |
| 6936 | This attribute is experimental and its effect on analysis is subject to change in |
| 6937 | a future version of clang. |
| 6938 | ::: |
| 6939 | |
| 6940 | The attribute `[[gsl::Owner(T)]]` applies to structs and classes that own an |
| 6941 | object of type `T`: |
| 6942 | |
| 6943 | ``` |
| 6944 | class [[gsl::Owner(int)]] IntOwner { |
| 6945 | private: |
| 6946 | int value; |
| 6947 | public: |
| 6948 | int *getInt() { return &value; } |
| 6949 | }; |
| 6950 | ``` |
| 6951 | |
| 6952 | The argument `T` is optional and is ignored. |
| 6953 | This attribute may be used by analysis tools and has no effect on code |
| 6954 | generation. A `void` argument means that the class can own any type. |
| 6955 | |
| 6956 | See [Pointer] for an example.)reST" ; |
| 6957 | |
| 6958 | static const char AttrDoc_Ownership[] = R"reST(:::{note} |
| 6959 | In order for the Clang Static Analyzer to acknowledge these attributes, the |
| 6960 | `Optimistic` config needs to be set to true for the checker |
| 6961 | `unix.DynamicMemoryModeling`: |
| 6962 | |
| 6963 | `-Xclang -analyzer-config -Xclang unix.DynamicMemoryModeling:Optimistic=true` |
| 6964 | ::: |
| 6965 | |
| 6966 | These attributes are used by the Clang Static Analyzer's dynamic memory modeling |
| 6967 | facilities to mark custom allocating/deallocating functions. |
| 6968 | |
| 6969 | All 3 attributes' first parameter of type string is the type of the allocation: |
| 6970 | `malloc`, `new`, etc. to allow for catching {ref}`mismatched deallocation |
| 6971 | <unix-MismatchedDeallocator>` bugs. The allocation type can be any string, e.g. |
| 6972 | a function annotated with |
| 6973 | returning a piece of memory of type `lasagna` but freed with a function |
| 6974 | annotated to release `cheese` typed memory will result in mismatched |
| 6975 | deallocation warning. |
| 6976 | |
| 6977 | The (currently) only allocation type having special meaning is `malloc` -- |
| 6978 | the Clang Static Analyzer makes sure that allocating functions annotated with |
| 6979 | `malloc` are treated like they used the standard `malloc()`, and can be |
| 6980 | safely deallocated with the standard `free()`. |
| 6981 | |
| 6982 | - Use `ownership_returns` to mark a function as an allocating function. |
| 6983 | It takes 1 or 2 arguments. |
| 6984 | The first argument is a user-provided identifier representing the "kind" of the allocation. |
| 6985 | This is basically what is enforced when checking the deallocation. This is mandatory. |
| 6986 | The second argument is optional. |
| 6987 | It represents the index of the parameter that represents the allocation size in bytes (counting from 1). |
| 6988 | The referenced parameter must have some integral type. |
| 6989 | This attribute may appear at most once per declaration. |
| 6990 | If this argument is not set, then tooling, such as the Clang Static Analyzer, |
| 6991 | won't be able to reason about the size of the allocation, thus check potential out-of-bounds accesses. |
| 6992 | However, such tooling could still warn if the wrong deallocation function |
| 6993 | was used for the `ownership_returns` attributed resource. |
| 6994 | If forward declarations have this attribute, those must have the same arguments. |
| 6995 | - Use `ownership_takes` to mark a function as a deallocating function. Takes 2 |
| 6996 | arguments: the allocation type, and the index of the parameter that is being |
| 6997 | deallocated (counting from 1). |
| 6998 | - Use `ownership_holds` to mark that a function takes over the ownership of a |
| 6999 | piece of memory and will free it at some unspecified point in the future. Like |
| 7000 | `ownership_takes`, this takes 2 arguments: the allocation type, and the |
| 7001 | index of the parameter whose ownership will be taken over (counting from 1). |
| 7002 | |
| 7003 | The annotations `ownership_takes` and `ownership_holds` both prevent memory |
| 7004 | leak reports (concerning the specified parameter); the difference between them |
| 7005 | is that using taken memory is a use-after-free error, while using held memory |
| 7006 | is assumed to be legitimate. However, releasing the held memory or passing it |
| 7007 | to another holding call is reported by the analyzer as an "attempt to release |
| 7008 | non-owned memory". |
| 7009 | |
| 7010 | Example: |
| 7011 | |
| 7012 | ```c |
| 7013 | // Denotes that my_malloc will return with a dynamically allocated piece of |
| 7014 | // memory using malloc(). |
| 7015 | void __attribute((ownership_returns(malloc))) *my_malloc(size_t sz); |
| 7016 | |
| 7017 | // 'sz' (parameter 1) is the allocation size. |
| 7018 | void __attribute((ownership_returns(malloc, 1))) *my_sized_malloc(size_t sz); |
| 7019 | |
| 7020 | // Denotes that my_free will deallocate its argument using free(). |
| 7021 | void __attribute((ownership_takes(malloc, 1))) my_free(void *); |
| 7022 | |
| 7023 | // Denotes that my_hold will take over the ownership of its argument that was |
| 7024 | // allocated via malloc(). |
| 7025 | void __attribute((ownership_holds(malloc, 1))) my_hold(void *); |
| 7026 | ``` |
| 7027 | |
| 7028 | Further reading about dynamic memory modeling in the Clang Static Analyzer is |
| 7029 | found in these checker docs: |
| 7030 | {ref}`unix.Malloc <unix-Malloc>`, {ref}`unix.MallocSizeof <unix-MallocSizeof>`, |
| 7031 | {ref}`unix.MismatchedDeallocator <unix-MismatchedDeallocator>`, |
| 7032 | {ref}`cplusplus.NewDelete <cplusplus-NewDelete>`, |
| 7033 | {ref}`cplusplus.NewDeleteLeaks <cplusplus-NewDeleteLeaks>`, |
| 7034 | {ref}`optin.taint.TaintedAlloc <optin-taint-TaintedAlloc>`. |
| 7035 | Mind that many more checkers are affected by dynamic memory modeling changes to |
| 7036 | some extent. |
| 7037 | |
| 7038 | Further reading for other annotations: |
| 7039 | {doc}`Static Analyzer source annotations <analyzer/user-docs/Annotations>`.)reST" ; |
| 7040 | |
| 7041 | static const char AttrDoc_Packed[] = R"reST(No documentation.)reST" ; |
| 7042 | |
| 7043 | static const char AttrDoc_ParamTypestate[] = R"reST(This attribute specifies expectations about function parameters. Calls to an |
| 7044 | function with annotated parameters will issue a warning if the corresponding |
| 7045 | argument isn't in the expected state. The attribute is also used to set the |
| 7046 | initial state of the parameter when analyzing the function's body.)reST" ; |
| 7047 | |
| 7048 | static const char AttrDoc_Pascal[] = R"reST(No documentation.)reST" ; |
| 7049 | |
| 7050 | static const char AttrDoc_PassObjectSize[] = R"reST(:::{Note} |
| 7051 | The mangling of functions with parameters that are annotated with |
| 7052 | `pass_object_size` is subject to change. You can get around this by |
| 7053 | using `__asm__("foo")` to explicitly name your functions, thus preserving |
| 7054 | your ABI; also, non-overloadable C functions with `pass_object_size` are |
| 7055 | not mangled. |
| 7056 | ::: |
| 7057 | |
| 7058 | The `pass_object_size(Type)` attribute can be placed on function parameters to |
| 7059 | instruct clang to call `__builtin_object_size(param, Type)` at each callsite |
| 7060 | of said function, and implicitly pass the result of this call in as an invisible |
| 7061 | argument of type `size_t` directly after the parameter annotated with |
| 7062 | `pass_object_size`. Clang will also replace any calls to |
| 7063 | `__builtin_object_size(param, Type)` in the function by said implicit |
| 7064 | parameter. |
| 7065 | |
| 7066 | Example usage: |
| 7067 | |
| 7068 | ```c |
| 7069 | int bzero1(char *const p __attribute__((pass_object_size(0)))) |
| 7070 | __attribute__((noinline)) { |
| 7071 | int i = 0; |
| 7072 | for (/**/; i < (int)__builtin_object_size(p, 0); ++i) { |
| 7073 | p[i] = 0; |
| 7074 | } |
| 7075 | return i; |
| 7076 | } |
| 7077 | |
| 7078 | int main() { |
| 7079 | char chars[100]; |
| 7080 | int n = bzero1(&chars[0]); |
| 7081 | assert(n == sizeof(chars)); |
| 7082 | return 0; |
| 7083 | } |
| 7084 | ``` |
| 7085 | |
| 7086 | If successfully evaluating `__builtin_object_size(param, Type)` at the |
| 7087 | callsite is not possible, then the "failed" value is passed in. So, using the |
| 7088 | definition of `bzero1` from above, the following code would exit cleanly: |
| 7089 | |
| 7090 | ```c |
| 7091 | int main2(int argc, char *argv[]) { |
| 7092 | int n = bzero1(argv); |
| 7093 | assert(n == -1); |
| 7094 | return 0; |
| 7095 | } |
| 7096 | ``` |
| 7097 | |
| 7098 | `pass_object_size` plays a part in overload resolution. If two overload |
| 7099 | candidates are otherwise equally good, then the overload with one or more |
| 7100 | parameters with `pass_object_size` is preferred. This implies that the choice |
| 7101 | between two identical overloads both with `pass_object_size` on one or more |
| 7102 | parameters will always be ambiguous; for this reason, having two such overloads |
| 7103 | is illegal. For example: |
| 7104 | |
| 7105 | ```c++ |
| 7106 | #define PS(N) __attribute__((pass_object_size(N))) |
| 7107 | // OK |
| 7108 | void Foo(char *a, char *b); // Overload A |
| 7109 | // OK -- overload A has no parameters with pass_object_size. |
| 7110 | void Foo(char *a PS(0), char *b PS(0)); // Overload B |
| 7111 | // Error -- Same signature (sans pass_object_size) as overload B, and both |
| 7112 | // overloads have one or more parameters with the pass_object_size attribute. |
| 7113 | void Foo(void *a PS(0), void *b); |
| 7114 | |
| 7115 | // OK |
| 7116 | void Bar(void *a PS(0)); // Overload C |
| 7117 | // OK |
| 7118 | void Bar(char *c PS(1)); // Overload D |
| 7119 | |
| 7120 | void main() { |
| 7121 | char known[10], *unknown; |
| 7122 | Foo(unknown, unknown); // Calls overload B |
| 7123 | Foo(known, unknown); // Calls overload B |
| 7124 | Foo(unknown, known); // Calls overload B |
| 7125 | Foo(known, known); // Calls overload B |
| 7126 | |
| 7127 | Bar(known); // Calls overload D |
| 7128 | Bar(unknown); // Calls overload D |
| 7129 | } |
| 7130 | ``` |
| 7131 | |
| 7132 | Currently, `pass_object_size` is a bit restricted in terms of its usage: |
| 7133 | |
| 7134 | - Only one use of `pass_object_size` is allowed per parameter. |
| 7135 | - It is an error to take the address of a function with `pass_object_size` on |
| 7136 | any of its parameters. If you wish to do this, you can create an overload |
| 7137 | without `pass_object_size` on any parameters. |
| 7138 | - It is an error to apply the `pass_object_size` attribute to parameters that |
| 7139 | are not pointers. Additionally, any parameter that `pass_object_size` is |
| 7140 | applied to must be marked `const` at its function's definition. |
| 7141 | |
| 7142 | Clang also supports the `pass_dynamic_object_size` attribute, which behaves |
| 7143 | identically to `pass_object_size`, but evaluates a call to |
| 7144 | `__builtin_dynamic_object_size` at the callee instead of |
| 7145 | `__builtin_object_size`. `__builtin_dynamic_object_size` provides some extra |
| 7146 | runtime checks when the object size can't be determined at compile-time. You can |
| 7147 | read more about `__builtin_dynamic_object_size` in |
| 7148 | {ref}`Evaluating Object Size <langext-evaluating-object-size>`.)reST" ; |
| 7149 | |
| 7150 | static const char AttrDoc_PatchableFunctionEntry[] = R"reST(`__attribute__((patchable_function_entry(N,M,Section)))` is used to generate M |
| 7151 | NOPs before the function entry and N-M NOPs after the function entry, with a record of |
| 7152 | the entry stored in section `Section`. This attribute takes precedence over the |
| 7153 | command line option `-fpatchable-function-entry=N,M,Section`. `M` defaults to 0 |
| 7154 | if omitted. `Section` defaults to the `-fpatchable-function-entry` section name if |
| 7155 | set, or to `__patchable_function_entries` otherwise. |
| 7156 | |
| 7157 | This attribute is only supported on |
| 7158 | aarch64/aarch64-be/loongarch32/loongarch64/riscv32/riscv64/i386/x86-64/ppc/ppc64/ppc64le/s390x targets. |
| 7159 | For ppc/ppc64 targets, AIX is still not supported.)reST" ; |
| 7160 | |
| 7161 | static const char AttrDoc_Pcs[] = R"reST(On ARM targets, this attribute can be used to select calling conventions |
| 7162 | similar to `stdcall` on x86. Valid parameter values are "aapcs" and |
| 7163 | "aapcs-vfp".)reST" ; |
| 7164 | |
| 7165 | static const char AttrDoc_Personality[] = R"reST(`__attribute__((personality(<routine>)))` is used to specify a personality |
| 7166 | routine that is different from the language that is being used to implement the |
| 7167 | function. This is a targeted, low-level feature aimed at language runtime |
| 7168 | implementors who write runtime support code in C/C++ but need that code to |
| 7169 | participate in a foreign language's exception-handling or unwinding model. |
| 7170 | |
| 7171 | A personality routine is a language-specific callback attached to each stack |
| 7172 | frame that the unwinder invokes to determine whether that frame handles a given |
| 7173 | exception and what cleanup actions to perform. It effectively colors the |
| 7174 | language-agnostic unwinding mechanism with language-specific semantics, enabling |
| 7175 | different languages to coexist on the same call stack while each interpreting |
| 7176 | exceptions according to their own rules.)reST" ; |
| 7177 | |
| 7178 | static const char AttrDoc_Pointer[] = R"reST(:::{Note} |
| 7179 | This attribute is experimental and its effect on analysis is subject to change in |
| 7180 | a future version of clang. |
| 7181 | ::: |
| 7182 | |
| 7183 | The attribute `[[gsl::Pointer(T)]]` applies to structs and classes that behave |
| 7184 | like pointers to an object of type `T`: |
| 7185 | |
| 7186 | ``` |
| 7187 | class [[gsl::Pointer(int)]] IntPointer { |
| 7188 | private: |
| 7189 | int *valuePointer; |
| 7190 | public: |
| 7191 | IntPointer(const IntOwner&); |
| 7192 | int *getInt() { return valuePointer; } |
| 7193 | }; |
| 7194 | ``` |
| 7195 | |
| 7196 | The argument `T` is optional and is ignored. |
| 7197 | This attribute may be used by analysis tools and has no effect on code |
| 7198 | generation. A `void` argument means that the pointer can point to any type. |
| 7199 | |
| 7200 | Example: |
| 7201 | When constructing an instance of a class annotated like this (a Pointer) from |
| 7202 | an instance of a class annotated with `[[gsl::Owner]]` (an Owner), |
| 7203 | then the analysis will consider the Pointer to point inside the Owner. |
| 7204 | When the Owner's lifetime ends, it will consider the Pointer to be dangling. |
| 7205 | |
| 7206 | ```c++ |
| 7207 | int f() { |
| 7208 | IntPointer P(IntOwner{}); // P "points into" a temporary IntOwner object |
| 7209 | P.getInt(); // P is dangling |
| 7210 | } |
| 7211 | ``` |
| 7212 | |
| 7213 | **Transparent Member Functions** |
| 7214 | |
| 7215 | The analysis automatically tracks certain member functions of `[[gsl::Pointer]]` types |
| 7216 | that provide transparent access to the pointed-to object. These include: |
| 7217 | |
| 7218 | - Dereference operators: `operator*`, `operator->` |
| 7219 | - Data access methods: `data()`, `c_str()`, `get()` |
| 7220 | - Iterator operations: `begin()`, `end()`, `rbegin()`, `rend()`, `cbegin()`, `cend()`, `crbegin()`, `crend()`, `operator+`, `operator-`, `operator++`, `operator--` |
| 7221 | |
| 7222 | When these methods return pointers, view types, or references, the analysis treats them as |
| 7223 | transparently borrowing from the same object that the pointer itself borrows from, |
| 7224 | enabling detection of use-after-free through these access patterns: |
| 7225 | |
| 7226 | ```c++ |
| 7227 | // For example, .data() here returns a borrow to 's' instead of 'v'. |
| 7228 | const char* f() { |
| 7229 | std::string s = "hello"; |
| 7230 | std::string_view v = s; // warning: address of stack memory returned |
| 7231 | return v.data(); // note: returned here |
| 7232 | } |
| 7233 | |
| 7234 | const MyObj& g(MyObj obj) { |
| 7235 | View v = obj; // warning: address of stack memory returned |
| 7236 | return *v; // note: returned here |
| 7237 | } |
| 7238 | ``` |
| 7239 | |
| 7240 | This tracking also applies to range-based for loops, where the `begin()` and `end()` |
| 7241 | iterators are used to access elements: |
| 7242 | |
| 7243 | ```c++ |
| 7244 | std::string_view f(std::vector<std::string> vec) { |
| 7245 | for (const std::string& s : vec) { // warning: address of stack memory returned |
| 7246 | return s; // note: returned here |
| 7247 | } |
| 7248 | } |
| 7249 | ``` |
| 7250 | |
| 7251 | **Container Template Specialization** |
| 7252 | |
| 7253 | If a template class is annotated with `[[gsl::Owner]]`, and the first |
| 7254 | instantiated template argument is a pointer type (raw pointer, or `[[gsl::Pointer]]`), |
| 7255 | the analysis will consider the instantiated class as a container of the pointer. |
| 7256 | When constructing such an object from a GSL owner object, the analysis will |
| 7257 | assume that the container holds a pointer to the owner object. Consequently, |
| 7258 | when the owner object is destroyed, the pointer will be considered dangling. |
| 7259 | |
| 7260 | ```c++ |
| 7261 | int f() { |
| 7262 | std::vector<std::string_view> v = {std::string()}; // v holds a dangling pointer. |
| 7263 | std::optional<std::string_view> o = std::string(); // o holds a dangling pointer. |
| 7264 | } |
| 7265 | ```)reST" ; |
| 7266 | |
| 7267 | static const char AttrDoc_PointerAuth[] = R"reST(The `__ptrauth` qualifier allows the programmer to directly control |
| 7268 | how pointers are signed when they are stored in a particular variable. |
| 7269 | This can be used to strengthen the default protections of pointer |
| 7270 | authentication and make it more difficult for an attacker to escalate |
| 7271 | an ability to alter memory into full control of a process. |
| 7272 | |
| 7273 | ```c |
| 7274 | #include <ptrauth.h> |
| 7275 | |
| 7276 | typedef void (*my_callback)(const void*); |
| 7277 | my_callback __ptrauth(ptrauth_key_process_dependent_code, 1, 0xe27a) callback; |
| 7278 | ``` |
| 7279 | |
| 7280 | The first argument to `__ptrauth` is the name of the signing key. |
| 7281 | Valid key names for the target are defined in `<ptrauth.h>`. |
| 7282 | |
| 7283 | The second argument to `__ptrauth` is a flag (0 or 1) specifying whether |
| 7284 | the object should use address discrimination. |
| 7285 | |
| 7286 | The third argument to `__ptrauth` is a 16-bit non-negative integer which |
| 7287 | allows additional discrimination between objects.)reST" ; |
| 7288 | |
| 7289 | static const char AttrDoc_PointerFieldProtection[] = R"reST(No documentation.)reST" ; |
| 7290 | |
| 7291 | static const char AttrDoc_PragmaClangBSSSection[] = R"reST()reST" ; |
| 7292 | |
| 7293 | static const char AttrDoc_PragmaClangDataSection[] = R"reST()reST" ; |
| 7294 | |
| 7295 | static const char AttrDoc_PragmaClangRelroSection[] = R"reST()reST" ; |
| 7296 | |
| 7297 | static const char AttrDoc_PragmaClangRodataSection[] = R"reST()reST" ; |
| 7298 | |
| 7299 | static const char AttrDoc_PragmaClangTextSection[] = R"reST()reST" ; |
| 7300 | |
| 7301 | static const char AttrDoc_PreferredName[] = R"reST(The `preferred_name` attribute can be applied to a class template, and |
| 7302 | specifies a preferred way of naming a specialization of the template. The |
| 7303 | preferred name will be used whenever the corresponding template specialization |
| 7304 | would otherwise be printed in a diagnostic or similar context. |
| 7305 | |
| 7306 | The preferred name must be a typedef or type alias declaration that refers to a |
| 7307 | specialization of the class template (not including any type qualifiers). In |
| 7308 | general this requires the template to be declared at least twice. For example: |
| 7309 | |
| 7310 | ```c++ |
| 7311 | template<typename T> struct basic_string; |
| 7312 | using string = basic_string<char>; |
| 7313 | using wstring = basic_string<wchar_t>; |
| 7314 | template<typename T> struct [[clang::preferred_name(string), |
| 7315 | clang::preferred_name(wstring)]] basic_string { |
| 7316 | // ... |
| 7317 | }; |
| 7318 | ``` |
| 7319 | |
| 7320 | Note that the `preferred_name` attribute will be ignored when the compiler |
| 7321 | writes a C++20 Module interface now. This is due to a compiler issue |
| 7322 | (<https://github.com/llvm/llvm-project/issues/56490>) that blocks users to modularize |
| 7323 | declarations with `preferred_name`. This is intended to be fixed in the future.)reST" ; |
| 7324 | |
| 7325 | static const char AttrDoc_PreferredType[] = R"reST(This attribute allows adjusting the type of a bit-field in debug information. |
| 7326 | This can be helpful when a bit-field is intended to store an enumeration value, |
| 7327 | but has to be specified as having the enumeration's underlying type in order to |
| 7328 | facilitate compiler optimizations or bit-field packing behavior. Normally, the |
| 7329 | underlying type is what is emitted in debug information, which can make it hard |
| 7330 | for debuggers to know to map a bit-field's value back to a particular enumeration. |
| 7331 | |
| 7332 | ```c++ |
| 7333 | enum Colors { Red, Green, Blue }; |
| 7334 | |
| 7335 | struct S { |
| 7336 | [[clang::preferred_type(Colors)]] unsigned ColorVal : 2; |
| 7337 | [[clang::preferred_type(bool)]] unsigned UseAlternateColorSpace : 1; |
| 7338 | } s = { Green, false }; |
| 7339 | ``` |
| 7340 | |
| 7341 | Without the attribute, a debugger is likely to display the value `1` for `ColorVal` |
| 7342 | and `0` for `UseAlternateColorSpace`. With the attribute, the debugger may now |
| 7343 | display `Green` and `false` instead. |
| 7344 | |
| 7345 | This can be used to map a bit-field to an arbitrary type that isn't integral |
| 7346 | or an enumeration type. For example: |
| 7347 | |
| 7348 | ```c++ |
| 7349 | struct A { |
| 7350 | short a1; |
| 7351 | short a2; |
| 7352 | }; |
| 7353 | |
| 7354 | struct B { |
| 7355 | [[clang::preferred_type(A)]] unsigned b1 : 32 = 0x000F'000C; |
| 7356 | }; |
| 7357 | ``` |
| 7358 | |
| 7359 | will associate the type `A` with the `b1` bit-field and is intended to display |
| 7360 | something like this in the debugger: |
| 7361 | |
| 7362 | ```text |
| 7363 | Process 2755547 stopped |
| 7364 | * thread #1, name = 'test-preferred-', stop reason = step in |
| 7365 | frame #0: 0x0000555555555148 test-preferred-type`main at test.cxx:13:14 |
| 7366 | 10 int main() |
| 7367 | 11 { |
| 7368 | 12 B b; |
| 7369 | -> 13 return b.b1; |
| 7370 | 14 } |
| 7371 | (lldb) v -T |
| 7372 | (B) b = { |
| 7373 | (A:32) b1 = { |
| 7374 | (short) a1 = 12 |
| 7375 | (short) a2 = 15 |
| 7376 | } |
| 7377 | } |
| 7378 | ``` |
| 7379 | |
| 7380 | Note that debuggers may not be able to handle more complex mappings, and so |
| 7381 | this usage is debugger-dependent.)reST" ; |
| 7382 | |
| 7383 | static const char AttrDoc_PreserveAll[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of |
| 7384 | a function. The `preserve_all` calling convention attempts to make the code |
| 7385 | in the caller even less intrusive than the `preserve_most` calling convention. |
| 7386 | This calling convention also behaves identical to the `C` calling convention |
| 7387 | on how arguments and return values are passed, but it uses a different set of |
| 7388 | caller/callee-saved registers. This removes the burden of saving and |
| 7389 | recovering a large register set before and after the call in the caller. If |
| 7390 | the arguments are passed in callee-saved registers, then they will be |
| 7391 | preserved by the callee across the call. This doesn't apply for values |
| 7392 | returned in callee-saved registers. |
| 7393 | |
| 7394 | - On X86-64 the callee preserves all general purpose registers, except for |
| 7395 | R11. R11 can be used as a scratch register. Furthermore it also preserves |
| 7396 | all floating-point registers (XMMs/YMMs). |
| 7397 | - On AArch64 the callee preserve all general purpose registers, except X0-X8 and |
| 7398 | X16-X18. Furthermore it also preserves lower 128 bits of V8-V31 SIMD - floating |
| 7399 | point registers. |
| 7400 | |
| 7401 | The idea behind this convention is to support calls to runtime functions |
| 7402 | that don't need to call out to any other functions. |
| 7403 | |
| 7404 | This calling convention, like the `preserve_most` calling convention, will be |
| 7405 | used by a future version of the Objective-C runtime and should be considered |
| 7406 | experimental at this time.)reST" ; |
| 7407 | |
| 7408 | static const char AttrDoc_PreserveMost[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of |
| 7409 | a function. The `preserve_most` calling convention attempts to make the code |
| 7410 | in the caller as unintrusive as possible. This convention behaves identically |
| 7411 | to the `C` calling convention on how arguments and return values are passed, |
| 7412 | but it uses a different set of caller/callee-saved registers. This alleviates |
| 7413 | the burden of saving and recovering a large register set before and after the |
| 7414 | call in the caller. If the arguments are passed in callee-saved registers, |
| 7415 | then they will be preserved by the callee across the call. This doesn't |
| 7416 | apply for values returned in callee-saved registers. |
| 7417 | |
| 7418 | - On X86-64 the callee preserves all general purpose registers, except for |
| 7419 | R11. R11 can be used as a scratch register. Floating-point registers |
| 7420 | (XMMs/YMMs) are not preserved and need to be saved by the caller. |
| 7421 | - On AArch64 the callee preserve all general purpose registers, except X0-X8 and |
| 7422 | X16-X18. |
| 7423 | |
| 7424 | The idea behind this convention is to support calls to runtime functions |
| 7425 | that have a hot path and a cold path. The hot path is usually a small piece |
| 7426 | of code that doesn't use many registers. The cold path might need to call out to |
| 7427 | another function and therefore only needs to preserve the caller-saved |
| 7428 | registers, which haven't already been saved by the caller. The |
| 7429 | `preserve_most` calling convention is very similar to the `cold` calling |
| 7430 | convention in terms of caller/callee-saved registers, but they are used for |
| 7431 | different types of function calls. `coldcc` is for function calls that are |
| 7432 | rarely executed, whereas `preserve_most` function calls are intended to be |
| 7433 | on the hot path and definitely executed a lot. Furthermore `preserve_most` |
| 7434 | doesn't prevent the inliner from inlining the function call. |
| 7435 | |
| 7436 | This calling convention will be used by a future version of the Objective-C |
| 7437 | runtime and should therefore still be considered experimental at this time. |
| 7438 | Although this convention was created to optimize certain runtime calls to |
| 7439 | the Objective-C runtime, it is not limited to this runtime and might be used |
| 7440 | by other runtimes in the future too. The current implementation only |
| 7441 | supports X86-64 and AArch64, but the intention is to support more architectures |
| 7442 | in the future.)reST" ; |
| 7443 | |
| 7444 | static const char AttrDoc_PreserveNone[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of a function. |
| 7445 | The `preserve_none` calling convention tries to preserve as few general |
| 7446 | registers as possible. So all general registers are caller saved registers. It |
| 7447 | also uses more general registers to pass arguments. This attribute doesn't |
| 7448 | impact floating-point registers. `preserve_none`'s ABI is still unstable, and |
| 7449 | may be changed in the future. |
| 7450 | |
| 7451 | - On X86-64, only RSP and RBP are preserved by the callee. |
| 7452 | Registers R12, R13, R14, R15, RDI, RSI, RDX, RCX, R8, R9, R11, and RAX now can |
| 7453 | be used to pass function arguments. Floating-point registers (XMMs/YMMs) still |
| 7454 | follow the C calling convention. |
| 7455 | - On AArch64, only LR and FP are preserved by the callee. |
| 7456 | Registers X20-X28, X0-X7, and X9-X14 are used to pass function arguments. |
| 7457 | X8, X16-X19, SIMD and floating-point registers follow the AAPCS calling |
| 7458 | convention. X15 is not available for argument passing on Windows, but is |
| 7459 | used to pass arguments on other platforms.)reST" ; |
| 7460 | |
| 7461 | static const char AttrDoc_PtGuardedBy[] = R"reST(No documentation.)reST" ; |
| 7462 | |
| 7463 | static const char AttrDoc_PtGuardedVar[] = R"reST(No documentation.)reST" ; |
| 7464 | |
| 7465 | static const char AttrDoc_Ptr32[] = R"reST(The `__ptr32` qualifier represents a native pointer on a 32-bit system. On a |
| 7466 | 64-bit system, a pointer with `__ptr32` is extended to a 64-bit pointer. The |
| 7467 | `__sptr` and `__uptr` qualifiers can be used to specify whether the pointer |
| 7468 | is sign extended or zero extended. This qualifier is enabled under |
| 7469 | `-fms-extensions`.)reST" ; |
| 7470 | |
| 7471 | static const char AttrDoc_Ptr64[] = R"reST(The `__ptr64` qualifier represents a native pointer on a 64-bit system. On a |
| 7472 | 32-bit system, a `__ptr64` pointer is truncated to a 32-bit pointer. This |
| 7473 | qualifier is enabled under `-fms-extensions`.)reST" ; |
| 7474 | |
| 7475 | static const char AttrDoc_Pure[] = R"reST(No documentation.)reST" ; |
| 7476 | |
| 7477 | static const char AttrDoc_RISCVInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt))` attribute on RISCV |
| 7478 | targets. This attribute may be attached to a function definition and instructs |
| 7479 | the backend to generate appropriate function entry/exit code so that it can be |
| 7480 | used directly as an interrupt service routine. |
| 7481 | |
| 7482 | Permissible values for this parameter are `machine`, `supervisor`, |
| 7483 | `rnmi`, `qci-nest`, `qci-nonest`, `SiFive-CLIC-preemptible`, and |
| 7484 | `SiFive-CLIC-stack-swap`. If there is no parameter, then it defaults to |
| 7485 | `machine`. |
| 7486 | |
| 7487 | The `rnmi` value is used for resumable non-maskable interrupts. It requires the |
| 7488 | standard Smrnmi extension. |
| 7489 | |
| 7490 | The `qci-nest` and `qci-nonest` values require Qualcomm's Xqciint extension |
| 7491 | and are used for Machine-mode Interrupts and Machine-mode Non-maskable |
| 7492 | interrupts. These use the following instructions from Xqciint to save and |
| 7493 | restore interrupt state to the stack -- the `qci-nest` value will use |
| 7494 | `qc.c.mienter.nest` and the `qci-nonest` value will use `qc.c.mienter` to |
| 7495 | begin the interrupt handler. Both of these will use `qc.c.mileaveret` to |
| 7496 | restore the state and return to the previous context. |
| 7497 | |
| 7498 | The `SiFive-CLIC-preemptible` and `SiFive-CLIC-stack-swap` values are used |
| 7499 | for machine-mode interrupts. For `SiFive-CLIC-preemptible` interrupts, the |
| 7500 | values of `mcause` and `mepc` are saved onto the stack, and interrupts are |
| 7501 | re-enabled. For `SiFive-CLIC-stack-swap` interrupts, the stack pointer is |
| 7502 | swapped with `mscratch` before its first use and after its last use. |
| 7503 | |
| 7504 | The SiFive CLIC values may be combined with each other and with the `machine` |
| 7505 | attribute value. Any other combination of different values is not allowed. |
| 7506 | |
| 7507 | Repeated interrupt attribute on the same declaration will cause a warning |
| 7508 | to be emitted. In case of repeated declarations, the last one prevails. |
| 7509 | |
| 7510 | Refer to: |
| 7511 | <https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html> |
| 7512 | <https://riscv.org/specifications/privileged-isa/> |
| 7513 | The RISC-V Instruction Set Manual Volume II: Privileged Architecture |
| 7514 | Version 1.10. |
| 7515 | <https://github.com/quic/riscv-unified-db/releases/tag/Xqci-0.13.0> |
| 7516 | <https://sifive.cdn.prismic.io/sifive/d1984d2b-c9b9-4c91-8de0-d68a5e64fa0f_sifive-interrupt-cookbook-v1p2.pdf>)reST" ; |
| 7517 | |
| 7518 | static const char AttrDoc_RISCVVLSCC[] = R"reST(The `riscv_vls_cc` attribute can be applied to a function. Functions |
| 7519 | declared with this attribute will utilize the standard fixed-length vector |
| 7520 | calling convention variant instead of the default calling convention defined by |
| 7521 | the ABI. This variant aims to pass fixed-length vectors via vector registers, |
| 7522 | if possible, rather than through general-purpose registers.)reST" ; |
| 7523 | |
| 7524 | static const char AttrDoc_RISCVVectorCC[] = R"reST(The `riscv_vector_cc` attribute can be applied to a function. It preserves 15 |
| 7525 | registers namely, v1-v7 and v24-v31 as callee-saved. Callers thus don't need |
| 7526 | to save these registers before function calls, and callees only need to save |
| 7527 | them if they use them.)reST" ; |
| 7528 | |
| 7529 | static const char AttrDoc_RandomizeLayout[] = R"reST(The attribute `randomize_layout`, when attached to a C structure, selects it |
| 7530 | for structure layout field randomization; a compile-time hardening technique. A |
| 7531 | "seed" value, is specified via the `-frandomize-layout-seed=` command line flag. |
| 7532 | For example: |
| 7533 | |
| 7534 | ```bash |
| 7535 | SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'` |
| 7536 | make ... CFLAGS="-frandomize-layout-seed=$SEED" ... |
| 7537 | ``` |
| 7538 | |
| 7539 | You can also supply the seed in a file with `-frandomize-layout-seed-file=`. |
| 7540 | For example: |
| 7541 | |
| 7542 | ```bash |
| 7543 | od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt |
| 7544 | make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ... |
| 7545 | ``` |
| 7546 | |
| 7547 | The randomization is deterministic based for a given seed, so the entire |
| 7548 | program should be compiled with the same seed, but keep the seed safe |
| 7549 | otherwise. |
| 7550 | |
| 7551 | The attribute `no_randomize_layout`, when attached to a C structure, |
| 7552 | instructs the compiler that this structure should not have its field layout |
| 7553 | randomized.)reST" ; |
| 7554 | |
| 7555 | static const char AttrDoc_ReadOnlyPlacement[] = R"reST(This attribute is attached to a structure, class or union declaration. |
| 7556 | |
| 7557 | : When attached to a record declaration/definition, it checks if all instances |
| 7558 | of this type can be placed in the read-only data segment of the program. If it |
| 7559 | finds an instance that can not be placed in a read-only segment, the compiler |
| 7560 | emits a warning at the source location where the type was used. |
| 7561 | |
| 7562 | Examples: |
| 7563 | \* `struct __attribute__((enforce_read_only_placement)) Foo;` |
| 7564 | \* `struct __attribute__((enforce_read_only_placement)) Bar { ... };` |
| 7565 | |
| 7566 | Both `Foo` and `Bar` types have the `enforce_read_only_placement` attribute. |
| 7567 | |
| 7568 | The goal of introducing this attribute is to assist developers with writing secure |
| 7569 | code. A `const`-qualified global is generally placed in the read-only section |
| 7570 | of the memory that has additional run time protection from malicious writes. By |
| 7571 | attaching this attribute to a declaration, the developer can express the intent |
| 7572 | to place all instances of the annotated type in the read-only program memory. |
| 7573 | |
| 7574 | Note 1: The attribute doesn't guarantee that the object will be placed in the |
| 7575 | read-only data segment as it does not instruct the compiler to ensure such |
| 7576 | a placement. It emits a warning if something in the code can be proven to prevent |
| 7577 | an instance from being placed in the read-only data segment. |
| 7578 | |
| 7579 | Note 2: Currently, clang only checks if all global declarations of a given type 'T' |
| 7580 | are `const`-qualified. The following conditions would also prevent the data to be |
| 7581 | put into read only segment, but the corresponding warnings are not yet implemented. |
| 7582 | |
| 7583 | 1. An instance of type `T` is allocated on the heap/stack. |
| 7584 | 2. Type `T` defines/inherits a mutable field. |
| 7585 | 3. Type `T` defines/inherits non-constexpr constructor(s) for initialization. |
| 7586 | 4. A field of type `T` is defined by type `Q`, which does not bear the |
| 7587 | `enforce_read_only_placement` attribute. |
| 7588 | 5. A type `Q` inherits from type `T` and it does not have the |
| 7589 | `enforce_read_only_placement` attribute.)reST" ; |
| 7590 | |
| 7591 | static const char AttrDoc_ReentrantCapability[] = R"reST(No documentation.)reST" ; |
| 7592 | |
| 7593 | static const char AttrDoc_RegCall[] = R"reST(On x86 targets, this attribute changes the calling convention to |
| 7594 | [\_\_regcall][__regcall] convention. This convention aims to pass as many arguments |
| 7595 | as possible in registers. It also tries to utilize registers for the |
| 7596 | return value whenever it is possible. |
| 7597 | |
| 7598 | [__regcall]: https://www.intel.com/content/www/us/en/docs/dpcpp-cpp-compiler/developer-guide-reference/2023-2/c-c-sycl-calling-conventions.html)reST" ; |
| 7599 | |
| 7600 | static const char AttrDoc_Reinitializes[] = R"reST(The `reinitializes` attribute can be applied to a non-static, non-const C++ |
| 7601 | member function to indicate that this member function reinitializes the entire |
| 7602 | object to a known state, independent of the previous state of the object. |
| 7603 | |
| 7604 | This attribute can be interpreted by static analyzers that warn about uses of an |
| 7605 | object that has been left in an indeterminate state by a move operation. If a |
| 7606 | member function marked with the `reinitializes` attribute is called on a |
| 7607 | moved-from object, the analyzer can conclude that the object is no longer in an |
| 7608 | indeterminate state. |
| 7609 | |
| 7610 | A typical example where this attribute would be used is on functions that clear |
| 7611 | a container class: |
| 7612 | |
| 7613 | ```c++ |
| 7614 | template <class T> |
| 7615 | class Container { |
| 7616 | public: |
| 7617 | ... |
| 7618 | [[clang::reinitializes]] void Clear(); |
| 7619 | ... |
| 7620 | }; |
| 7621 | ```)reST" ; |
| 7622 | |
| 7623 | static const char AttrDoc_ReleaseCapability[] = R"reST(Marks a function as releasing a capability.)reST" ; |
| 7624 | |
| 7625 | static const char AttrDoc_ReleaseHandle[] = R"reST(If a function parameter is annotated with `release_handle(tag)` it is assumed to |
| 7626 | close the handle. It is also assumed to require an open handle to work with. The |
| 7627 | attribute requires a string literal argument to identify the handle being released. |
| 7628 | |
| 7629 | ```c++ |
| 7630 | zx_status_t zx_handle_close(zx_handle_t handle [[clang::release_handle("tag")]]); |
| 7631 | ```)reST" ; |
| 7632 | |
| 7633 | static const char AttrDoc_ReqdWorkGroupSize[] = R"reST(No documentation.)reST" ; |
| 7634 | |
| 7635 | static const char AttrDoc_RequiresCapability[] = R"reST(No documentation.)reST" ; |
| 7636 | |
| 7637 | static const char AttrDoc_Restrict[] = R"reST(The `malloc` attribute has two forms with different functionality. The first |
| 7638 | is when it is used without arguments, where it marks that a function acts like |
| 7639 | a system memory allocation function, returning a pointer to allocated storage |
| 7640 | that does not alias storage from any other object accessible to the caller. |
| 7641 | |
| 7642 | The second form is when `malloc` takes one or two arguments. The first |
| 7643 | argument names a function that should be associated with this function as its |
| 7644 | deallocation function. When this form is used, it enables the compiler to |
| 7645 | diagnose when the incorrect deallocation function is used with this variable. |
| 7646 | However the associated warning, spelled `-Wmismatched-dealloc` in GCC, is not |
| 7647 | yet implemented in clang.)reST" ; |
| 7648 | |
| 7649 | static const char AttrDoc_Retain[] = R"reST(This attribute, when attached to a function or variable definition, prevents |
| 7650 | section garbage collection in the linker. It does not prevent other discard |
| 7651 | mechanisms, such as archive member selection, and COMDAT group resolution. |
| 7652 | |
| 7653 | If the compiler does not emit the definition, e.g. because it was not used in |
| 7654 | the translation unit or the compiler was able to eliminate all of the uses, |
| 7655 | this attribute has no effect. This attribute is typically combined with the |
| 7656 | `used` attribute to force the definition to be emitted and preserved into the |
| 7657 | final linked image. |
| 7658 | |
| 7659 | This attribute is only necessary on ELF targets; other targets prevent section |
| 7660 | garbage collection by the linker when using the `used` attribute alone. |
| 7661 | Using the attributes together should result in consistent behavior across |
| 7662 | targets. |
| 7663 | |
| 7664 | This attribute requires the linker to support the `SHF_GNU_RETAIN` extension. |
| 7665 | This support is available in GNU `ld` and `gold` as of binutils 2.36, as |
| 7666 | well as in `ld.lld` 13.)reST" ; |
| 7667 | |
| 7668 | static const char AttrDoc_ReturnTypestate[] = R"reST(The `return_typestate` attribute can be applied to functions or parameters. |
| 7669 | When applied to a function the attribute specifies the state of the returned |
| 7670 | value. The function's body is checked to ensure that it always returns a value |
| 7671 | in the specified state. On the caller side, values returned by the annotated |
| 7672 | function are initialized to the given state. |
| 7673 | |
| 7674 | When applied to a function parameter it modifies the state of an argument after |
| 7675 | a call to the function returns. The function's body is checked to ensure that |
| 7676 | the parameter is in the expected state before returning.)reST" ; |
| 7677 | |
| 7678 | static const char AttrDoc_ReturnsNonNull[] = R"reST(The `returns_nonnull` attribute indicates that a particular function (or |
| 7679 | Objective-C method) always returns a non-null pointer. For example, a |
| 7680 | particular system `malloc` might be defined to terminate a process when |
| 7681 | memory is not available rather than returning a null pointer: |
| 7682 | |
| 7683 | ```c |
| 7684 | extern void * malloc (size_t size) __attribute__((returns_nonnull)); |
| 7685 | ``` |
| 7686 | |
| 7687 | The `returns_nonnull` attribute implies that returning a null pointer is |
| 7688 | undefined behavior, which the optimizer may take advantage of. The `_Nonnull` |
| 7689 | type qualifier indicates that a pointer cannot be null in a more general manner |
| 7690 | (because it is part of the type system) and does not imply undefined behavior, |
| 7691 | making it more widely applicable)reST" ; |
| 7692 | |
| 7693 | static const char AttrDoc_ReturnsTwice[] = R"reST(No documentation.)reST" ; |
| 7694 | |
| 7695 | static const char AttrDoc_RootSignature[] = R"reST(The `RootSignature` attribute applies to HLSL entry functions to define what |
| 7696 | types of resources are bound to the graphics pipeline. |
| 7697 | |
| 7698 | For details about the use and specification of Root Signatures please see here: |
| 7699 | <https://learn.microsoft.com/en-us/windows/win32/direct3d12/root-signatures>)reST" ; |
| 7700 | |
| 7701 | static const char AttrDoc_SPtr[] = R"reST(The `__sptr` qualifier specifies that a 32-bit pointer should be sign |
| 7702 | extended when converted to a 64-bit pointer.)reST" ; |
| 7703 | |
| 7704 | static const char AttrDoc_SYCLExternal[] = R"reST(The `sycl_external` attribute indicates that a function defined in another |
| 7705 | translation unit may be called by a device function defined in the current |
| 7706 | translation unit or, if defined in the current translation unit, the function |
| 7707 | may be called by device functions defined in other translation units. |
| 7708 | The attribute is intended for use in the implementation of the `SYCL_EXTERNAL` |
| 7709 | macro as specified in section 5.10.1, "SYCL functions and member functions |
| 7710 | linkage", of the SYCL 2020 specification. |
| 7711 | |
| 7712 | The attribute only appertains to functions and only those that meet the |
| 7713 | following requirements: |
| 7714 | |
| 7715 | - Has external linkage |
| 7716 | - Is not explicitly defined as deleted (the function may be an explicitly |
| 7717 | defaulted function that is defined as deleted) |
| 7718 | |
| 7719 | The attribute shall be present on the first declaration of a function and |
| 7720 | may optionally be present on subsequent declarations. |
| 7721 | |
| 7722 | When compiling for a SYCL device target that does not support the generic |
| 7723 | address space, the function shall not specify a raw pointer or reference type |
| 7724 | as the return type or as a parameter type. |
| 7725 | See section 5.10, "SYCL offline linking", of the SYCL 2020 specification. |
| 7726 | The following examples demonstrate the use of this attribute: |
| 7727 | |
| 7728 | ```c++ |
| 7729 | [[clang::sycl_external]] void Foo(); // Ok. |
| 7730 | |
| 7731 | [[clang::sycl_external]] void Bar() { /* ... */ } // Ok. |
| 7732 | |
| 7733 | [[clang::sycl_external]] extern void Baz(); // Ok. |
| 7734 | |
| 7735 | [[clang::sycl_external]] static void Quux() { /* ... */ } // error: Quux() has internal linkage. |
| 7736 | ```)reST" ; |
| 7737 | |
| 7738 | static const char AttrDoc_SYCLKernel[] = R"reST(The `sycl_kernel` attribute specifies that a function template will be used |
| 7739 | to outline device code and to generate an OpenCL kernel. |
| 7740 | Here is a code example of the SYCL program, which demonstrates the compiler's |
| 7741 | outlining job: |
| 7742 | |
| 7743 | ```c++ |
| 7744 | int foo(int x) { return ++x; } |
| 7745 | |
| 7746 | using namespace cl::sycl; |
| 7747 | queue Q; |
| 7748 | buffer<int, 1> a(range<1>{1024}); |
| 7749 | Q.submit([&](handler& cgh) { |
| 7750 | auto A = a.get_access<access::mode::write>(cgh); |
| 7751 | cgh.parallel_for<init_a>(range<1>{1024}, [=](id<1> index) { |
| 7752 | A[index] = index[0] + foo(42); |
| 7753 | }); |
| 7754 | } |
| 7755 | ``` |
| 7756 | |
| 7757 | A C++ function object passed to the `parallel_for` is called a "SYCL kernel". |
| 7758 | A SYCL kernel defines the entry point to the "device part" of the code. The |
| 7759 | compiler will emit all symbols accessible from a "kernel". In this code |
| 7760 | example, the compiler will emit "foo" function. More details about the |
| 7761 | compilation of functions for the device part can be found in the SYCL 1.2.1 |
| 7762 | specification Section 6.4. |
| 7763 | To show to the compiler entry point to the "device part" of the code, the SYCL |
| 7764 | runtime can use the `sycl_kernel` attribute in the following way: |
| 7765 | |
| 7766 | ```c++ |
| 7767 | namespace cl { |
| 7768 | namespace sycl { |
| 7769 | class handler { |
| 7770 | template <typename KernelName, typename KernelType/*, ...*/> |
| 7771 | __attribute__((sycl_kernel)) void sycl_kernel_function(KernelType KernelFuncObj) { |
| 7772 | // ... |
| 7773 | KernelFuncObj(); |
| 7774 | } |
| 7775 | |
| 7776 | template <typename KernelName, typename KernelType, int Dims> |
| 7777 | void parallel_for(range<Dims> NumWorkItems, KernelType KernelFunc) { |
| 7778 | #ifdef __SYCL_DEVICE_ONLY__ |
| 7779 | sycl_kernel_function<KernelName, KernelType, Dims>(KernelFunc); |
| 7780 | #else |
| 7781 | // Host implementation |
| 7782 | #endif |
| 7783 | } |
| 7784 | }; |
| 7785 | } // namespace sycl |
| 7786 | } // namespace cl |
| 7787 | ``` |
| 7788 | |
| 7789 | The compiler will also generate an OpenCL kernel using the function marked with |
| 7790 | the `sycl_kernel` attribute. |
| 7791 | Here is the list of SYCL device compiler expectations with regard to the |
| 7792 | function marked with the `sycl_kernel` attribute: |
| 7793 | |
| 7794 | - The function must be a template with at least two type template parameters. |
| 7795 | The compiler generates an OpenCL kernel and uses the first template parameter |
| 7796 | as a unique name for the generated OpenCL kernel. The host application uses |
| 7797 | this unique name to invoke the OpenCL kernel generated for the SYCL kernel |
| 7798 | specialized by this name and second template parameter `KernelType` (which |
| 7799 | might be an unnamed function object type). |
| 7800 | - The function must have at least one parameter. The first parameter is |
| 7801 | required to be a function object type (named or unnamed i.e. lambda). The |
| 7802 | compiler uses function object type fields to generate OpenCL kernel |
| 7803 | parameters. |
| 7804 | - The function must return void. The compiler reuses the body of marked functions to |
| 7805 | generate the OpenCL kernel body, and the OpenCL kernel must return `void`. |
| 7806 | |
| 7807 | The SYCL kernel in the previous code sample meets these expectations.)reST" ; |
| 7808 | |
| 7809 | static const char AttrDoc_SYCLKernelEntryPoint[] = R"reST(The `sycl_kernel_entry_point` attribute facilitates the launch of a SYCL |
| 7810 | kernel and the generation of an offload kernel entry point, sometimes called |
| 7811 | a SYCL kernel caller function, suitable for invoking a SYCL kernel on an |
| 7812 | offload device. The attribute is intended for use in the implementation of |
| 7813 | SYCL kernel invocation functions like the `single_task` and `parallel_for` |
| 7814 | member functions of the `sycl::handler` class specified in section 4.9.4, |
| 7815 | "Command group `handler` class", of the SYCL 2020 specification. |
| 7816 | |
| 7817 | The attribute requires a single type argument that meets the requirements for |
| 7818 | a SYCL kernel name as described in section 5.2, "Naming of kernels", of the |
| 7819 | SYCL 2020 specification. A unique kernel name type is required for each |
| 7820 | function declared with the attribute. The attribute may not first appear on a |
| 7821 | declaration that follows a definition of the function. |
| 7822 | |
| 7823 | The attribute only appertains to functions and only those that meet the |
| 7824 | following requirements. |
| 7825 | |
| 7826 | - Has a non-deduced `void` return type. |
| 7827 | - Is not a constructor or destructor. |
| 7828 | - Is not a non-static member function with an explicit object parameter. |
| 7829 | - Is not a C variadic function. |
| 7830 | - Is not a coroutine. |
| 7831 | - Is not defined as deleted or as defaulted. |
| 7832 | - Is not defined with a function try block. |
| 7833 | - Is not declared with the `constexpr` or `consteval` specifiers. |
| 7834 | - Is not declared with the `[[noreturn]]` attribute. |
| 7835 | |
| 7836 | Use in the implementation of a SYCL kernel invocation function might look as |
| 7837 | follows. |
| 7838 | |
| 7839 | ```c++ |
| 7840 | namespace sycl { |
| 7841 | class handler { |
| 7842 | template<typename KernelName, typename... Ts> |
| 7843 | void sycl_kernel_launch(const char* kernelSymbol, Ts&&... kernelArgs) { |
| 7844 | // This code will run on the host and is responsible for calling functions |
| 7845 | // appropriate for the desired offload backend (OpenCL, CUDA, HIP, |
| 7846 | // Level Zero, etc...) to copy the kernel arguments denoted by kernelArgs |
| 7847 | // to a device and to schedule an invocation of the offload kernel entry |
| 7848 | // point denoted by kernelSymbol with the copied arguments. |
| 7849 | } |
| 7850 | |
| 7851 | template<typename KernelName, typename KernelType> |
| 7852 | [[ clang::sycl_kernel_entry_point(KernelName) ]] |
| 7853 | void kernel_entry_point(KernelType kernelFunc) { |
| 7854 | // This code will run on the device. The call to kernelFunc() invokes |
| 7855 | // the SYCL kernel. |
| 7856 | kernelFunc(); |
| 7857 | } |
| 7858 | |
| 7859 | public: |
| 7860 | template<typename KernelName, typename KernelType> |
| 7861 | void single_task(const KernelType& kernelFunc) { |
| 7862 | // This code will run on the host. kernel_entry_point() is called to |
| 7863 | // trigger generation of an offload kernel entry point and to schedule |
| 7864 | // an invocation of it on a device with kernelFunc (a SYCL kernel object) |
| 7865 | // passed as a kernel argument. This call will result in an implicit call |
| 7866 | // to sycl_kernel_launch() with the symbol name for the generated offload |
| 7867 | // kernel entry point passed as the first function argument followed by |
| 7868 | // kernelFunc. |
| 7869 | kernel_entry_point<KernelName>(kernelFunc); |
| 7870 | } |
| 7871 | }; |
| 7872 | } // namespace sycl |
| 7873 | ``` |
| 7874 | |
| 7875 | A SYCL kernel object is a callable object of class type that is constructed on |
| 7876 | a host, often via a lambda expression, and then passed to a SYCL kernel |
| 7877 | invocation function to be executed on an offload device. The `kernelFunc` |
| 7878 | parameters in the example code above correspond to SYCL kernel objects. |
| 7879 | |
| 7880 | A SYCL kernel object type is required to satisfy the device copyability |
| 7881 | requirements specified in section 3.13.1, "Device copyable", of the SYCL 2020 |
| 7882 | specification. Additionally, any data members of the kernel object type are |
| 7883 | required to satisfy section 4.12.4, "Rules for parameter passing to kernels". |
| 7884 | For most types, these rules require that the type is trivially copyable. |
| 7885 | However, the SYCL specification mandates that certain special SYCL types, such |
| 7886 | as `sycl::accessor` and `sycl::stream`, be device copyable even if they are |
| 7887 | not trivially copyable. These types require special handling because they cannot |
| 7888 | necessarily be copied to device memory as if by `memcpy()`. |
| 7889 | |
| 7890 | The SYCL kernel object and its data members constitute the parameters of an |
| 7891 | offload kernel. An offload kernel consists of an offload entry point function |
| 7892 | and the set of all functions and variables that are directly or indirectly used |
| 7893 | by the entry point function. |
| 7894 | |
| 7895 | A SYCL kernel invocation function is responsible for performing the following |
| 7896 | tasks (likely with the help of an offload backend like OpenCL): |
| 7897 | |
| 7898 | 1. Identifying the offload kernel entry point to be used for the SYCL kernel. |
| 7899 | 2. Validating that the SYCL kernel object type and its data members meet the |
| 7900 | SYCL device copyability and kernel parameter requirements noted above. |
| 7901 | 3. Copying the SYCL kernel object and any other kernel arguments to device |
| 7902 | memory including any special handling required for SYCL special types. |
| 7903 | 4. Initiating execution of the offload kernel entry point. |
| 7904 | |
| 7905 | The offload kernel entry point for a SYCL kernel performs the following tasks: |
| 7906 | |
| 7907 | 1. Calling the `operator()` member function of the SYCL kernel object. |
| 7908 | |
| 7909 | The `sycl_kernel_entry_point` attribute facilitates or automates these tasks |
| 7910 | by providing generation of an offload kernel entry point with a unique symbol |
| 7911 | name, type checking of kernel argument requirements, and initiation of kernel |
| 7912 | execution via synthesized calls to a `sycl_kernel_launch` template. |
| 7913 | |
| 7914 | A function declared with the `sycl_kernel_entry_point` attribute specifies |
| 7915 | the parameters and body of an offload entry point function. Consider the |
| 7916 | following call to the `single_task()` SYCL kernel invocation function assuming |
| 7917 | an implementation similar to the one shown above. |
| 7918 | |
| 7919 | ```c++ |
| 7920 | struct S { int i; }; |
| 7921 | void f(sycl::handler &handler, sycl::stream &sout, S s) { |
| 7922 | handler.single_task<struct KN>([=] { |
| 7923 | sout << "The value of s.i is " << s.i << "\n"; |
| 7924 | }); |
| 7925 | } |
| 7926 | ``` |
| 7927 | |
| 7928 | The SYCL kernel object is the result of the lambda expression. The call to |
| 7929 | `kernel_entry_point()` via the call to `single_task()` triggers the |
| 7930 | generation of an offload kernel entry point function that looks approximately |
| 7931 | as follows. |
| 7932 | |
| 7933 | ```c++ |
| 7934 | void sycl-kernel-caller-for-KN(kernel-type kernelFunc) { |
| 7935 | kernelFunc(); |
| 7936 | } |
| 7937 | ``` |
| 7938 | |
| 7939 | There are a few items worthy of note: |
| 7940 | |
| 7941 | 1. `sycl-kernel-caller-for-KN` is an exposition only name; the actual name |
| 7942 | generated for an entry point is an implementation detail and subject to |
| 7943 | change. However, the name will incorporate the SYCL kernel name, `KN`, |
| 7944 | that was passed as the `KernelName` template parameter to |
| 7945 | `single_task()` and eventually provided as the argument to the |
| 7946 | `sycl_kernel_entry_point` attribute in order to ensure that a unique |
| 7947 | name is generated for each entry point. There is a one-to-one correspondence |
| 7948 | between SYCL kernel names and offload kernel entry points. |
| 7949 | 2. The SYCL kernel is a lambda closure type and therefore has no name; |
| 7950 | `kernel-type` is substituted above and corresponds to the `KernelType` |
| 7951 | template parameter deduced in the call to `single_task()`. |
| 7952 | 3. The parameter and the call to `kernelFunc()` in the function body |
| 7953 | correspond to the definition of `kernel_entry_point()` as called by |
| 7954 | `single_task()`. |
| 7955 | 4. The parameter is type checked for conformance with the SYCL device |
| 7956 | copyability and kernel parameter requirements. |
| 7957 | |
| 7958 | Within `single_task()`, the call to `kernel_entry_point()` is effectively |
| 7959 | replaced with a synthesized call to a ''sycl_kernel_launch\`\` template that |
| 7960 | looks approximately as follows. |
| 7961 | |
| 7962 | ```c++ |
| 7963 | sycl_kernel_launch<KN>("sycl-kernel-caller-for-KN", kernelFunc); |
| 7964 | ``` |
| 7965 | |
| 7966 | There are a few items worthy of note: |
| 7967 | |
| 7968 | 1. Lookup for the `sycl_kernel_launch` template is performed as if from the |
| 7969 | body of the (possibly instantiated) definition of `kernel_entry_point()`. |
| 7970 | If name lookup or overload resolution fails, the program is ill-formed. |
| 7971 | If the selected overload is a non-static member function, then `this` is |
| 7972 | passed as the implicit object parameter. |
| 7973 | 2. Function arguments passed to `sycl_kernel_launch()` are passed |
| 7974 | as if by `std::move(x)`. |
| 7975 | 3. The `sycl_kernel_launch` template is expected to be provided by the SYCL |
| 7976 | library implementation. It is responsible for copying the kernel arguments |
| 7977 | to device memory and for scheduling execution of the generated offload |
| 7978 | kernel entry point identified by the symbol name passed as the first |
| 7979 | function argument. `sycl-kernel-caller-for-KN` is substituted above for |
| 7980 | the actual symbol name that would be generated for the offload kernel entry |
| 7981 | point. |
| 7982 | |
| 7983 | It is not necessary for a function declared with the `sycl_kernel_entry_point` |
| 7984 | attribute to be called for the offload kernel entry point to be emitted. For |
| 7985 | inline functions and function templates, any ODR-use will suffice. For other |
| 7986 | functions, an ODR-use is not required; the offload kernel entry point will be |
| 7987 | emitted if the function is defined. In any case, a call to the function is |
| 7988 | required for the synthesized call to `sycl_kernel_launch()` to occur. |
| 7989 | |
| 7990 | A function declared with the `sycl_kernel_entry_point` attribute may include |
| 7991 | an exception specification. If a non-throwing exception specification is |
| 7992 | present, an exception propagating from the implicit call to the |
| 7993 | `sycl_kernel_launch` template will result in a call to `std::terminate()`. |
| 7994 | Otherwise, such an exception will propagate normally. |
| 7995 | |
| 7996 | Functions declared with the `sycl_kernel_entry_point` attribute are not |
| 7997 | limited to the simple example shown above. They may have additional template |
| 7998 | parameters, declare additional function parameters, and have complex control |
| 7999 | flow in the function body. The function must abide by the language feature |
| 8000 | restrictions described in section 5.4, "Language restrictions for device |
| 8001 | functions" in the SYCL 2020 specification. If the function is a non-static |
| 8002 | member function, `this` shall not be used in a potentially evaluated |
| 8003 | expression.)reST" ; |
| 8004 | |
| 8005 | static const char AttrDoc_SYCLSpecialClass[] = R"reST(SYCL defines some special classes (accessor, sampler, and stream) which require |
| 8006 | specific handling during the generation of the SPIR entry point. |
| 8007 | The `__attribute__((sycl_special_class))` attribute is used in SYCL |
| 8008 | headers to indicate that a class or a struct needs a specific handling when |
| 8009 | it is passed from host to device. |
| 8010 | Special classes will have a mandatory `__init` method and an optional |
| 8011 | `__finalize` method (the `__finalize` method is used only with the |
| 8012 | `stream` type). Kernel parameters types are extract from the `__init` method |
| 8013 | parameters. The kernel function arguments list is derived from the |
| 8014 | arguments of the `__init` method. The arguments of the `__init` method are |
| 8015 | copied into the kernel function argument list and the `__init` and |
| 8016 | `__finalize` methods are called at the beginning and the end of the kernel, |
| 8017 | respectively. |
| 8018 | The `__init` and `__finalize` methods must be defined inside the |
| 8019 | special class. |
| 8020 | Please note that this is an attribute that is used as an internal |
| 8021 | implementation detail and not intended to be used by external users. |
| 8022 | |
| 8023 | The syntax of the attribute is as follows: |
| 8024 | |
| 8025 | ```text |
| 8026 | class __attribute__((sycl_special_class)) accessor {}; |
| 8027 | class [[clang::sycl_special_class]] accessor {}; |
| 8028 | ``` |
| 8029 | |
| 8030 | This is a code example that illustrates the use of the attribute: |
| 8031 | |
| 8032 | ```c++ |
| 8033 | class __attribute__((sycl_special_class)) SpecialType { |
| 8034 | int F1; |
| 8035 | int F2; |
| 8036 | void __init(int f1) { |
| 8037 | F1 = f1; |
| 8038 | F2 = f1; |
| 8039 | } |
| 8040 | void __finalize() {} |
| 8041 | public: |
| 8042 | SpecialType() = default; |
| 8043 | int getF2() const { return F2; } |
| 8044 | }; |
| 8045 | |
| 8046 | int main () { |
| 8047 | SpecialType T; |
| 8048 | cgh.single_task([=] { |
| 8049 | T.getF2(); |
| 8050 | }); |
| 8051 | } |
| 8052 | ``` |
| 8053 | |
| 8054 | This would trigger the following kernel entry point in the AST: |
| 8055 | |
| 8056 | ```c++ |
| 8057 | void __sycl_kernel(int f1) { |
| 8058 | SpecialType T; |
| 8059 | T.__init(f1); |
| 8060 | ... |
| 8061 | T.__finalize() |
| 8062 | } |
| 8063 | ```)reST" ; |
| 8064 | |
| 8065 | static const char AttrDoc_ScopedLockable[] = R"reST(No documentation.)reST" ; |
| 8066 | |
| 8067 | static const char AttrDoc_Section[] = R"reST(The `section` attribute allows you to specify a specific section a |
| 8068 | global variable or function should be in after translation.)reST" ; |
| 8069 | |
| 8070 | static const char AttrDoc_SelectAny[] = R"reST(This attribute appertains to a global symbol, causing it to have a weak |
| 8071 | definition ( |
| 8072 | [linkonce](https://llvm.org/docs/LangRef.html#linkage-types) |
| 8073 | ), allowing the linker to select any definition. |
| 8074 | |
| 8075 | For more information see |
| 8076 | [gcc documentation](https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html) |
| 8077 | or [msvc documentation](https://docs.microsoft.com/pl-pl/cpp/cpp/selectany).)reST" ; |
| 8078 | |
| 8079 | static const char AttrDoc_Sentinel[] = R"reST(The `sentinel` attribute can be applied to variadic functions and pointers to |
| 8080 | variadic functions, to diagnose each function call that does not pass a |
| 8081 | sentinel value (a null pointer constant) as the last argument to the function |
| 8082 | call. The attribute accepts two optional arguments: the first argument is the |
| 8083 | position of the expected sentinel value, starting from the last parameter. The |
| 8084 | second argument describes whether the last fixed parameter is treated as a |
| 8085 | valid sentinel value when set to '1'. |
| 8086 | All arguments described above default to '0' when elided. |
| 8087 | The attribute is also supported with blocks and in Objective-C. |
| 8088 | |
| 8089 | ```c |
| 8090 | void foo(const char*, ...) __attribute__((sentinel)); |
| 8091 | void bar(int, ...) __attribute__((sentinel(1))); |
| 8092 | void baz(const char*, const char*, ...) __attribute__((sentinel(0, 1))); |
| 8093 | |
| 8094 | void example() { |
| 8095 | foo("Example", (void*)0); |
| 8096 | foo("Another", "example", NULL); |
| 8097 | foo("Missing", "sentinel"); // Not OK |
| 8098 | |
| 8099 | bar(1, 2, NULL, 3); // OK: sentinel value at the 2nd to last position |
| 8100 | bar(1, 2, 3, nullptr, 4); // OK: `nullptr` is valid in C23 |
| 8101 | bar(1, 2, 3, 4, NULL); // Not OK |
| 8102 | |
| 8103 | baz("Test", "with", "multiple", "args", NULL); |
| 8104 | baz("One", NULL); // OK: last fixed parameter is a valid sentinel |
| 8105 | |
| 8106 | void (*ptr) (int arg, ...) __attribute__ ((__sentinel__)); |
| 8107 | ptr(1, 2, 3, NULL); |
| 8108 | } |
| 8109 | ``` |
| 8110 | |
| 8111 | ```c++ |
| 8112 | struct Ty { |
| 8113 | int value; |
| 8114 | |
| 8115 | template<typename T> |
| 8116 | auto&& foo(T&& val, ...) __attribute__((sentinel(1))) { |
| 8117 | return std::forward<T>(val); |
| 8118 | } |
| 8119 | |
| 8120 | template<class Self> |
| 8121 | auto&& bar(this Self&& self, ...) __attribute__((sentinel(1))) { |
| 8122 | return std::forward<Self>(self).value; |
| 8123 | } |
| 8124 | }; |
| 8125 | |
| 8126 | void example2() { |
| 8127 | auto sty = Ty{}; |
| 8128 | sty.foo(1, nullptr, 3); |
| 8129 | sty.bar(1, nullptr, 3); |
| 8130 | |
| 8131 | auto lmbd = [](int a, ...) __attribute__((sentinel)) {}; |
| 8132 | lmbd(1, 2, nullptr); |
| 8133 | } |
| 8134 | ```)reST" ; |
| 8135 | |
| 8136 | static const char AttrDoc_SetTypestate[] = R"reST(Annotate methods that transition an object into a new state with |
| 8137 | `__attribute__((set_typestate(new_state)))`. The new state must be |
| 8138 | unconsumed, consumed, or unknown.)reST" ; |
| 8139 | |
| 8140 | static const char AttrDoc_SizedBy[] = R"reST(The `sized_by` attribute is applied to a pointer to indicate that the pointer |
| 8141 | points to memory containing at least the number of *bytes* given by the |
| 8142 | attribute's argument. It is closely related to `counted_by`; the difference is |
| 8143 | that `counted_by` counts the number of *elements* of the pointee type, whereas |
| 8144 | `sized_by` counts the number of *bytes*. This makes `sized_by` the natural |
| 8145 | choice for `void *` and other byte buffers. |
| 8146 | |
| 8147 | This attribute is used by {doc}`-fbounds-safety <BoundsSafety>` to propagate |
| 8148 | bounds information on API surfaces without any ABI changes. This attribute is |
| 8149 | also used to improve the results of the array bound sanitizer and the |
| 8150 | `__builtin_dynamic_object_size` builtin. |
| 8151 | |
| 8152 | The argument is an expression of integer type, following the same rules as the |
| 8153 | argument of `counted_by`. Unlike `counted_by`, `sized_by` cannot be |
| 8154 | applied to a C99 flexible array member; it applies to pointers only. For |
| 8155 | example: |
| 8156 | |
| 8157 | ```c |
| 8158 | struct object { |
| 8159 | unsigned long size; |
| 8160 | void *data __attribute__((sized_by(size))); |
| 8161 | }; |
| 8162 | ``` |
| 8163 | |
| 8164 | A pointer annotated with `sized_by` must have a size of zero when it is null. |
| 8165 | This requirement is currently only enforced when compiling with |
| 8166 | {doc}`-fbounds-safety <BoundsSafety>` (see {ref}`Current status of |
| 8167 | -fbounds-safety support in upstream Clang <bounds-safety-current-upstream-status>`). Use |
| 8168 | `sized_by_or_null` for a pointer that may be null while carrying a nonzero |
| 8169 | size. |
| 8170 | |
| 8171 | #### Keeping pointer and size in sync |
| 8172 | |
| 8173 | The `sized_by` attribute establishes a relationship between the annotated |
| 8174 | pointer and its size: the pointer must point to at least `size` bytes. |
| 8175 | Assigning to only one of them can break this relationship. |
| 8176 | Without {doc}`-fbounds-safety <BoundsSafety>`, it is the programmer's |
| 8177 | responsibility to ensure the pointer and size remain in sync. With |
| 8178 | `-fbounds-safety` it is automatically enforced. For example: |
| 8179 | |
| 8180 | ```c |
| 8181 | struct buffer { |
| 8182 | uint8_t *buf __attribute__((sized_by(size))); |
| 8183 | size_t size; |
| 8184 | }; |
| 8185 | |
| 8186 | void grow(struct buffer *b, size_t new_size) { |
| 8187 | // b->buf isn't updated. The underlying memory pointed to by b->buf might be |
| 8188 | // smaller than new_size which would contradict the sized_by attribute. |
| 8189 | // Compile error with -fbounds-safety but allowed without -fbounds-safety. |
| 8190 | b->size = new_size; |
| 8191 | } |
| 8192 | ``` |
| 8193 | |
| 8194 | Updating both together - so that `buf` points to `size` bytes - keeps |
| 8195 | the attribute true. For example: |
| 8196 | |
| 8197 | ```c |
| 8198 | void grow(struct buffer *b, size_t new_size) { |
| 8199 | // Allowed by -fbounds-safety |
| 8200 | uint8_t *new_buf = malloc(new_size); |
| 8201 | // -fbounds-safety enforces that the `new_buf` points to at least `new_size` |
| 8202 | // bytes at runtime. Without -fbounds-safety nothing enforces this. |
| 8203 | b->buf = new_buf; |
| 8204 | b->size = new_size; |
| 8205 | } |
| 8206 | ``` |
| 8207 | |
| 8208 | #### Incomplete and variable-length pointees |
| 8209 | |
| 8210 | `sized_by` is typically applied to `void *` or a pointer to a byte-sized |
| 8211 | type, but it may be used with any pointee type. Two situations call for this, |
| 8212 | both of which rule out counting fixed-size elements: |
| 8213 | |
| 8214 | First, the pointee type may be incomplete, such as an opaque type. Its element |
| 8215 | size is then unavailable, so `counted_by` cannot be used, whereas `sized_by` |
| 8216 | bounds the memory in bytes and imposes no completeness requirement. |
| 8217 | |
| 8218 | Second, the buffer may hold variable-length elements, so there is no fixed |
| 8219 | element size to count, even though the total byte size is well defined. For |
| 8220 | example, a buffer might pack together several structures that each end in a |
| 8221 | flexible array member of differing length: |
| 8222 | |
| 8223 | ```c |
| 8224 | struct var_len { |
| 8225 | int fam_size; |
| 8226 | char data[] __attribute__((counted_by(fam_size))); |
| 8227 | }; |
| 8228 | |
| 8229 | struct buffer_view { |
| 8230 | int byte_size; |
| 8231 | struct var_len *buf __attribute__((sized_by(byte_size))); |
| 8232 | }; |
| 8233 | ``` |
| 8234 | |
| 8235 | Here `counted_by` cannot be applied to `buf` because its pointee is a |
| 8236 | variable-length structure, but `sized_by` bounds the whole region in bytes; |
| 8237 | the region is traversed by advancing a byte offset rather than by indexing |
| 8238 | elements.)reST" ; |
| 8239 | |
| 8240 | static const char AttrDoc_SizedByOrNull[] = R"reST(The `sized_by_or_null` attribute is applied to a pointer to indicate that, if |
| 8241 | the pointer is non-null, it points to memory containing at least the number of |
| 8242 | *bytes* given by the attribute's argument. If the pointer is null, the value of |
| 8243 | the argument is ignored and the pointer points to zero bytes. |
| 8244 | |
| 8245 | The `sized_by_or_null` attribute is identical to `sized_by` except in how |
| 8246 | it treats null pointers. Whereas `sized_by` requires a null pointer to have a |
| 8247 | size of zero, `sized_by_or_null` allows the pointer to be null regardless of |
| 8248 | the value of the size. This supports the common idiom where a pointer is either |
| 8249 | null or points to memory containing at least the given number of bytes. |
| 8250 | |
| 8251 | Currently only {doc}`-fbounds-safety <BoundsSafety>` makes use of the |
| 8252 | distinction between `sized_by_or_null` and `sized_by` (see |
| 8253 | {ref}`Current status of -fbounds-safety support in upstream Clang |
| 8254 | <bounds-safety-current-upstream-status>`).)reST" ; |
| 8255 | |
| 8256 | static const char AttrDoc_SpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate |
| 8257 | that [Speculative Load Hardening][slh] |
| 8258 | should be enabled for the function body. This can also be applied to a method |
| 8259 | in Objective C. This attribute will take precedence over the command line flag |
| 8260 | in the case where {option}`-mno-speculative-load-hardening` is specified. |
| 8261 | |
| 8262 | [slh]: https://llvm.org/docs/SpeculativeLoadHardening.html |
| 8263 | |
| 8264 | Speculative Load Hardening is a best-effort mitigation against |
| 8265 | information leak attacks that make use of control flow |
| 8266 | miss-speculation - specifically miss-speculation of whether a branch |
| 8267 | is taken or not. Typically vulnerabilities enabling such attacks are |
| 8268 | classified as "Spectre variant #1". Notably, this does not attempt to |
| 8269 | mitigate against miss-speculation of branch target, classified as |
| 8270 | "Spectre variant #2" vulnerabilities. |
| 8271 | |
| 8272 | When inlining, the attribute is sticky. Inlining a function that |
| 8273 | carries this attribute will cause the caller to gain the |
| 8274 | attribute. This is intended to provide a maximally conservative model |
| 8275 | where the code in a function annotated with this attribute will always |
| 8276 | (even after inlining) end up hardened.)reST" ; |
| 8277 | |
| 8278 | static const char AttrDoc_StackProtectorIgnore[] = R"reST(The `stack_protector_ignore` attribute skips analysis of the given local |
| 8279 | variable when determining if a function should use a stack protector. |
| 8280 | |
| 8281 | The `-fstack-protector` option uses a heuristic to only add stack protectors |
| 8282 | to functions which contain variables or buffers over some size threshold. This |
| 8283 | attribute overrides that heuristic for the attached variable, opting |
| 8284 | them out. If this results in no variables or buffers remaining over the stack |
| 8285 | protector threshold, then the function will no longer use a stack protector.)reST" ; |
| 8286 | |
| 8287 | static const char AttrDoc_StandaloneDebug[] = R"reST(The `standalone_debug` attribute causes debug info to be emitted for a record |
| 8288 | type regardless of the debug info optimizations that are enabled with |
| 8289 | -fno-standalone-debug. This attribute only has an effect when debug info |
| 8290 | optimizations are enabled (e.g. with -fno-standalone-debug), and is C++-only.)reST" ; |
| 8291 | |
| 8292 | static const char AttrDoc_StdCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a |
| 8293 | function to clear parameters off of the stack on return. This convention does |
| 8294 | not support variadic calls or unprototyped functions in C, and has no effect on |
| 8295 | x86_64 targets. This calling convention is used widely by the Windows API and |
| 8296 | COM applications. See the documentation for [\_\_stdcall][__stdcall] on MSDN. |
| 8297 | |
| 8298 | [__stdcall]: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx)reST" ; |
| 8299 | |
| 8300 | static const char AttrDoc_StrictFP[] = R"reST()reST" ; |
| 8301 | |
| 8302 | static const char AttrDoc_StrictGuardStackCheck[] = R"reST(Clang supports the Microsoft style `__declspec((strict_gs_check))` attribute |
| 8303 | which upgrades the stack protector check from `-fstack-protector` to |
| 8304 | `-fstack-protector-strong`. |
| 8305 | |
| 8306 | For example, it upgrades the stack protector for the function `foo` to |
| 8307 | `-fstack-protector-strong` but function `bar` will still be built with the |
| 8308 | stack protector with the `-fstack-protector` option. |
| 8309 | |
| 8310 | ```c |
| 8311 | __declspec((strict_gs_check)) |
| 8312 | int foo(int x); // stack protection will be upgraded for foo. |
| 8313 | |
| 8314 | int bar(int y); // bar can be built with the standard stack protector checks. |
| 8315 | ```)reST" ; |
| 8316 | |
| 8317 | static const char AttrDoc_Suppress[] = R"reST(The `suppress` attribute suppresses unwanted warnings coming from static |
| 8318 | analysis tools such as the Clang Static Analyzer. The tool will not report |
| 8319 | any issues in source code annotated with the attribute. |
| 8320 | |
| 8321 | The attribute cannot be used to suppress traditional Clang warnings, because |
| 8322 | many such warnings are emitted before the attribute is fully parsed. |
| 8323 | Consider using `#pragma clang diagnostic` to control such diagnostics, |
| 8324 | as described in |
| 8325 | {ref}`Controlling Diagnostics via Pragmas <pragma-gcc-diagnostic>`. |
| 8326 | |
| 8327 | The `suppress` attribute can be placed on an individual statement in order to |
| 8328 | suppress warnings about undesirable behavior occurring at that statement: |
| 8329 | |
| 8330 | ```c++ |
| 8331 | int foo() { |
| 8332 | int *x = nullptr; |
| 8333 | ... |
| 8334 | [[clang::suppress]] |
| 8335 | return *x; // null pointer dereference warning suppressed here |
| 8336 | } |
| 8337 | ``` |
| 8338 | |
| 8339 | Putting the attribute on a compound statement suppresses all warnings in scope: |
| 8340 | |
| 8341 | ```c++ |
| 8342 | int foo() { |
| 8343 | [[clang::suppress]] { |
| 8344 | int *x = nullptr; |
| 8345 | ... |
| 8346 | return *x; // warnings suppressed in the entire scope |
| 8347 | } |
| 8348 | } |
| 8349 | ``` |
| 8350 | |
| 8351 | The attribute can also be placed on entire declarations of functions, classes, |
| 8352 | variables, member variables, and so on, to suppress warnings related |
| 8353 | to the declarations themselves. When used this way, the attribute additionally |
| 8354 | suppresses all warnings in the lexical scope of the declaration: |
| 8355 | |
| 8356 | ```c++ |
| 8357 | class [[clang::suppress]] C { |
| 8358 | int foo() { |
| 8359 | int *x = nullptr; |
| 8360 | ... |
| 8361 | return *x; // warnings suppressed in the entire class scope |
| 8362 | } |
| 8363 | |
| 8364 | int bar(); |
| 8365 | }; |
| 8366 | |
| 8367 | int C::bar() { |
| 8368 | int *x = nullptr; |
| 8369 | ... |
| 8370 | return *x; // warning NOT suppressed! - not lexically nested in 'class C{}' |
| 8371 | } |
| 8372 | ``` |
| 8373 | |
| 8374 | Some static analysis warnings are accompanied by one or more notes, and the |
| 8375 | line of code against which the warning is emitted isn't necessarily the best |
| 8376 | for suppression purposes. In such cases the tools are allowed to implement |
| 8377 | additional ways to suppress specific warnings based on the attribute attached |
| 8378 | to a note location. |
| 8379 | |
| 8380 | For example, the Clang Static Analyzer suppresses memory leak warnings when |
| 8381 | the suppression attribute is placed at the allocation site (highlited by |
| 8382 | a "note: memory is allocated"), which may be different from the line of code |
| 8383 | at which the program "loses track" of the pointer (where the warning |
| 8384 | is ultimately emitted): |
| 8385 | |
| 8386 | ```c |
| 8387 | int bar1(bool coin_flip) { |
| 8388 | __attribute__((suppress)) |
| 8389 | int *result = (int *)malloc(sizeof(int)); |
| 8390 | if (coin_flip) |
| 8391 | return 1; // warning about this leak path is suppressed |
| 8392 | |
| 8393 | return *result; // warning about this leak path is also suppressed |
| 8394 | } |
| 8395 | |
| 8396 | int bar2(bool coin_flip) { |
| 8397 | int *result = (int *)malloc(sizeof(int)); |
| 8398 | if (coin_flip) |
| 8399 | return 1; // leak warning on this path NOT suppressed |
| 8400 | |
| 8401 | __attribute__((suppress)) |
| 8402 | return *result; // leak warning is suppressed only on this path |
| 8403 | } |
| 8404 | ``` |
| 8405 | |
| 8406 | When written as `[[gsl::suppress]]`, this attribute suppresses specific |
| 8407 | clang-tidy diagnostics for rules of the [C++ Core Guidelines][c++ core guidelines] in a portable |
| 8408 | way. The attribute can be attached to declarations, statements, and at |
| 8409 | namespace scope. |
| 8410 | |
| 8411 | ```c++ |
| 8412 | [[gsl::suppress("Rh-public")]] |
| 8413 | void f_() { |
| 8414 | int *p; |
| 8415 | [[gsl::suppress("type")]] { |
| 8416 | p = reinterpret_cast<int*>(7); |
| 8417 | } |
| 8418 | } |
| 8419 | namespace N { |
| 8420 | [[clang::suppress("type", "bounds")]]; |
| 8421 | ... |
| 8422 | } |
| 8423 | ``` |
| 8424 | |
| 8425 | [c++ core guidelines]: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement)reST" ; |
| 8426 | |
| 8427 | static const char AttrDoc_SwiftAsync[] = R"reST(The `swift_async` attribute specifies if and how a particular function or |
| 8428 | Objective-C method is imported into a swift async method. For instance: |
| 8429 | |
| 8430 | ```objc |
| 8431 | @interface MyClass : NSObject |
| 8432 | -(void)notActuallyAsync:(int)p1 withCompletionHandler:(void (^)())handler |
| 8433 | __attribute__((swift_async(none))); |
| 8434 | |
| 8435 | -(void)actuallyAsync:(int)p1 callThisAsync:(void (^)())fun |
| 8436 | __attribute__((swift_async(swift_private, 1))); |
| 8437 | @end |
| 8438 | ``` |
| 8439 | |
| 8440 | Here, `notActuallyAsync:withCompletionHandler` would have been imported as |
| 8441 | `async` (because it's last parameter's selector piece is |
| 8442 | `withCompletionHandler`) if not for the `swift_async(none)` attribute. |
| 8443 | Conversely, `actuallyAsync:callThisAsync` wouldn't have been imported as |
| 8444 | `async` if not for the `swift_async` attribute because it doesn't match the |
| 8445 | naming convention. |
| 8446 | |
| 8447 | When using `swift_async` to enable importing, the first argument to the |
| 8448 | attribute is either `swift_private` or `not_swift_private` to indicate |
| 8449 | whether the function/method is private to the current framework, and the second |
| 8450 | argument is the index of the completion handler parameter.)reST" ; |
| 8451 | |
| 8452 | static const char AttrDoc_SwiftAsyncCall[] = R"reST(The `swiftasynccall` attribute indicates that a function is |
| 8453 | compatible with the low-level conventions of Swift async functions, |
| 8454 | provided it declares the right formal arguments. |
| 8455 | |
| 8456 | In most respects, this is similar to the `swiftcall` attribute, except for |
| 8457 | the following: |
| 8458 | |
| 8459 | - A parameter may be marked `swift_async_context`, `swift_context` |
| 8460 | or `swift_indirect_result` (with the same restrictions on parameter |
| 8461 | ordering as `swiftcall`) but the parameter attribute |
| 8462 | `swift_error_result` is not permitted. |
| 8463 | - A `swiftasynccall` function must have return type `void`. |
| 8464 | - Within a `swiftasynccall` function, a call to a `swiftasynccall` |
| 8465 | function that is the immediate operand of a `return` statement is |
| 8466 | guaranteed to be performed as a tail call. This syntax is allowed even |
| 8467 | in C as an extension (a call to a void-returning function cannot be a |
| 8468 | return operand in standard C). If something in the calling function would |
| 8469 | semantically be performed after a guaranteed tail call, such as the |
| 8470 | non-trivial destruction of a local variable or temporary, |
| 8471 | then the program is ill-formed. |
| 8472 | |
| 8473 | Query for this attribute with `__has_attribute(swiftasynccall)`. Query if |
| 8474 | the target supports the calling convention with |
| 8475 | `__has_extension(swiftasynccc)`. |
| 8476 | |
| 8477 | Since this attribute follows the Swift async calling convention, it is |
| 8478 | considered ABI-unstable except on targets where the Swift project |
| 8479 | has declared ABI stability. Users are responsible for ensuring that |
| 8480 | calls and definitions of functions with this attribute are compiled |
| 8481 | with compatible compilers. Note that different operating systems |
| 8482 | on the same architecture may use different ABIs and therefore may |
| 8483 | have different standards for ABI stability.)reST" ; |
| 8484 | |
| 8485 | static const char AttrDoc_SwiftAsyncContext[] = R"reST(The `swift_async_context` attribute marks a parameter of a `swiftasynccall` |
| 8486 | function as having the special asynchronous context-parameter ABI treatment. |
| 8487 | |
| 8488 | If the function is not `swiftasynccall`, this attribute only generates |
| 8489 | extended frame information. |
| 8490 | |
| 8491 | A context parameter must have pointer or reference type.)reST" ; |
| 8492 | |
| 8493 | static const char AttrDoc_SwiftAsyncError[] = R"reST(The `swift_async_error` attribute specifies how an error state will be |
| 8494 | represented in a swift async method. It's a bit analogous to the `swift_error` |
| 8495 | attribute for the generated async method. The `swift_async_error` attribute |
| 8496 | can indicate a variety of different ways of representing an error. |
| 8497 | |
| 8498 | - `__attribute__((swift_async_error(zero_argument, N)))`, specifies that the |
| 8499 | async method is considered to have failed if the Nth argument to the |
| 8500 | completion handler is zero. |
| 8501 | - `__attribute__((swift_async_error(nonzero_argument, N)))`, specifies that |
| 8502 | the async method is considered to have failed if the Nth argument to the |
| 8503 | completion handler is non-zero. |
| 8504 | - `__attribute__((swift_async_error(nonnull_error)))`, specifies that the |
| 8505 | async method is considered to have failed if the `NSError *` argument to the |
| 8506 | completion handler is non-null. |
| 8507 | - `__attribute__((swift_async_error(none)))`, specifies that the async method |
| 8508 | cannot fail. |
| 8509 | |
| 8510 | For instance: |
| 8511 | |
| 8512 | ```objc |
| 8513 | @interface MyClass : NSObject |
| 8514 | -(void)asyncMethod:(void (^)(char, int, float))handler |
| 8515 | __attribute__((swift_async(swift_private, 1))) |
| 8516 | __attribute__((swift_async_error(zero_argument, 2))); |
| 8517 | @end |
| 8518 | ``` |
| 8519 | |
| 8520 | Here, the `swift_async` attribute specifies that `handler` is the completion |
| 8521 | handler for this method, and the `swift_async_error` attribute specifies that |
| 8522 | the `int` parameter is the one that represents the error.)reST" ; |
| 8523 | |
| 8524 | static const char AttrDoc_SwiftAsyncName[] = R"reST(The `swift_async_name` attribute provides the name of the `async` overload for |
| 8525 | the given declaration in Swift. If this attribute is absent, the name is |
| 8526 | transformed according to the algorithm built into the Swift compiler. |
| 8527 | |
| 8528 | The argument is a string literal that contains the Swift name of the function or |
| 8529 | method. The name may be a compound Swift name. The function or method with such |
| 8530 | an attribute must have more than zero parameters, as its last parameter is |
| 8531 | assumed to be a callback that's eliminated in the Swift `async` name. |
| 8532 | |
| 8533 | ```objc |
| 8534 | @interface URL |
| 8535 | + (void) loadContentsFrom:(URL *)url callback:(void (^)(NSData *))data __attribute__((__swift_async_name__("URL.loadContentsFrom(_:)"))) |
| 8536 | @end |
| 8537 | ```)reST" ; |
| 8538 | |
| 8539 | static const char AttrDoc_SwiftAttr[] = R"reST(The `swift_attr` provides a Swift-specific annotation for the declaration |
| 8540 | or type to which the attribute appertains to. It can be used on any declaration |
| 8541 | or type in Clang. This kind of annotation is ignored by Clang as it doesn't have any |
| 8542 | semantic meaning in languages supported by Clang. The Swift compiler can |
| 8543 | interpret these annotations according to its own rules when importing C or |
| 8544 | Objective-C declarations.)reST" ; |
| 8545 | |
| 8546 | static const char AttrDoc_SwiftBridge[] = R"reST(The `swift_bridge` attribute indicates that the declaration to which the |
| 8547 | attribute appertains is bridged to the named Swift type. |
| 8548 | |
| 8549 | ```objc |
| 8550 | __attribute__((__objc_root__)) |
| 8551 | @interface Base |
| 8552 | - (instancetype)init; |
| 8553 | @end |
| 8554 | |
| 8555 | __attribute__((__swift_bridge__("BridgedI"))) |
| 8556 | @interface I : Base |
| 8557 | @end |
| 8558 | ``` |
| 8559 | |
| 8560 | In this example, the Objective-C interface `I` will be made available to Swift |
| 8561 | with the name `BridgedI`. It would be possible for the compiler to refer to |
| 8562 | `I` still in order to bridge the type back to Objective-C.)reST" ; |
| 8563 | |
| 8564 | static const char AttrDoc_SwiftBridgedTypedef[] = R"reST(The `swift_bridged_typedef` attribute indicates that when the typedef to which |
| 8565 | the attribute appertains is imported into Swift, it should refer to the bridged |
| 8566 | Swift type (e.g. Swift's `String`) rather than the Objective-C type as written |
| 8567 | (e.g. `NSString`). |
| 8568 | |
| 8569 | ```objc |
| 8570 | @interface NSString; |
| 8571 | typedef NSString *AliasedString __attribute__((__swift_bridged_typedef__)); |
| 8572 | |
| 8573 | extern void acceptsAliasedString(AliasedString _Nonnull parameter); |
| 8574 | ``` |
| 8575 | |
| 8576 | In this case, the function `acceptsAliasedString` will be imported into Swift |
| 8577 | as a function which accepts a `String` type parameter.)reST" ; |
| 8578 | |
| 8579 | static const char AttrDoc_SwiftCall[] = R"reST(The `swiftcall` attribute indicates that a function should be called |
| 8580 | using the Swift calling convention for a function or function pointer. |
| 8581 | |
| 8582 | The lowering for the Swift calling convention, as described by the Swift |
| 8583 | ABI documentation, occurs in multiple phases. The first, "high-level" |
| 8584 | phase breaks down the formal parameters and results into innately direct |
| 8585 | and indirect components, adds implicit parameters for the generic |
| 8586 | signature, and assigns the context and error ABI treatments to parameters |
| 8587 | where applicable. The second phase breaks down the direct parameters |
| 8588 | and results from the first phase and assigns them to registers or the |
| 8589 | stack. The `swiftcall` convention only handles this second phase of |
| 8590 | lowering; the C function type must accurately reflect the results |
| 8591 | of the first phase, as follows: |
| 8592 | |
| 8593 | - Results classified as indirect by high-level lowering should be |
| 8594 | represented as parameters with the `swift_indirect_result` attribute. |
| 8595 | |
| 8596 | - Results classified as direct by high-level lowering should be represented |
| 8597 | as follows: |
| 8598 | |
| 8599 | - First, remove any empty direct results. |
| 8600 | - If there are no direct results, the C result type should be `void`. |
| 8601 | - If there is one direct result, the C result type should be a type with |
| 8602 | the exact layout of that result type. |
| 8603 | - If there are a multiple direct results, the C result type should be |
| 8604 | a struct type with the exact layout of a tuple of those results. |
| 8605 | |
| 8606 | - Parameters classified as indirect by high-level lowering should be |
| 8607 | represented as parameters of pointer type. |
| 8608 | |
| 8609 | - Parameters classified as direct by high-level lowering should be |
| 8610 | omitted if they are empty types; otherwise, they should be represented |
| 8611 | as a parameter type with a layout exactly matching the layout of the |
| 8612 | Swift parameter type. |
| 8613 | |
| 8614 | - The context parameter, if present, should be represented as a trailing |
| 8615 | parameter with the `swift_context` attribute. |
| 8616 | |
| 8617 | - The error result parameter, if present, should be represented as a |
| 8618 | trailing parameter (always following a context parameter) with the |
| 8619 | `swift_error_result` attribute. |
| 8620 | |
| 8621 | `swiftcall` does not support variadic arguments or unprototyped functions. |
| 8622 | |
| 8623 | The parameter ABI treatment attributes are aspects of the function type. |
| 8624 | A function type which applies an ABI treatment attribute to a |
| 8625 | parameter is a different type from an otherwise-identical function type |
| 8626 | that does not. A single parameter may not have multiple ABI treatment |
| 8627 | attributes. |
| 8628 | |
| 8629 | Support for this feature is target-dependent, although it should be |
| 8630 | supported on every target that Swift supports. Query for this attribute |
| 8631 | with `__has_attribute(swiftcall)`. Query if the target supports the |
| 8632 | calling convention with `__has_extension(swiftcc)`. This implies |
| 8633 | support for the `swift_context`, `swift_error_result`, and |
| 8634 | `swift_indirect_result` attributes. |
| 8635 | |
| 8636 | Since this attribute follows the Swift calling convention, it is |
| 8637 | considered ABI-unstable except on targets where the Swift project |
| 8638 | has declared ABI stability. Users are responsible for ensuring that |
| 8639 | calls and definitions of functions with this attribute are compiled |
| 8640 | with compatible compilers. Note that different operating systems |
| 8641 | on the same architecture may use different ABIs and therefore may |
| 8642 | have different standards for ABI stability.)reST" ; |
| 8643 | |
| 8644 | static const char AttrDoc_SwiftContext[] = R"reST(The `swift_context` attribute marks a parameter of a `swiftcall` |
| 8645 | or `swiftasynccall` function as having the special context-parameter |
| 8646 | ABI treatment. |
| 8647 | |
| 8648 | This treatment generally passes the context value in a special register |
| 8649 | which is normally callee-preserved. |
| 8650 | |
| 8651 | A `swift_context` parameter must either be the last parameter or must be |
| 8652 | followed by a `swift_error_result` parameter (which itself must always be |
| 8653 | the last parameter). |
| 8654 | |
| 8655 | A context parameter must have pointer or reference type.)reST" ; |
| 8656 | |
| 8657 | static const char AttrDoc_SwiftError[] = R"reST(The `swift_error` attribute controls whether a particular function (or |
| 8658 | Objective-C method) is imported into Swift as a throwing function, and if so, |
| 8659 | which dynamic convention it uses. |
| 8660 | |
| 8661 | All of these conventions except `none` require the function to have an error |
| 8662 | parameter. Currently, the error parameter is always the last parameter of type |
| 8663 | `NSError**` or `CFErrorRef*`. Swift will remove the error parameter from |
| 8664 | the imported API. When calling the API, Swift will always pass a valid address |
| 8665 | initialized to a null pointer. |
| 8666 | |
| 8667 | - `swift_error(none)` means that the function should not be imported as |
| 8668 | throwing. The error parameter and result type will be imported normally. |
| 8669 | - `swift_error(null_result)` means that calls to the function should be |
| 8670 | considered to have thrown if they return a null value. The return type must be |
| 8671 | a pointer type, and it will be imported into Swift with a non-optional type. |
| 8672 | This is the default error convention for Objective-C methods that return |
| 8673 | pointers. |
| 8674 | - `swift_error(zero_result)` means that calls to the function should be |
| 8675 | considered to have thrown if they return a zero result. The return type must be |
| 8676 | an integral type. If the return type would have been imported as `Bool`, it |
| 8677 | is instead imported as `Void`. This is the default error convention for |
| 8678 | Objective-C methods that return a type that would be imported as `Bool`. |
| 8679 | - `swift_error(nonzero_result)` means that calls to the function should be |
| 8680 | considered to have thrown if they return a non-zero result. The return type must |
| 8681 | be an integral type. If the return type would have been imported as `Bool`, |
| 8682 | it is instead imported as `Void`. |
| 8683 | - `swift_error(nonnull_error)` means that calls to the function should be |
| 8684 | considered to have thrown if they leave a non-null error in the error parameter. |
| 8685 | The return type is left unmodified.)reST" ; |
| 8686 | |
| 8687 | static const char AttrDoc_SwiftErrorResult[] = R"reST(The `swift_error_result` attribute marks a parameter of a `swiftcall` |
| 8688 | function as having the special error-result ABI treatment. |
| 8689 | |
| 8690 | This treatment generally passes the underlying error value in and out of |
| 8691 | the function through a special register which is normally callee-preserved. |
| 8692 | This is modeled in C by pretending that the register is addressable memory: |
| 8693 | |
| 8694 | - The caller appears to pass the address of a variable of pointer type. |
| 8695 | The current value of this variable is copied into the register before |
| 8696 | the call; if the call returns normally, the value is copied back into the |
| 8697 | variable. |
| 8698 | - The callee appears to receive the address of a variable. This address |
| 8699 | is actually a hidden location in its own stack, initialized with the |
| 8700 | value of the register upon entry. When the function returns normally, |
| 8701 | the value in that hidden location is written back to the register. |
| 8702 | |
| 8703 | A `swift_error_result` parameter must be the last parameter, and it must be |
| 8704 | preceded by a `swift_context` parameter. |
| 8705 | |
| 8706 | A `swift_error_result` parameter must have type `T**` or `T*&` for some |
| 8707 | type T. Note that no qualifiers are permitted on the intermediate level. |
| 8708 | |
| 8709 | It is undefined behavior if the caller does not pass a pointer or |
| 8710 | reference to a valid object. |
| 8711 | |
| 8712 | The standard convention is that the error value itself (that is, the |
| 8713 | value stored in the apparent argument) will be null upon function entry, |
| 8714 | but this is not enforced by the ABI.)reST" ; |
| 8715 | |
| 8716 | static const char AttrDoc_SwiftImportAsNonGeneric[] = R"reST()reST" ; |
| 8717 | |
| 8718 | static const char AttrDoc_SwiftImportPropertyAsAccessors[] = R"reST()reST" ; |
| 8719 | |
| 8720 | static const char AttrDoc_SwiftIndirectResult[] = R"reST(The `swift_indirect_result` attribute marks a parameter of a `swiftcall` |
| 8721 | or `swiftasynccall` function as having the special indirect-result ABI |
| 8722 | treatment. |
| 8723 | |
| 8724 | This treatment gives the parameter the target's normal indirect-result |
| 8725 | ABI treatment, which may involve passing it differently from an ordinary |
| 8726 | parameter. However, only the first indirect result will receive this |
| 8727 | treatment. Furthermore, low-level lowering may decide that a direct result |
| 8728 | must be returned indirectly; if so, this will take priority over the |
| 8729 | `swift_indirect_result` parameters. |
| 8730 | |
| 8731 | A `swift_indirect_result` parameter must either be the first parameter or |
| 8732 | follow another `swift_indirect_result` parameter. |
| 8733 | |
| 8734 | A `swift_indirect_result` parameter must have type `T*` or `T&` for |
| 8735 | some object type `T`. If `T` is a complete type at the point of |
| 8736 | definition of a function, it is undefined behavior if the argument |
| 8737 | value does not point to storage of adequate size and alignment for a |
| 8738 | value of type `T`. |
| 8739 | |
| 8740 | Making indirect results explicit in the signature allows C functions to |
| 8741 | directly construct objects into them without relying on language |
| 8742 | optimizations like C++'s named return value optimization (NRVO).)reST" ; |
| 8743 | |
| 8744 | static const char AttrDoc_SwiftName[] = R"reST(The `swift_name` attribute provides the name of the declaration in Swift. If |
| 8745 | this attribute is absent, the name is transformed according to the algorithm |
| 8746 | built into the Swift compiler. |
| 8747 | |
| 8748 | The argument is a string literal that contains the Swift name of the function, |
| 8749 | variable, or type. When renaming a function, the name may be a compound Swift |
| 8750 | name. For a type, enum constant, property, or variable declaration, the name |
| 8751 | must be a simple or qualified identifier. |
| 8752 | |
| 8753 | ```objc |
| 8754 | @interface URL |
| 8755 | - (void) initWithString:(NSString *)s __attribute__((__swift_name__("URL.init(_:)"))) |
| 8756 | @end |
| 8757 | |
| 8758 | void __attribute__((__swift_name__("squareRoot()"))) sqrt(double v) { |
| 8759 | } |
| 8760 | ```)reST" ; |
| 8761 | |
| 8762 | static const char AttrDoc_SwiftNewType[] = R"reST(The `swift_newtype` attribute indicates that the typedef to which the |
| 8763 | attribute appertains is imported as a new Swift type of the typedef's name. |
| 8764 | Previously, the attribute was spelt `swift_wrapper`. While the behaviour of |
| 8765 | the attribute is identical with either spelling, `swift_wrapper` is |
| 8766 | deprecated, only exists for compatibility purposes, and should not be used in |
| 8767 | new code. |
| 8768 | |
| 8769 | - `swift_newtype(struct)` means that a Swift struct will be created for this |
| 8770 | typedef. |
| 8771 | |
| 8772 | - `swift_newtype(enum)` means that a Swift enum will be created for this |
| 8773 | typedef. |
| 8774 | |
| 8775 | ```c |
| 8776 | // Import UIFontTextStyle as an enum type, with enumerated values being |
| 8777 | // constants. |
| 8778 | typedef NSString * UIFontTextStyle __attribute__((__swift_newtype__(enum))); |
| 8779 | |
| 8780 | // Import UIFontDescriptorFeatureKey as a structure type, with enumerated |
| 8781 | // values being members of the type structure. |
| 8782 | typedef NSString * UIFontDescriptorFeatureKey __attribute__((__swift_newtype__(struct))); |
| 8783 | ```)reST" ; |
| 8784 | |
| 8785 | static const char AttrDoc_SwiftNullability[] = R"reST()reST" ; |
| 8786 | |
| 8787 | static const char AttrDoc_SwiftObjCMembers[] = R"reST(This attribute indicates that Swift subclasses and members of Swift extensions |
| 8788 | of this class will be implicitly marked with the `@objcMembers` Swift |
| 8789 | attribute, exposing them back to Objective-C.)reST" ; |
| 8790 | |
| 8791 | static const char AttrDoc_SwiftPrivate[] = R"reST(Declarations marked with the `swift_private` attribute are hidden from the |
| 8792 | framework client but are still made available for use within the framework or |
| 8793 | Swift SDK overlay. |
| 8794 | |
| 8795 | The purpose of this attribute is to permit a more idomatic implementation of |
| 8796 | declarations in Swift while hiding the non-idiomatic one.)reST" ; |
| 8797 | |
| 8798 | static const char AttrDoc_SwiftType[] = R"reST()reST" ; |
| 8799 | |
| 8800 | static const char AttrDoc_SwiftVersionedAddition[] = R"reST()reST" ; |
| 8801 | |
| 8802 | static const char AttrDoc_SwiftVersionedRemoval[] = R"reST()reST" ; |
| 8803 | |
| 8804 | static const char AttrDoc_SysVABI[] = R"reST(On Windows x86_64 targets, this attribute changes the calling convention of a |
| 8805 | function to match the default convention used on Sys V targets such as Linux, |
| 8806 | Mac, and BSD. This attribute has no effect on other targets.)reST" ; |
| 8807 | |
| 8808 | static const char AttrDoc_TLSModel[] = R"reST(The `tls_model` attribute allows you to specify which thread-local storage |
| 8809 | model to use. It accepts the following strings: |
| 8810 | |
| 8811 | - global-dynamic |
| 8812 | - local-dynamic |
| 8813 | - initial-exec |
| 8814 | - local-exec |
| 8815 | |
| 8816 | TLS models are mutually exclusive.)reST" ; |
| 8817 | |
| 8818 | static const char AttrDoc_Target[] = R"reST(Clang supports the GNU style `__attribute__((target("OPTIONS")))` attribute. |
| 8819 | This attribute may be attached to a function definition and instructs |
| 8820 | the backend to use different code generation options than were passed on the |
| 8821 | command line. |
| 8822 | |
| 8823 | The current set of options correspond to the existing "subtarget features" for |
| 8824 | the target with or without a "-mno-" in front corresponding to the absence |
| 8825 | of the feature, as well as `arch="CPU"` which will change the default "CPU" |
| 8826 | for the function. |
| 8827 | |
| 8828 | For X86, the attribute also allows `tune="CPU"` to optimize the generated |
| 8829 | code for the given CPU without changing the available instructions. |
| 8830 | |
| 8831 | For AArch64, `arch="Arch"` will set the architecture, similar to the -march |
| 8832 | command line options. `cpu="CPU"` can be used to select a specific cpu, |
| 8833 | as per the `-mcpu` option, similarly for `tune=`. The attribute also allows the |
| 8834 | "branch-protection=\<args>" option, where the permissible arguments and their |
| 8835 | effect on code generation are the same as for the command-line option |
| 8836 | `-mbranch-protection`. |
| 8837 | |
| 8838 | Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2", |
| 8839 | "avx", "xop" and largely correspond to the machine specific options handled by |
| 8840 | the front end. |
| 8841 | |
| 8842 | Note that this attribute does not apply transitively to nested functions such |
| 8843 | as blocks or C++ lambdas. |
| 8844 | |
| 8845 | Additionally, this attribute supports function multiversioning for ELF based |
| 8846 | x86/x86-64 targets, which can be used to create multiple implementations of the |
| 8847 | same function that will be resolved at runtime based on the priority of their |
| 8848 | `target` attribute strings. A function is considered a multiversioned function |
| 8849 | if either two declarations of the function have different `target` attribute |
| 8850 | strings, or if it has a `target` attribute string of `default`. For |
| 8851 | example: |
| 8852 | |
| 8853 | ```c++ |
| 8854 | __attribute__((target("arch=atom"))) |
| 8855 | void foo() {} // will be called on 'atom' processors. |
| 8856 | __attribute__((target("default"))) |
| 8857 | void foo() {} // will be called on any other processors. |
| 8858 | ``` |
| 8859 | |
| 8860 | All multiversioned functions must contain a `default` (fallback) |
| 8861 | implementation, otherwise usages of the function are considered invalid. |
| 8862 | Additionally, a function may not become multiversioned after its first use.)reST" ; |
| 8863 | |
| 8864 | static const char AttrDoc_TargetClones[] = R"reST(Clang supports the `target_clones("OPTIONS")` attribute. This attribute may be |
| 8865 | attached to a function declaration and causes function multiversioning, where |
| 8866 | multiple versions of the function will be emitted with different code |
| 8867 | generation options. Additionally, these versions will be resolved at runtime |
| 8868 | based on the priority of their attribute options. All `target_clone` functions |
| 8869 | are considered multiversioned functions. |
| 8870 | |
| 8871 | For AArch64 target: |
| 8872 | The attribute contains comma-separated strings of target features joined by "+" |
| 8873 | sign. For example: |
| 8874 | |
| 8875 | ```c++ |
| 8876 | __attribute__((target_clones("sha2+memtag", "fcma+sve2-pmull128"))) |
| 8877 | void foo() {} |
| 8878 | ``` |
| 8879 | |
| 8880 | For every multiversioned function a `default` (fallback) implementation |
| 8881 | always generated if not specified directly. |
| 8882 | |
| 8883 | For x86/x86-64 targets: |
| 8884 | All multiversioned functions must contain a `default` (fallback) |
| 8885 | implementation, otherwise usages of the function are considered invalid. |
| 8886 | Additionally, a function may not become multiversioned after its first use. |
| 8887 | |
| 8888 | The options to `target_clones` can either be a target-specific architecture |
| 8889 | (specified as `arch=CPU`), or one of a list of subtarget features. |
| 8890 | |
| 8891 | Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2", |
| 8892 | "avx", "xop" and largely correspond to the machine specific options handled by |
| 8893 | the front end. |
| 8894 | |
| 8895 | The versions can either be listed as a comma-separated sequence of string |
| 8896 | literals or as a single string literal containing a comma-separated list of |
| 8897 | versions. For compatibility with GCC, the two formats can be mixed. For |
| 8898 | example, the following will emit 4 versions of the function: |
| 8899 | |
| 8900 | ```c++ |
| 8901 | __attribute__((target_clones("arch=atom,avx2","arch=ivybridge","default"))) |
| 8902 | void foo() {} |
| 8903 | ``` |
| 8904 | |
| 8905 | For targets that support the GNU indirect function (IFUNC) feature, dispatch |
| 8906 | is performed by emitting an indirect function that is resolved to the appropriate |
| 8907 | target clone at load time. The indirect function is given the name the |
| 8908 | multiversioned function would have if it had been declared without the attribute. |
| 8909 | For backward compatibility with earlier Clang releases, a function alias with an |
| 8910 | `.ifunc` suffix is also emitted. The `.ifunc` suffixed symbol is a deprecated |
| 8911 | feature and support for it may be removed in the future. |
| 8912 | |
| 8913 | For PowerPC targets, `target_clones` is supported on AIX only. Only CPU |
| 8914 | (specified as `cpu=CPU`) and `default` options are allowed. IFUNC is supported |
| 8915 | on AIX in Clang, so dispatch is implemented similar to other targets using IFUNC. |
| 8916 | An FMV function that is only declared in a translation unit is treated as a |
| 8917 | non-FMV. The resolver and the function clones are given internal linkage.)reST" ; |
| 8918 | |
| 8919 | static const char AttrDoc_TargetVersion[] = R"reST(For AArch64 target clang supports function multiversioning by |
| 8920 | `__attribute__((target_version("OPTIONS")))` attribute. When applied to a |
| 8921 | function it instructs compiler to emit multiple function versions based on |
| 8922 | `target_version` attribute strings, which resolved at runtime depend on their |
| 8923 | priority and target features availability. One of the versions is always |
| 8924 | ( implicitly or explicitly ) the `default` (fallback). Attribute strings can |
| 8925 | contain dependent features names joined by the "+" sign. |
| 8926 | |
| 8927 | For targets that support the GNU indirect function (IFUNC) feature, dispatch |
| 8928 | is performed by emitting an indirect function that is resolved to the appropriate |
| 8929 | target clone at load time. The indirect function is given the name the |
| 8930 | multiversioned function would have if it had been declared without the attribute. |
| 8931 | For backward compatibility with earlier Clang releases, a function alias with an |
| 8932 | `.ifunc` suffix is also emitted. The `.ifunc` suffixed symbol is a deprecated |
| 8933 | feature and support for it may be removed in the future.)reST" ; |
| 8934 | |
| 8935 | static const char AttrDoc_TestTypestate[] = R"reST(Use `__attribute__((test_typestate(tested_state)))` to indicate that a method |
| 8936 | returns true if the object is in the specified state..)reST" ; |
| 8937 | |
| 8938 | static const char AttrDoc_ThisCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a |
| 8939 | function to use ECX for the first parameter (typically the implicit `this` |
| 8940 | parameter of C++ methods) and clear parameters off of the stack on return. This |
| 8941 | convention does not support variadic calls or unprototyped functions in C, and |
| 8942 | has no effect on x86_64 targets. See the documentation for [\_\_thiscall][__thiscall] on |
| 8943 | MSDN. |
| 8944 | |
| 8945 | [__thiscall]: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx)reST" ; |
| 8946 | |
| 8947 | static const char AttrDoc_Thread[] = R"reST(The `__declspec(thread)` attribute declares a variable with thread local |
| 8948 | storage. It is available under the `-fms-extensions` flag for MSVC |
| 8949 | compatibility. See the documentation for [\_\_declspec(thread)][__declspec(thread)] on MSDN. |
| 8950 | |
| 8951 | In Clang, `__declspec(thread)` is generally equivalent in functionality to the |
| 8952 | GNU `__thread` keyword. The variable must not have a destructor and must have |
| 8953 | a constant initializer, if any. The attribute only applies to variables |
| 8954 | declared with static storage duration, such as globals, class static data |
| 8955 | members, and static locals. |
| 8956 | |
| 8957 | [__declspec(thread)]: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx)reST" ; |
| 8958 | |
| 8959 | static const char AttrDoc_TransparentUnion[] = R"reST(This attribute can be applied to a union to change the behavior of calls to |
| 8960 | functions that have an argument with a transparent union type. The compiler |
| 8961 | behavior is changed in the following manner: |
| 8962 | |
| 8963 | - A value whose type is any member of the transparent union can be passed as an |
| 8964 | argument without the need to cast that value. |
| 8965 | - The argument is passed to the function using the calling convention of the |
| 8966 | first member of the transparent union. Consequently, all the members of the |
| 8967 | transparent union should have the same calling convention as its first member. |
| 8968 | |
| 8969 | Transparent unions are not supported in C++.)reST" ; |
| 8970 | |
| 8971 | static const char AttrDoc_TrivialABI[] = R"reST(The `trivial_abi` attribute can be applied to a C++ class, struct, or union. |
| 8972 | It instructs the compiler to pass and return the type using the C ABI for the |
| 8973 | underlying type when the type would otherwise be considered non-trivial for the |
| 8974 | purpose of calls. |
| 8975 | A class annotated with `trivial_abi` can have non-trivial destructors or |
| 8976 | copy/move constructors without automatically becoming non-trivial for the |
| 8977 | purposes of calls. For example: |
| 8978 | |
| 8979 | ```c++ |
| 8980 | // A is trivial for the purposes of calls because `trivial_abi` makes the |
| 8981 | // user-provided special functions trivial. |
| 8982 | struct __attribute__((trivial_abi)) A { |
| 8983 | ~A(); |
| 8984 | A(const A &); |
| 8985 | A(A &&); |
| 8986 | int x; |
| 8987 | }; |
| 8988 | |
| 8989 | // B's destructor and copy/move constructor are considered trivial for the |
| 8990 | // purpose of calls because A is trivial. |
| 8991 | struct B { |
| 8992 | A a; |
| 8993 | }; |
| 8994 | ``` |
| 8995 | |
| 8996 | If a type is trivial for the purposes of calls, has a non-trivial destructor, |
| 8997 | and is passed as an argument by value, the convention is that the callee will |
| 8998 | destroy the object before returning. The lifetime of the copy of the parameter |
| 8999 | in the caller ends without a destructor call when the call begins. |
| 9000 | |
| 9001 | If a type is trivial for the purpose of calls, it is assumed to be trivially |
| 9002 | relocatable for the purpose of `__is_trivially_relocatable` and |
| 9003 | `__builtin_is_cpp_trivially_relocatable`. |
| 9004 | When a type marked with `[[trivial_abi]]` is used as a function argument, |
| 9005 | the compiler may omit the call to the copy constructor. |
| 9006 | Thus, side effects of the copy constructor are potentially not performed. |
| 9007 | For example, objects that contain pointers to themselves or otherwise depend |
| 9008 | on their address (or the address or their subobjects) should not be declared |
| 9009 | `[[trivial_abi]]`. |
| 9010 | |
| 9011 | Attribute `trivial_abi` has no effect in the following cases: |
| 9012 | |
| 9013 | - The class directly declares a virtual base or virtual methods. |
| 9014 | |
| 9015 | - Copy constructors and move constructors of the class are all deleted. |
| 9016 | |
| 9017 | - The class has a base class that is non-trivial for the purposes of calls. |
| 9018 | |
| 9019 | - The class has a non-static data member whose type is non-trivial for the |
| 9020 | purposes of calls, which includes: |
| 9021 | |
| 9022 | - classes that are non-trivial for the purposes of calls |
| 9023 | - \_\_weak-qualified types in Objective-C++ |
| 9024 | - arrays of any of the above)reST" ; |
| 9025 | |
| 9026 | static const char AttrDoc_TryAcquireCapability[] = R"reST(Marks a function that attempts to acquire a capability. This function may fail to |
| 9027 | actually acquire the capability; they accept a Boolean value determining |
| 9028 | whether acquiring the capability means success (true), or failing to acquire |
| 9029 | the capability means success (false).)reST" ; |
| 9030 | |
| 9031 | static const char AttrDoc_TypeNonNull[] = R"reST(The `_Nonnull` nullability qualifier indicates that null is not a meaningful |
| 9032 | value for a value of the `_Nonnull` pointer type. For example, given a |
| 9033 | declaration such as: |
| 9034 | |
| 9035 | ```c |
| 9036 | int fetch(int * _Nonnull ptr); |
| 9037 | ``` |
| 9038 | |
| 9039 | a caller of `fetch` should not provide a null value, and the compiler will |
| 9040 | produce a warning if it sees a literal null value passed to `fetch`. Note |
| 9041 | that, unlike the declaration attribute `nonnull`, the presence of |
| 9042 | `_Nonnull` does not imply that passing null is undefined behavior: `fetch` |
| 9043 | is free to consider null undefined behavior or (perhaps for |
| 9044 | backward-compatibility reasons) defensively handle null.)reST" ; |
| 9045 | |
| 9046 | static const char AttrDoc_TypeNullUnspecified[] = R"reST(The `_Null_unspecified` nullability qualifier indicates that neither the |
| 9047 | `_Nonnull` nor `_Nullable` qualifiers make sense for a particular pointer |
| 9048 | type. It is used primarily to indicate that the role of null with specific |
| 9049 | pointers in a nullability-annotated header is unclear, e.g., due to |
| 9050 | overly-complex implementations or historical factors with a long-lived API.)reST" ; |
| 9051 | |
| 9052 | static const char AttrDoc_TypeNullable[] = R"reST(The `_Nullable` nullability qualifier indicates that a value of the |
| 9053 | `_Nullable` pointer type can be null. For example, given: |
| 9054 | |
| 9055 | ```c |
| 9056 | int fetch_or_zero(int * _Nullable ptr); |
| 9057 | ``` |
| 9058 | |
| 9059 | a caller of `fetch_or_zero` can provide null. |
| 9060 | |
| 9061 | The `_Nullable` attribute on classes indicates that the given class can |
| 9062 | represent null values, and so the `_Nullable`, `_Nonnull` etc qualifiers |
| 9063 | make sense for this type. For example: |
| 9064 | |
| 9065 | ```c |
| 9066 | class _Nullable ArenaPointer { ... }; |
| 9067 | |
| 9068 | ArenaPointer _Nonnull x = ...; |
| 9069 | ArenaPointer _Nullable y = nullptr; |
| 9070 | ```)reST" ; |
| 9071 | |
| 9072 | static const char AttrDoc_TypeNullableResult[] = R"reST(The `_Nullable_result` nullability qualifier means that a value of the |
| 9073 | `_Nullable_result` pointer can be `nil`, just like `_Nullable`. Where this |
| 9074 | attribute differs from `_Nullable` is when it's used on a parameter to a |
| 9075 | completion handler in a Swift async method. For instance, here: |
| 9076 | |
| 9077 | ```objc |
| 9078 | -(void)fetchSomeDataWithID:(int)identifier |
| 9079 | completionHandler:(void (^)(Data *_Nullable_result result, NSError *error))completionHandler; |
| 9080 | ``` |
| 9081 | |
| 9082 | This method asynchronously calls `completionHandler` when the data is |
| 9083 | available, or calls it with an error. `_Nullable_result` indicates to the |
| 9084 | Swift importer that this is the uncommon case where `result` can get `nil` |
| 9085 | even if no error has occurred, and will therefore import it as a Swift optional |
| 9086 | type. Otherwise, if `result` was annotated with `_Nullable`, the Swift |
| 9087 | importer will assume that `result` will always be non-nil unless an error |
| 9088 | occurred.)reST" ; |
| 9089 | |
| 9090 | static const char AttrDoc_TypeTagForDatatype[] = R"reST(When declaring a variable, use |
| 9091 | `__attribute__((type_tag_for_datatype(kind, type)))` to create a type tag that |
| 9092 | is tied to the `type` argument given to the attribute. |
| 9093 | |
| 9094 | In the attribute prototype above: |
| 9095 | : - `kind` is an identifier that should be used when annotating all applicable |
| 9096 | type tags. |
| 9097 | - `type` indicates the name of the type. |
| 9098 | |
| 9099 | Clang supports annotating type tags of two forms. |
| 9100 | |
| 9101 | - **Type tag that is a reference to a declared identifier.** |
| 9102 | Use `__attribute__((type_tag_for_datatype(kind, type)))` when declaring that |
| 9103 | identifier: |
| 9104 | |
| 9105 | ```c++ |
| 9106 | typedef int MPI_Datatype; |
| 9107 | extern struct mpi_datatype mpi_datatype_int |
| 9108 | __attribute__(( type_tag_for_datatype(mpi,int) )); |
| 9109 | #define MPI_INT ((MPI_Datatype) &mpi_datatype_int) |
| 9110 | // &mpi_datatype_int is a type tag. It is tied to type "int". |
| 9111 | ``` |
| 9112 | |
| 9113 | - **Type tag that is an integral literal.** |
| 9114 | Declare a `static const` variable with an initializer value and attach |
| 9115 | `__attribute__((type_tag_for_datatype(kind, type)))` on that declaration: |
| 9116 | |
| 9117 | ```c++ |
| 9118 | typedef int MPI_Datatype; |
| 9119 | static const MPI_Datatype mpi_datatype_int |
| 9120 | __attribute__(( type_tag_for_datatype(mpi,int) )) = 42; |
| 9121 | #define MPI_INT ((MPI_Datatype) 42) |
| 9122 | // The number 42 is a type tag. It is tied to type "int". |
| 9123 | ``` |
| 9124 | |
| 9125 | The `type_tag_for_datatype` attribute also accepts an optional third argument |
| 9126 | that determines how the type of the function argument specified by either |
| 9127 | `arg_idx` or `ptr_idx` is compared against the type associated with the type |
| 9128 | tag. (Recall that for the `argument_with_type_tag` attribute, the type of the |
| 9129 | function argument specified by `arg_idx` is compared against the type |
| 9130 | associated with the type tag. Also recall that for the `pointer_with_type_tag` |
| 9131 | attribute, the pointee type of the function argument specified by `ptr_idx` is |
| 9132 | compared against the type associated with the type tag.) There are two supported |
| 9133 | values for this optional third argument: |
| 9134 | |
| 9135 | - `layout_compatible` will cause types to be compared according to |
| 9136 | layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the |
| 9137 | layout-compatibility rules for two standard-layout struct types and for two |
| 9138 | standard-layout union types). This is useful when creating a type tag |
| 9139 | associated with a struct or union type. For example: |
| 9140 | |
| 9141 | ```c++ |
| 9142 | /* In mpi.h */ |
| 9143 | typedef int MPI_Datatype; |
| 9144 | struct internal_mpi_double_int { double d; int i; }; |
| 9145 | extern struct mpi_datatype mpi_datatype_double_int |
| 9146 | __attribute__(( type_tag_for_datatype(mpi, |
| 9147 | struct internal_mpi_double_int, layout_compatible) )); |
| 9148 | |
| 9149 | #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int) |
| 9150 | |
| 9151 | int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...) |
| 9152 | __attribute__(( pointer_with_type_tag(mpi,1,3) )); |
| 9153 | |
| 9154 | /* In user code */ |
| 9155 | struct my_pair { double a; int b; }; |
| 9156 | struct my_pair *buffer; |
| 9157 | MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the |
| 9158 | // layout of my_pair is |
| 9159 | // compatible with that of |
| 9160 | // internal_mpi_double_int |
| 9161 | |
| 9162 | struct my_int_pair { int a; int b; } |
| 9163 | struct my_int_pair *buffer2; |
| 9164 | MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the |
| 9165 | // layout of my_int_pair |
| 9166 | // does not match that of |
| 9167 | // internal_mpi_double_int |
| 9168 | ``` |
| 9169 | |
| 9170 | - `must_be_null` specifies that the function argument specified by either |
| 9171 | `arg_idx` (for the `argument_with_type_tag` attribute) or `ptr_idx` (for |
| 9172 | the `pointer_with_type_tag` attribute) should be a null pointer constant. |
| 9173 | The second argument to the `type_tag_for_datatype` attribute is ignored. For |
| 9174 | example: |
| 9175 | |
| 9176 | ```c++ |
| 9177 | /* In mpi.h */ |
| 9178 | typedef int MPI_Datatype; |
| 9179 | extern struct mpi_datatype mpi_datatype_null |
| 9180 | __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) )); |
| 9181 | |
| 9182 | #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null) |
| 9183 | int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...) |
| 9184 | __attribute__(( pointer_with_type_tag(mpi,1,3) )); |
| 9185 | |
| 9186 | /* In user code */ |
| 9187 | struct my_pair { double a; int b; }; |
| 9188 | struct my_pair *buffer; |
| 9189 | MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL |
| 9190 | // was specified but buffer |
| 9191 | // is not a null pointer |
| 9192 | ```)reST" ; |
| 9193 | |
| 9194 | static const char AttrDoc_TypeVisibility[] = R"reST(The `type_visibility` attribute allows the visibility of a type and its vague |
| 9195 | linkage objects (vtable, typeinfo, typeinfo name) to be controlled separately from |
| 9196 | the visibility of functions and data members of the type. |
| 9197 | |
| 9198 | For example, this can be used to give default visibility to the typeinfo and the vtable |
| 9199 | of a type while still keeping hidden visibility on its member functions and static data |
| 9200 | members. |
| 9201 | |
| 9202 | This attribute can only be applied to types and namespaces. |
| 9203 | |
| 9204 | If both `visibility` and `type_visibility` are applied to a type or a namespace, the |
| 9205 | visibility specified with the `type_visibility` attribute overrides the visibility |
| 9206 | provided with the regular `visibility` attribute.)reST" ; |
| 9207 | |
| 9208 | static const char AttrDoc_UPtr[] = R"reST(The `__uptr` qualifier specifies that a 32-bit pointer should be zero |
| 9209 | extended when converted to a 64-bit pointer.)reST" ; |
| 9210 | |
| 9211 | static const char AttrDoc_Unavailable[] = R"reST(No documentation.)reST" ; |
| 9212 | |
| 9213 | static const char AttrDoc_Uninitialized[] = R"reST(The command-line parameter `-ftrivial-auto-var-init=*` can be used to |
| 9214 | initialize trivial automatic stack variables. By default, trivial automatic |
| 9215 | stack variables are uninitialized. This attribute is used to override the |
| 9216 | command-line parameter, forcing variables to remain uninitialized. It has no |
| 9217 | semantic meaning in that using uninitialized values is undefined behavior, |
| 9218 | it rather documents the programmer's intent.)reST" ; |
| 9219 | |
| 9220 | static const char AttrDoc_Unlikely[] = R"reST(The `likely` and `unlikely` attributes are used as compiler hints. |
| 9221 | The attributes are used to aid the compiler to determine which branch is |
| 9222 | likely or unlikely to be taken. This is done by marking the branch substatement |
| 9223 | with one of the two attributes. |
| 9224 | |
| 9225 | It isn't allowed to annotate a single statement with both `likely` and |
| 9226 | `unlikely`. Annotating the `true` and `false` branch of an `if` |
| 9227 | statement with the same likelihood attribute will result in a diagnostic and |
| 9228 | the attributes are ignored on both branches. |
| 9229 | |
| 9230 | In a `switch` statement it's allowed to annotate multiple `case` labels |
| 9231 | or the `default` label with the same likelihood attribute. This makes |
| 9232 | \* all labels without an attribute have a neutral likelihood, |
| 9233 | \* all labels marked `[[likely]]` have an equally positive likelihood, and |
| 9234 | \* all labels marked `[[unlikely]]` have an equally negative likelihood. |
| 9235 | The neutral likelihood is the more likely of path execution than the negative |
| 9236 | likelihood. The positive likelihood is the more likely of path of execution |
| 9237 | than the neutral likelihood. |
| 9238 | |
| 9239 | These attributes have no effect on the generated code when using |
| 9240 | PGO (Profile-Guided Optimization) or at optimization level 0. |
| 9241 | |
| 9242 | In Clang, the attributes will be ignored if they're not placed on |
| 9243 | \* the `case` or `default` label of a `switch` statement, |
| 9244 | \* or on the substatement of an `if` or `else` statement, |
| 9245 | \* or on the substatement of an `for` or `while` statement. |
| 9246 | The C++ Standard recommends to honor them on every statement in the |
| 9247 | path of execution, but that can be confusing: |
| 9248 | |
| 9249 | ```c++ |
| 9250 | if (b) { |
| 9251 | [[unlikely]] --b; // Per the standard this is in the path of |
| 9252 | // execution, so this branch should be considered |
| 9253 | // unlikely. However, Clang ignores the attribute |
| 9254 | // here since it is not on the substatement. |
| 9255 | } |
| 9256 | |
| 9257 | if (b) { |
| 9258 | --b; |
| 9259 | if(b) |
| 9260 | return; |
| 9261 | [[unlikely]] --b; // Not in the path of execution, |
| 9262 | } // the branch has no likelihood information. |
| 9263 | |
| 9264 | if (b) { |
| 9265 | --b; |
| 9266 | foo(b); |
| 9267 | // Whether or not the next statement is in the path of execution depends |
| 9268 | // on the declaration of foo(): |
| 9269 | // In the path of execution: void foo(int); |
| 9270 | // Not in the path of execution: [[noreturn]] void foo(int); |
| 9271 | // This means the likelihood of the branch depends on the declaration |
| 9272 | // of foo(). |
| 9273 | [[unlikely]] --b; |
| 9274 | } |
| 9275 | ``` |
| 9276 | |
| 9277 | Below are some example usages of the likelihood attributes and their effects: |
| 9278 | |
| 9279 | ```c++ |
| 9280 | if (b) [[likely]] { // Placement on the first statement in the branch. |
| 9281 | // The compiler will optimize to execute the code here. |
| 9282 | } else { |
| 9283 | } |
| 9284 | |
| 9285 | if (b) |
| 9286 | [[unlikely]] b++; // Placement on the first statement in the branch. |
| 9287 | else { |
| 9288 | // The compiler will optimize to execute the code here. |
| 9289 | } |
| 9290 | |
| 9291 | if (b) { |
| 9292 | [[unlikely]] b++; // Placement on the second statement in the branch. |
| 9293 | } // The attribute will be ignored. |
| 9294 | |
| 9295 | if (b) [[likely]] { |
| 9296 | [[unlikely]] b++; // No contradiction since the second attribute |
| 9297 | } // is ignored. |
| 9298 | |
| 9299 | if (b) |
| 9300 | ; |
| 9301 | else [[likely]] { |
| 9302 | // The compiler will optimize to execute the code here. |
| 9303 | } |
| 9304 | |
| 9305 | if (b) |
| 9306 | ; |
| 9307 | else |
| 9308 | // The compiler will optimize to execute the next statement. |
| 9309 | [[likely]] b = f(); |
| 9310 | |
| 9311 | if (b) [[likely]]; // Both branches are likely. A diagnostic is issued |
| 9312 | else [[likely]]; // and the attributes are ignored. |
| 9313 | |
| 9314 | if (b) |
| 9315 | [[likely]] int i = 5; // Issues a diagnostic since the attribute |
| 9316 | // isn't allowed on a declaration. |
| 9317 | |
| 9318 | switch (i) { |
| 9319 | [[likely]] case 1: // This value is likely |
| 9320 | ... |
| 9321 | break; |
| 9322 | |
| 9323 | [[unlikely]] case 2: // This value is unlikely |
| 9324 | ... |
| 9325 | [[fallthrough]]; |
| 9326 | |
| 9327 | case 3: // No likelihood attribute |
| 9328 | ... |
| 9329 | [[likely]] break; // No effect |
| 9330 | |
| 9331 | case 4: [[likely]] { // attribute on substatement has no effect |
| 9332 | ... |
| 9333 | break; |
| 9334 | } |
| 9335 | |
| 9336 | [[unlikely]] default: // All other values are unlikely |
| 9337 | ... |
| 9338 | break; |
| 9339 | } |
| 9340 | |
| 9341 | switch (i) { |
| 9342 | [[likely]] case 0: // This value and code path is likely |
| 9343 | ... |
| 9344 | [[fallthrough]]; |
| 9345 | |
| 9346 | case 1: // No likelihood attribute, code path is neutral |
| 9347 | break; // falling through has no effect on the likelihood |
| 9348 | |
| 9349 | case 2: // No likelihood attribute, code path is neutral |
| 9350 | [[fallthrough]]; |
| 9351 | |
| 9352 | [[unlikely]] default: // This value and code path are both unlikely |
| 9353 | break; |
| 9354 | } |
| 9355 | |
| 9356 | for(int i = 0; i != size; ++i) [[likely]] { |
| 9357 | ... // The loop is the likely path of execution |
| 9358 | } |
| 9359 | |
| 9360 | for(const auto &E : Elements) [[likely]] { |
| 9361 | ... // The loop is the likely path of execution |
| 9362 | } |
| 9363 | |
| 9364 | while(i != size) [[unlikely]] { |
| 9365 | ... // The loop is the unlikely path of execution |
| 9366 | } // The generated code will optimize to skip the loop body |
| 9367 | |
| 9368 | while(true) [[unlikely]] { |
| 9369 | ... // The attribute has no effect |
| 9370 | } // Clang elides the comparison and generates an infinite |
| 9371 | // loop |
| 9372 | ```)reST" ; |
| 9373 | |
| 9374 | static const char AttrDoc_UnsafeBufferUsage[] = R"reST(The attribute `[[clang::unsafe_buffer_usage]]` should be placed on functions |
| 9375 | that need to be avoided as they are prone to buffer overflows or unsafe buffer |
| 9376 | struct fields. It is designed to work together with the off-by-default compiler |
| 9377 | warning `-Wunsafe-buffer-usage` to help codebases transition away from raw pointer |
| 9378 | based buffer management, in favor of safer abstractions such as C++20 `std::span`. |
| 9379 | The attribute causes `-Wunsafe-buffer-usage` to warn on every use of the function or |
| 9380 | the field it is attached to, and it may also lead to emission of automatic fix-it |
| 9381 | hints which would help the user replace the use of unsafe functions(/fields) with safe |
| 9382 | alternatives, though the attribute can be used even when the fix can't be automated. |
| 9383 | |
| 9384 | - Attribute attached to functions: The attribute suppresses all |
| 9385 | `-Wunsafe-buffer-usage` warnings within the function it is attached to, as the |
| 9386 | function is now classified as unsafe. The attribute should be used carefully, as it |
| 9387 | will silence all unsafe operation warnings inside the function; including any new |
| 9388 | unsafe operations introduced in the future. |
| 9389 | |
| 9390 | The attribute is warranted even if the only way a function can overflow |
| 9391 | the buffer is by violating the function's preconditions. For example, it |
| 9392 | would make sense to put the attribute on function `foo()` below because |
| 9393 | passing an incorrect size parameter would cause a buffer overflow: |
| 9394 | |
| 9395 | ```c++ |
| 9396 | [[clang::unsafe_buffer_usage]] |
| 9397 | void foo(int *buf, size_t size) { |
| 9398 | for (size_t i = 0; i < size; ++i) { |
| 9399 | buf[i] = i; |
| 9400 | } |
| 9401 | } |
| 9402 | ``` |
| 9403 | |
| 9404 | The attribute is NOT warranted when the function uses safe abstractions, |
| 9405 | assuming that these abstractions weren't misused outside the function. |
| 9406 | For example, function `bar()` below doesn't need the attribute, |
| 9407 | because assuming that the container `buf` is well-formed (has size that |
| 9408 | fits the original buffer it refers to), overflow cannot occur: |
| 9409 | |
| 9410 | ```c++ |
| 9411 | void bar(std::span<int> buf) { |
| 9412 | for (size_t i = 0; i < buf.size(); ++i) { |
| 9413 | buf[i] = i; |
| 9414 | } |
| 9415 | } |
| 9416 | ``` |
| 9417 | |
| 9418 | In this case function `bar()` enables the user to keep the buffer |
| 9419 | "containerized" in a span for as long as possible. On the other hand, |
| 9420 | Function `foo()` in the previous example may have internal |
| 9421 | consistency, but by accepting a raw buffer it requires the user to unwrap |
| 9422 | their span, which is undesirable according to the programming model |
| 9423 | behind `-Wunsafe-buffer-usage`. |
| 9424 | |
| 9425 | The attribute is warranted when a function accepts a raw buffer only to |
| 9426 | immediately put it into a span: |
| 9427 | |
| 9428 | ```c++ |
| 9429 | [[clang::unsafe_buffer_usage]] |
| 9430 | void baz(int *buf, size_t size) { |
| 9431 | std::span<int> sp{ buf, size }; |
| 9432 | for (size_t i = 0; i < sp.size(); ++i) { |
| 9433 | sp[i] = i; |
| 9434 | } |
| 9435 | } |
| 9436 | ``` |
| 9437 | |
| 9438 | In this case `baz()` does not contain any unsafe operations, but the awkward |
| 9439 | parameter type causes the caller to unwrap the span unnecessarily. |
| 9440 | Note that regardless of the attribute, code inside `baz()` isn't flagged |
| 9441 | by `-Wunsafe-buffer-usage` as unsafe. It is definitely undesirable, |
| 9442 | but if `baz()` is on an API surface, there is no way to improve it |
| 9443 | to make it as safe as `bar()` without breaking the source and binary |
| 9444 | compatibility with existing users of the function. In such cases |
| 9445 | the proper solution would be to create a different function (possibly |
| 9446 | an overload of `baz()`) that accepts a safe container like `bar()`, |
| 9447 | and then use the attribute on the original `baz()` to help the users |
| 9448 | update their code to use the new function. |
| 9449 | |
| 9450 | - Attribute attached to fields: The attribute should only be attached to |
| 9451 | struct fields, if the fields can not be updated to a safe type with bounds |
| 9452 | check, such as std::span. In other words, the buffers prone to unsafe accesses |
| 9453 | should always be updated to use safe containers/views and attaching the attribute |
| 9454 | must be last resort when such an update is infeasible. |
| 9455 | |
| 9456 | The attribute can be placed on individual fields or a set of them as shown below. |
| 9457 | |
| 9458 | ```c++ |
| 9459 | struct A { |
| 9460 | [[clang::unsafe_buffer_usage]] |
| 9461 | int *ptr1; |
| 9462 | |
| 9463 | [[clang::unsafe_buffer_usage]] |
| 9464 | int *ptr2, buf[10]; |
| 9465 | |
| 9466 | [[clang::unsafe_buffer_usage]] |
| 9467 | size_t sz; |
| 9468 | }; |
| 9469 | ``` |
| 9470 | |
| 9471 | Here, every read/write to the fields ptr1, ptr2, buf and sz will trigger a warning |
| 9472 | that the field has been explcitly marked as unsafe due to unsafe-buffer operations.)reST" ; |
| 9473 | |
| 9474 | static const char AttrDoc_Unused[] = R"reST(When passing the `-Wunused` flag to Clang, entities that are unused by the |
| 9475 | program may be diagnosed. The `[[maybe_unused]]` (or |
| 9476 | `__attribute__((unused))`) attribute can be used to silence such diagnostics |
| 9477 | when the entity cannot be removed. For instance, a local variable may exist |
| 9478 | solely for use in an `assert()` statement, which makes the local variable |
| 9479 | unused when `NDEBUG` is defined. |
| 9480 | |
| 9481 | The attribute may be applied to the declaration of a class, a typedef, a |
| 9482 | variable, a function or method, a function parameter, an enumeration, an |
| 9483 | enumerator, a non-static data member, or a label. |
| 9484 | |
| 9485 | ```c++ |
| 9486 | #include <cassert> |
| 9487 | |
| 9488 | [[maybe_unused]] void f([[maybe_unused]] bool thing1, |
| 9489 | [[maybe_unused]] bool thing2) { |
| 9490 | [[maybe_unused]] bool b = thing1 && thing2; |
| 9491 | assert(b); |
| 9492 | } |
| 9493 | ```)reST" ; |
| 9494 | |
| 9495 | static const char AttrDoc_UseHandle[] = R"reST(A function taking a handle by value might close the handle. If a function |
| 9496 | parameter is annotated with `use_handle(tag)` it is assumed to not to change |
| 9497 | the state of the handle. It is also assumed to require an open handle to work with. |
| 9498 | The attribute requires a string literal argument to identify the handle being used. |
| 9499 | |
| 9500 | ```c++ |
| 9501 | zx_status_t zx_port_wait(zx_handle_t handle [[clang::use_handle("zircon")]], |
| 9502 | zx_time_t deadline, |
| 9503 | zx_port_packet_t* packet); |
| 9504 | ```)reST" ; |
| 9505 | |
| 9506 | static const char AttrDoc_Used[] = R"reST(This attribute, when attached to a function or variable definition, indicates |
| 9507 | that there may be references to the entity which are not apparent in the source |
| 9508 | code. For example, it may be referenced from inline `asm`, or it may be |
| 9509 | found through a dynamic symbol or section lookup. |
| 9510 | |
| 9511 | The compiler must emit the definition even if it appears to be unused, and it |
| 9512 | must not apply optimizations which depend on fully understanding how the entity |
| 9513 | is used. |
| 9514 | |
| 9515 | Whether this attribute has any effect on the linker depends on the target and |
| 9516 | the linker. Most linkers support the feature of section garbage collection |
| 9517 | (`--gc-sections`), also known as "dead stripping" (`ld64 -dead_strip`) or |
| 9518 | discarding unreferenced sections (`link.exe /OPT:REF`). On COFF and Mach-O |
| 9519 | targets (Windows and Apple platforms), the `used` attribute prevents symbols |
| 9520 | from being removed by linker section GC. On ELF targets, it has no effect on its |
| 9521 | own, and the linker may remove the definition if it is not otherwise referenced. |
| 9522 | This linker GC can be avoided by also adding the `retain` attribute. Note |
| 9523 | that `retain` requires special support from the linker; see that attribute's |
| 9524 | documentation for further information.)reST" ; |
| 9525 | |
| 9526 | static const char AttrDoc_UsingIfExists[] = R"reST(The `using_if_exists` attribute applies to a using-declaration. It allows |
| 9527 | programmers to import a declaration that potentially does not exist, instead |
| 9528 | deferring any errors to the point of use. For instance: |
| 9529 | |
| 9530 | ```c++ |
| 9531 | namespace empty_namespace {}; |
| 9532 | __attribute__((using_if_exists)) |
| 9533 | using empty_namespace::does_not_exist; // no error! |
| 9534 | |
| 9535 | does_not_exist x; // error: use of unresolved 'using_if_exists' |
| 9536 | ``` |
| 9537 | |
| 9538 | The C++ spelling of the attribute (`[[clang::using_if_exists]]`) is also |
| 9539 | supported as a clang extension, since ISO C++ doesn't support attributes in this |
| 9540 | position. If the entity referred to by the using-declaration is found by name |
| 9541 | lookup, the attribute has no effect. This attribute is useful for libraries |
| 9542 | (primarily, libc++) that wish to redeclare a set of declarations in another |
| 9543 | namespace, when the availability of those declarations is difficult or |
| 9544 | impossible to detect at compile time with the preprocessor.)reST" ; |
| 9545 | |
| 9546 | static const char AttrDoc_Uuid[] = R"reST(No documentation.)reST" ; |
| 9547 | |
| 9548 | static const char AttrDoc_VTablePointerAuthentication[] = R"reST(No documentation.)reST" ; |
| 9549 | |
| 9550 | static const char AttrDoc_VecReturn[] = R"reST(No documentation.)reST" ; |
| 9551 | |
| 9552 | static const char AttrDoc_VecTypeHint[] = R"reST(No documentation.)reST" ; |
| 9553 | |
| 9554 | static const char AttrDoc_VectorCall[] = R"reST(On 32-bit x86 *and* x86_64 targets, this attribute changes the calling |
| 9555 | convention of a function to pass vector parameters in SSE registers. |
| 9556 | |
| 9557 | On 32-bit x86 targets, this calling convention is similar to `__fastcall`. |
| 9558 | The first two integer parameters are passed in ECX and EDX. Subsequent integer |
| 9559 | parameters are passed in memory, and callee clears the stack. On x86_64 |
| 9560 | targets, the callee does *not* clear the stack, and integer parameters are |
| 9561 | passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling |
| 9562 | convention. |
| 9563 | |
| 9564 | On both 32-bit x86 and x86_64 targets, vector and floating point arguments are |
| 9565 | passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are |
| 9566 | passed in sequential SSE registers if enough are available. If AVX is enabled, |
| 9567 | 256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that |
| 9568 | cannot be passed in registers for any reason is passed by reference, which |
| 9569 | allows the caller to align the parameter memory. |
| 9570 | |
| 9571 | See the documentation for [\_\_vectorcall][__vectorcall] on MSDN for more details. |
| 9572 | |
| 9573 | [__vectorcall]: http://msdn.microsoft.com/en-us/library/dn375768.aspx)reST" ; |
| 9574 | |
| 9575 | static const char AttrDoc_Visibility[] = R"reST(No documentation.)reST" ; |
| 9576 | |
| 9577 | static const char AttrDoc_WarnUnused[] = R"reST(The `warn_unused` attribute can be placed on the declaration of a structure or union type. |
| 9578 | When 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. |
| 9579 | Those constructor or destructor invocations are not considered a use if the type is declared with the `warn_unused` attribute. |
| 9580 | The variable is considered used if it is named outside of its declaration. |
| 9581 | |
| 9582 | This attribute is available in both C and C++ language modes but is primarily useful in C++ for classes which have a non-trivial constructor or destructor but act as a value type rather than an RAII type. |
| 9583 | |
| 9584 | ```c++ |
| 9585 | struct [[gnu::warn_unused]] S { |
| 9586 | S(); |
| 9587 | ~S(); |
| 9588 | }; |
| 9589 | |
| 9590 | struct T { |
| 9591 | T(); |
| 9592 | ~T(); |
| 9593 | }; |
| 9594 | |
| 9595 | int func() { |
| 9596 | S s1; // -Wunused-variable warning |
| 9597 | S s2; // No -Wunused-variable warning because of the member access expression below |
| 9598 | S s3; // No -Wunused-variable warning because of the sizeof operand below |
| 9599 | T t; // No -Wunused-variable warning |
| 9600 | |
| 9601 | s2.~S(); |
| 9602 | return sizeof(s3); |
| 9603 | } |
| 9604 | ```)reST" ; |
| 9605 | |
| 9606 | static const char AttrDoc_WarnUnusedResult[] = R"reST(Clang supports the ability to diagnose when the results of a function call |
| 9607 | expression are discarded under suspicious circumstances. A diagnostic is |
| 9608 | generated when a function or its return type is marked with `[[nodiscard]]` |
| 9609 | (or `__attribute__((warn_unused_result))`) and the function call appears as a |
| 9610 | potentially-evaluated discarded-value expression that is not explicitly cast to |
| 9611 | `void`. |
| 9612 | |
| 9613 | A string literal may optionally be provided to the attribute, which will be |
| 9614 | reproduced in any resulting diagnostics. Redeclarations using different forms |
| 9615 | of the attribute (with or without the string literal or with different string |
| 9616 | literal contents) are allowed. If there are redeclarations of the entity with |
| 9617 | differing string literals, it is unspecified which one will be used by Clang |
| 9618 | in any resulting diagnostics. |
| 9619 | |
| 9620 | ```c++ |
| 9621 | struct [[nodiscard]] error_info { /*...*/ }; |
| 9622 | error_info enable_missile_safety_mode(); |
| 9623 | |
| 9624 | void launch_missiles(); |
| 9625 | void test_missiles() { |
| 9626 | enable_missile_safety_mode(); // diagnoses |
| 9627 | launch_missiles(); |
| 9628 | } |
| 9629 | error_info &foo(); |
| 9630 | void f() { foo(); } // Does not diagnose, error_info is a reference. |
| 9631 | ``` |
| 9632 | |
| 9633 | Additionally, discarded temporaries resulting from a call to a constructor |
| 9634 | marked with `[[nodiscard]]` or a constructor of a type marked |
| 9635 | `[[nodiscard]]` will also diagnose. This also applies to type conversions that |
| 9636 | use the annotated `[[nodiscard]]` constructor or result in an annotated type. |
| 9637 | |
| 9638 | ```c++ |
| 9639 | struct [[nodiscard]] marked_type {/*..*/ }; |
| 9640 | struct marked_ctor { |
| 9641 | [[nodiscard]] marked_ctor(); |
| 9642 | marked_ctor(int); |
| 9643 | }; |
| 9644 | |
| 9645 | struct S { |
| 9646 | operator marked_type() const; |
| 9647 | [[nodiscard]] operator int() const; |
| 9648 | }; |
| 9649 | |
| 9650 | void usages() { |
| 9651 | marked_type(); // diagnoses. |
| 9652 | marked_ctor(); // diagnoses. |
| 9653 | marked_ctor(3); // Does not diagnose, int constructor isn't marked nodiscard. |
| 9654 | |
| 9655 | S s; |
| 9656 | static_cast<marked_type>(s); // diagnoses |
| 9657 | (int)s; // diagnoses |
| 9658 | } |
| 9659 | ```)reST" ; |
| 9660 | |
| 9661 | static const char AttrDoc_Weak[] = R"reST(In supported output formats the `weak` attribute can be used to |
| 9662 | specify that a variable or function should be emitted as a symbol with |
| 9663 | `weak` (if a definition) or `extern_weak` (if a declaration of an |
| 9664 | external symbol) [linkage](https://llvm.org/docs/LangRef.html#linkage-types). |
| 9665 | |
| 9666 | If there is a non-weak definition of the symbol the linker will select |
| 9667 | that over the weak. They must have same type and alignment (variables |
| 9668 | must also have the same size), but may have a different value. |
| 9669 | |
| 9670 | If there are multiple weak definitions of same symbol, but no non-weak |
| 9671 | definition, they should have same type, size, alignment and value, the |
| 9672 | linker will select one of them (see also [selectany] attribute). |
| 9673 | |
| 9674 | If the `weak` attribute is applied to a `const` qualified variable |
| 9675 | definition that variable is no longer consider a compiletime constant |
| 9676 | as its value can change during linking (or dynamic linking). This |
| 9677 | means that it can e.g no longer be part of an initializer expression. |
| 9678 | |
| 9679 | ```c |
| 9680 | const int ANSWER __attribute__ ((weak)) = 42; |
| 9681 | |
| 9682 | /* This function may be replaced link-time */ |
| 9683 | __attribute__ ((weak)) void debug_log(const char *msg) |
| 9684 | { |
| 9685 | fprintf(stderr, "DEBUG: %s\n", msg); |
| 9686 | } |
| 9687 | |
| 9688 | int main(int argc, const char **argv) |
| 9689 | { |
| 9690 | debug_log ("Starting up..."); |
| 9691 | |
| 9692 | /* This may print something else than "6 * 7 = 42", |
| 9693 | if there is a non-weak definition of "ANSWER" in |
| 9694 | an object linked in */ |
| 9695 | printf("6 * 7 = %d\n", ANSWER); |
| 9696 | |
| 9697 | return 0; |
| 9698 | } |
| 9699 | ``` |
| 9700 | |
| 9701 | If an external declaration is marked weak and that symbol does not |
| 9702 | exist during linking (possibly dynamic) the address of the symbol will |
| 9703 | evaluate to NULL. |
| 9704 | |
| 9705 | ```c |
| 9706 | void may_not_exist(void) __attribute__ ((weak)); |
| 9707 | |
| 9708 | int main(int argc, const char **argv) |
| 9709 | { |
| 9710 | if (may_not_exist) { |
| 9711 | may_not_exist(); |
| 9712 | } else { |
| 9713 | printf("Function did not exist\n"); |
| 9714 | } |
| 9715 | return 0; |
| 9716 | } |
| 9717 | ```)reST" ; |
| 9718 | |
| 9719 | static const char AttrDoc_WeakImport[] = R"reST(No documentation.)reST" ; |
| 9720 | |
| 9721 | static const char AttrDoc_WeakRef[] = R"reST(No documentation.)reST" ; |
| 9722 | |
| 9723 | static const char AttrDoc_WebAssemblyExportName[] = R"reST(Clang supports the `__attribute__((export_name(<name>)))` |
| 9724 | attribute for the WebAssembly target. This attribute may be attached to a |
| 9725 | function declaration, where it modifies how the symbol is to be exported |
| 9726 | from the linked WebAssembly. |
| 9727 | |
| 9728 | WebAssembly functions are exported via string name. By default when a symbol |
| 9729 | is exported, the export name for C/C++ symbols are the same as their C/C++ |
| 9730 | symbol names. This attribute can be used to override the default behavior, and |
| 9731 | request a specific string name be used instead.)reST" ; |
| 9732 | |
| 9733 | static const char AttrDoc_WebAssemblyFuncref[] = R"reST(Clang supports the `__attribute__((export_name(<name>)))` |
| 9734 | attribute for the WebAssembly target. This attribute may be attached to a |
| 9735 | function declaration, where it modifies how the symbol is to be exported |
| 9736 | from the linked WebAssembly. |
| 9737 | |
| 9738 | WebAssembly functions are exported via string name. By default when a symbol |
| 9739 | is exported, the export name for C/C++ symbols are the same as their C/C++ |
| 9740 | symbol names. This attribute can be used to override the default behavior, and |
| 9741 | request a specific string name be used instead.)reST" ; |
| 9742 | |
| 9743 | static const char AttrDoc_WebAssemblyImportModule[] = R"reST(Clang supports the `__attribute__((import_module(<module_name>)))` |
| 9744 | attribute for the WebAssembly target. This attribute may be attached to a |
| 9745 | function declaration, where it modifies how the symbol is to be imported |
| 9746 | within the WebAssembly linking environment. |
| 9747 | |
| 9748 | WebAssembly imports use a two-level namespace scheme, consisting of a module |
| 9749 | name, which typically identifies a module from which to import, and a field |
| 9750 | name, which typically identifies a field from that module to import. By |
| 9751 | default, module names for C/C++ symbols are assigned automatically by the |
| 9752 | linker. This attribute can be used to override the default behavior, and |
| 9753 | request a specific module name be used instead.)reST" ; |
| 9754 | |
| 9755 | static const char AttrDoc_WebAssemblyImportName[] = R"reST(Clang supports the `__attribute__((import_name(<name>)))` |
| 9756 | attribute for the WebAssembly target. This attribute may be attached to a |
| 9757 | function declaration, where it modifies how the symbol is to be imported |
| 9758 | within the WebAssembly linking environment. |
| 9759 | |
| 9760 | WebAssembly imports use a two-level namespace scheme, consisting of a module |
| 9761 | name, which typically identifies a module from which to import, and a field |
| 9762 | name, which typically identifies a field from that module to import. By |
| 9763 | default, field names for C/C++ symbols are the same as their C/C++ symbol |
| 9764 | names. This attribute can be used to override the default behavior, and |
| 9765 | request a specific field name be used instead.)reST" ; |
| 9766 | |
| 9767 | static const char AttrDoc_WorkGroupSizeHint[] = R"reST(No documentation.)reST" ; |
| 9768 | |
| 9769 | static const char AttrDoc_X86ForceAlignArgPointer[] = R"reST(Use this attribute to force stack alignment. |
| 9770 | |
| 9771 | Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions |
| 9772 | (like 'movaps') that work with the stack require operands to be 16-byte aligned. |
| 9773 | This attribute realigns the stack in the function prologue to make sure the |
| 9774 | stack can be used with SSE instructions. |
| 9775 | |
| 9776 | Note that the x86_64 ABI forces 16-byte stack alignment at the call site. |
| 9777 | Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in |
| 9778 | rare cases where the caller does not align the stack properly (e.g. flow |
| 9779 | jumps from i386 arch code). |
| 9780 | |
| 9781 | ```c |
| 9782 | __attribute__ ((force_align_arg_pointer)) |
| 9783 | void f () { |
| 9784 | ... |
| 9785 | } |
| 9786 | ```)reST" ; |
| 9787 | |
| 9788 | static const char AttrDoc_XRayInstrument[] = R"reST(`__attribute__((xray_always_instrument))` or |
| 9789 | `[[clang::xray_always_instrument]]` is used to mark member functions (in C++), |
| 9790 | methods (in Objective C), and free functions (in C, C++, and Objective C) to be |
| 9791 | instrumented with XRay. This will cause the function to always have space at |
| 9792 | the beginning and exit points to allow for runtime patching. |
| 9793 | |
| 9794 | Conversely, `__attribute__((xray_never_instrument))` or |
| 9795 | `[[clang::xray_never_instrument]]` will inhibit the insertion of these |
| 9796 | instrumentation points. |
| 9797 | |
| 9798 | If a function has neither of these attributes, they become subject to the XRay |
| 9799 | heuristics used to determine whether a function should be instrumented or |
| 9800 | otherwise. |
| 9801 | |
| 9802 | `__attribute__((xray_log_args(N)))` or `[[clang::xray_log_args(N)]]` is |
| 9803 | used to preserve N function arguments for the logging function. Currently, |
| 9804 | only N==1 is supported.)reST" ; |
| 9805 | |
| 9806 | static const char AttrDoc_XRayLogArgs[] = R"reST(`__attribute__((xray_always_instrument))` or |
| 9807 | `[[clang::xray_always_instrument]]` is used to mark member functions (in C++), |
| 9808 | methods (in Objective C), and free functions (in C, C++, and Objective C) to be |
| 9809 | instrumented with XRay. This will cause the function to always have space at |
| 9810 | the beginning and exit points to allow for runtime patching. |
| 9811 | |
| 9812 | Conversely, `__attribute__((xray_never_instrument))` or |
| 9813 | `[[clang::xray_never_instrument]]` will inhibit the insertion of these |
| 9814 | instrumentation points. |
| 9815 | |
| 9816 | If a function has neither of these attributes, they become subject to the XRay |
| 9817 | heuristics used to determine whether a function should be instrumented or |
| 9818 | otherwise. |
| 9819 | |
| 9820 | `__attribute__((xray_log_args(N)))` or `[[clang::xray_log_args(N)]]` is |
| 9821 | used to preserve N function arguments for the logging function. Currently, |
| 9822 | only N==1 is supported.)reST" ; |
| 9823 | |
| 9824 | static const char AttrDoc_ZeroCallUsedRegs[] = R"reST(This attribute, when attached to a function, causes the compiler to zero a |
| 9825 | subset of all call-used registers before the function returns. It's used to |
| 9826 | increase program security by either mitigating [Return-Oriented Programming][return-oriented programming] |
| 9827 | (ROP) attacks or preventing information leakage through registers. |
| 9828 | |
| 9829 | The term "call-used" means registers which are not guaranteed to be preserved |
| 9830 | unchanged for the caller by the current calling convention. This could also be |
| 9831 | described as "caller-saved" or "not callee-saved". |
| 9832 | |
| 9833 | The `choice` parameters gives the programmer flexibility to choose the subset |
| 9834 | of the call-used registers to be zeroed: |
| 9835 | |
| 9836 | - `skip` doesn't zero any call-used registers. This choice overrides any |
| 9837 | command-line arguments. |
| 9838 | - `used` only zeros call-used registers used in the function. By `used`, we |
| 9839 | mean a register whose contents have been set or referenced in the function. |
| 9840 | - `used-gpr` only zeros call-used GPR registers used in the function. |
| 9841 | - `used-arg` only zeros call-used registers used to pass arguments to the |
| 9842 | function. |
| 9843 | - `used-gpr-arg` only zeros call-used GPR registers used to pass arguments to |
| 9844 | the function. |
| 9845 | - `all` zeros all call-used registers. |
| 9846 | - `all-gpr` zeros all call-used GPR registers. |
| 9847 | - `all-arg` zeros all call-used registers used to pass arguments to the |
| 9848 | function. |
| 9849 | - `all-gpr-arg` zeros all call-used GPR registers used to pass arguments to |
| 9850 | the function. |
| 9851 | |
| 9852 | The default for the attribute is controlled by the `-fzero-call-used-regs` |
| 9853 | flag. |
| 9854 | |
| 9855 | [return-oriented programming]: https://en.wikipedia.org/wiki/Return-oriented_programming)reST" ; |
| 9856 | |