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