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