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