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