Attributes in Clang¶
Introduction¶
This page lists the attributes currently supported by Clang.
AArch64 SME Attributes¶
Clang supports a number of AArch64-specific attributes to manage stateadded by the Scalable Matrix Extension (SME). This state includes theruntime mode that the processor is in (e.g. non-streaming or streaming)as well as the state of theZA
Matrix Storage.
The attributes come in the form of type- and declaration attributes:
The SME declaration attributes can appear anywhere that a standard
[[...]]
declaration attribute can appear.The SME type attributes apply only to prototyped functions and can appearanywhere that a standard
[[...]]
type attribute can appear. The SMEtype attributes do not apply to functions having a K&R-styleunprototyped function type.
SeeArm C Language Extensionsfor more details about the features related to the SME extension.
SeeProcedure Call Standard for the Arm® 64-bit Architecture (AArch64) for more details aboutstreaming-interface functions and shared/private-ZA interface functions.
__arm_agnostic¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__arm_agnostic
keyword applies to prototyped function types andaffects the function’s calling convention for a given state S. Thisattribute allows the user to describe a function that preserves S, withoutrequiring the function to share S with its callers and without makingthe assumption that S exists.
If a function has the__arm_agnostic(S)
attribute and calls a functionwithout this attribute, then the function’s object code will contain codeto preserve state S. Otherwise, the function’s object code will be the sameas if it did not have the attribute.
The attribute takes string arguments to describe state S. The supportedstates are:
"sme_za_state"
for state enabled by PSTATE.ZA, such as ZA and ZT0.
The attribute__arm_agnostic("sme_za_state")
cannot be used in conjunctionwith__arm_in(S)
,__arm_out(S)
,__arm_inout(S)
or__arm_preserves(S)
where state S describes state enabled by PSTATE.ZA,such as “za” or “zt0”.
__arm_in¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__arm_in
keyword applies to prototyped function types and specifiesthat the function shares a given state S with its caller. For__arm_in
, thefunction takes the state S as input and returns with the state S unchanged.
The attribute takes string arguments to instruct the compiler which stateis shared. The supported states for S are:
"za"
for Matrix Storage (requires SME)
The attributes__arm_in(S)
,__arm_out(S)
,__arm_inout(S)
and__arm_preserves(S)
are all mutually exclusive for the same state S.
__arm_inout¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__arm_inout
keyword applies to prototyped function types and specifiesthat the function shares a given state S with its caller. For__arm_inout
,the function takes the state S as input and returns new state for S.
The attribute takes string arguments to instruct the compiler which stateis shared. The supported states for S are:
"za"
for Matrix Storage (requires SME)
The attributes__arm_in(S)
,__arm_out(S)
,__arm_inout(S)
and__arm_preserves(S)
are all mutually exclusive for the same state S.
__arm_locally_streaming¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__arm_locally_streaming
keyword applies to function declarationsand specifies that all the statements in the function are executed instreaming mode. This means that:
the function requires that the target processor implements the Scalable MatrixExtension (SME).
the program automatically puts the machine into streaming mode beforeexecuting the statements and automatically restores the previous modeafterwards.
Clang manages PSTATE.SM automatically; it is not the source code’sresponsibility to do this. For example, Clang will emit code to enablestreaming mode at the start of the function, and disable streaming modeat the end of the function.
__arm_new¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__arm_new
keyword applies to function declarations and specifiesthat the function will create a new scope for state S.
The attribute takes string arguments to instruct the compiler for which stateto create new scope. The supported states for S are:
"za"
for Matrix Storage (requires SME)
For state"za"
, this means that:
the function requires that the target processor implements the Scalable MatrixExtension (SME).
the function will commit any lazily saved ZA data.
the function will create a new ZA context and enable PSTATE.ZA.
the function will disable PSTATE.ZA (by setting it to 0) before returning.
For__arm_new("za")
functions Clang will set up the ZA context automaticallyon entry to the function and disable it before returning. For example, if ZA isin a dormant state Clang will generate the code to commit a lazy-save and set upa new ZA state before executing user code.
__arm_out¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__arm_out
keyword applies to prototyped function types and specifiesthat the function shares a given state S with its caller. For__arm_out
,the function ignores the incoming state for S and returns new state for S.
The attribute takes string arguments to instruct the compiler which stateis shared. The supported states for S are:
"za"
for Matrix Storage (requires SME)
The attributes__arm_in(S)
,__arm_out(S)
,__arm_inout(S)
and__arm_preserves(S)
are all mutually exclusive for the same state S.
__arm_preserves¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__arm_preserves
keyword applies to prototyped function types andspecifies that the function does not read a given state S and returnswith state S unchanged.
The attribute takes string arguments to instruct the compiler which stateis shared. The supported states for S are:
"za"
for Matrix Storage (requires SME)
The attributes__arm_in(S)
,__arm_out(S)
,__arm_inout(S)
and__arm_preserves(S)
are all mutually exclusive for the same state S.
__arm_streaming¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__arm_streaming
keyword applies to prototyped function types and specifiesthat the function has a “streaming interface”. This means that:
the function requires that the processor implements the Scalable MatrixExtension (SME).
the function must be entered in streaming mode (that is, with PSTATE.SMset to 1)
the function must return in streaming mode
Clang manages PSTATE.SM automatically; it is not the source code’sresponsibility to do this. For example, if a non-streamingfunction calls an__arm_streaming
function, Clang generates codethat switches into streaming mode before calling the function andswitches back to non-streaming mode on return.
__arm_streaming_compatible¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__arm_streaming_compatible
keyword applies to prototyped function types andspecifies that the function has a “streaming compatible interface”. Thismeans that:
the function may be entered in either non-streaming mode (PSTATE.SM=0) orin streaming mode (PSTATE.SM=1).
the function must return in the same mode as it was entered.
the code executed in the function is compatible with either mode.
Clang manages PSTATE.SM automatically; it is not the source code’sresponsibility to do this. Clang will ensure that the generated code instreaming-compatible functions is valid in either mode (PSTATE.SM=0 orPSTATE.SM=1). For example, if an__arm_streaming_compatible
function calls anon-streaming function, Clang generates code to temporarily switch out of streamingmode before calling the function and switch back to streaming-mode on return ifPSTATE.SM
is1
on entry of the caller. IfPSTATE.SM
is0
onentry to the__arm_streaming_compatible
function, the call will be executedwithout changing modes.
AMD GPU Attributes¶
amdgpu_flat_work_group_size¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
The flat work-group size is the number of work-items in the work-group sizespecified when the kernel is dispatched. It is the product of the sizes of thex, y, and z dimension of the work-group.
Clang supports the__attribute__((amdgpu_flat_work_group_size(<min>,<max>)))
attribute for theAMDGPU target. This attribute may be attached to a kernel function definitionand is an optimization hint.
<min>
parameter specifies the minimum flat work-group size, and<max>
parameter specifies the maximum flat work-group size (must be greater than<min>
) to which all dispatches of the kernel will conform. Passing0,0
as<min>,<max>
implies the default behavior (128,256
).
If specified, the AMDGPU target backend might be able to produce better machinecode for barriers and perform scratch promotion by estimating available groupsegment size.
- An error will be given if:
Specified values violate subtarget specifications;
Specified values are not compatible with values provided through otherattributes.
amdgpu_max_num_work_groups¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
This attribute specifies the max number of work groups when the kernelis dispatched.
Clang supports the__attribute__((amdgpu_max_num_work_groups(<x>,<y>,<z>)))
or[[clang::amdgpu_max_num_work_groups(<x>,<y>,<z>)]]
attribute for theAMDGPU target. This attribute may be attached to HIP or OpenCL kernel functiondefinitions and is an optimization hint.
The<x>
parameter specifies the maximum number of work groups in the x dimension.Similarly<y>
and<z>
are for the y and z dimensions respectively.Each of the three values must be greater than 0 when provided. The<x>
parameteris required, while<y>
and<z>
are optional with default value of 1.
If specified, the AMDGPU target backend might be able to produce better machinecode.
- An error will be given if:
Specified values violate subtarget specifications;
Specified values are not compatible with values provided through otherattributes.
amdgpu_num_sgpr, amdgpu_num_vgpr¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
Clang supports the__attribute__((amdgpu_num_sgpr(<num_sgpr>)))
and__attribute__((amdgpu_num_vgpr(<num_vgpr>)))
attributes for the AMDGPUtarget. These attributes may be attached to a kernel function definition and arean optimization hint.
If these attributes are specified, then the AMDGPU target backend will attemptto limit the number of SGPRs and/or VGPRs used to the specified value(s). Thenumber of used SGPRs and/or VGPRs may further be rounded up to satisfy theallocation requirements or constraints of the subtarget. Passing0
asnum_sgpr
and/ornum_vgpr
implies the default behavior (no limits).
These attributes can be used to test the AMDGPU target backend. It isrecommended that theamdgpu_waves_per_eu
attribute be used to controlresources such as SGPRs and VGPRs since it is aware of the limits for differentsubtargets.
- An error will be given if:
Specified values violate subtarget specifications;
Specified values are not compatible with values provided through otherattributes;
The AMDGPU target backend is unable to create machine code that can meet therequest.
amdgpu_waves_per_eu¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
A compute unit (CU) is responsible for executing the wavefronts of a work-group.It is composed of one or more execution units (EU), which are responsible forexecuting the wavefronts. An EU can have enough resources to maintain the stateof more than one executing wavefront. This allows an EU to hide latency byswitching between wavefronts in a similar way to symmetric multithreading on aCPU. In order to allow the state for multiple wavefronts to fit on an EU, theresources used by a single wavefront have to be limited. For example, the numberof SGPRs and VGPRs. Limiting such resources can allow greater latency hiding,but can result in having to spill some register state to memory.
Clang supports the__attribute__((amdgpu_waves_per_eu(<min>[,<max>])))
attribute for the AMDGPU target. This attribute may be attached to a kernelfunction definition and is an optimization hint.
<min>
parameter specifies the requested minimum number of waves per EU, andoptional<max>
parameter specifies the requested maximum number of wavesper EU (must be greater than<min>
if specified). If<max>
is omitted,then there is no restriction on the maximum number of waves per EU other thanthe one dictated by the hardware for which the kernel is compiled. Passing0,0
as<min>,<max>
implies the default behavior (no limits).
If specified, this attribute allows an advanced developer to tune the number ofwavefronts that are capable of fitting within the resources of an EU. The AMDGPUtarget backend can use this information to limit resources, such as number ofSGPRs, number of VGPRs, size of available group and private memory segments, insuch a way that guarantees that at least<min>
wavefronts and at most<max>
wavefronts are able to fit within the resources of an EU. Requestingmore wavefronts can hide memory latency but limits available registers whichcan result in spilling. Requesting fewer wavefronts can help reduce cachethrashing, but can reduce memory latency hiding.
This attribute controls the machine code generated by the AMDGPU target backendto ensure it is capable of meeting the requested values. However, when thekernel is executed, there may be other reasons that prevent meeting the request,for example, there may be wavefronts from other kernels executing on the EU.
- An error will be given if:
Specified values violate subtarget specifications;
Specified values are not compatible with values provided through otherattributes;
The AMDGPU target backend will emit a warning whenever it is unable tocreate machine code that meets the request.
Calling Conventions¶
Clang supports several different calling conventions, depending on the targetplatform and architecture. The calling convention used for a function determineshow parameters are passed, how results are returned to the caller, and otherlow-level details of calling a function.
aarch64_sve_pcs¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
On AArch64 targets, this attribute changes the calling convention of afunction to preserve additional Scalable Vector registers and ScalablePredicate registers relative to the default calling convention used forAArch64.
This means it is more efficient to call such functions from code that performsextensive scalable vector and scalable predicate calculations, because fewerlive SVE registers need to be saved. This property makes it well-suited for SVEmath library functions, which are typically leaf functions that require a smallnumber of registers.
However, using this attribute also means that it is more expensive to calla function that adheres to the default calling convention from within sucha function. Therefore, it is recommended that this attribute is only usedfor leaf functions.
For more information, see the documentation foraarch64_sve_pcs in theARM C Language Extension (ACLE) documentation.
aarch64_vector_pcs¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
On AArch64 targets, this attribute changes the calling convention of afunction to preserve additional floating-point and Advanced SIMD registersrelative to the default calling convention used for AArch64.
This means it is more efficient to call such functions from code that performsextensive floating-point and vector calculations, because fewer live SIMD and FPregisters need to be saved. This property makes it well-suited for e.g.floating-point or vector math library functions, which are typically leaffunctions that require a small number of registers.
However, using this attribute also means that it is more expensive to calla function that adheres to the default calling convention from within sucha function. Therefore, it is recommended that this attribute is only usedfor leaf functions.
For more information, see the documentation foraarch64_vector_pcs onthe Arm Developer website.
fastcall¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
On 32-bit x86 targets, this attribute changes the calling convention of afunction to use ECX and EDX as register parameters and clear parameters off ofthe stack on return. This convention does not support variadic calls orunprototyped functions in C, and has no effect on x86_64 targets. This callingconvention is supported primarily for compatibility with existing code. Usersseeking register parameters should use theregparm
attribute, which doesnot require callee-cleanup. See the documentation for__fastcall on MSDN.
m68k_rtd¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
On M68k targets, this attribute changes the calling convention of a functionto clear parameters off the stack on return. In other words, callee isresponsible for cleaning out the stack space allocated for incoming paramters.This convention does not support variadic calls or unprototyped functions in C.When targeting M68010 or newer CPUs, this calling convention is implementedusing thertd instruction.
ms_abi¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
On non-Windows x86_64 targets, this attribute changes the calling convention ofa function to match the default convention used on Windows x86_64. Thisattribute has no effect on Windows targets or non-x86_64 targets.
pcs¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
On ARM targets, this attribute can be used to select calling conventionssimilar tostdcall
on x86. Valid parameter values are “aapcs” and“aapcs-vfp”.
preserve_all¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
On X86-64 and AArch64 targets, this attribute changes the calling convention ofa function. Thepreserve_all
calling convention attempts to make the codein the caller even less intrusive than thepreserve_most
calling convention.This calling convention also behaves identical to theC
calling conventionon how arguments and return values are passed, but it uses a different set ofcaller/callee-saved registers. This removes the burden of saving andrecovering a large register set before and after the call in the caller. Ifthe arguments are passed in callee-saved registers, then they will bepreserved by the callee across the call. This doesn’t apply for valuesreturned in callee-saved registers.
On X86-64 the callee preserves all general purpose registers, except forR11. R11 can be used as a scratch register. Furthermore it also preservesall floating-point registers (XMMs/YMMs).
On AArch64 the callee preserve all general purpose registers, except X0-X8 andX16-X18. Furthermore it also preserves lower 128 bits of V8-V31 SIMD - floatingpoint registers.
The idea behind this convention is to support calls to runtime functionsthat don’t need to call out to any other functions.
This calling convention, like thepreserve_most
calling convention, will beused by a future version of the Objective-C runtime and should be consideredexperimental at this time.
preserve_most¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
On X86-64 and AArch64 targets, this attribute changes the calling convention ofa function. Thepreserve_most
calling convention attempts to make the codein the caller as unintrusive as possible. This convention behaves identicallyto theC
calling convention on how arguments and return values are passed,but it uses a different set of caller/callee-saved registers. This alleviatesthe burden of saving and recovering a large register set before and after thecall in the caller. If the arguments are passed in callee-saved registers,then they will be preserved by the callee across the call. This doesn’tapply for values returned in callee-saved registers.
On X86-64 the callee preserves all general purpose registers, except forR11. R11 can be used as a scratch register. Floating-point registers(XMMs/YMMs) are not preserved and need to be saved by the caller.
On AArch64 the callee preserve all general purpose registers, except X0-X8 andX16-X18.
The idea behind this convention is to support calls to runtime functionsthat have a hot path and a cold path. The hot path is usually a small pieceof code that doesn’t use many registers. The cold path might need to call out toanother function and therefore only needs to preserve the caller-savedregisters, which haven’t already been saved by the caller. Thepreserve_most
calling convention is very similar to thecold
callingconvention in terms of caller/callee-saved registers, but they are used fordifferent types of function calls.coldcc
is for function calls that arerarely executed, whereaspreserve_most
function calls are intended to beon the hot path and definitely executed a lot. Furthermorepreserve_most
doesn’t prevent the inliner from inlining the function call.
This calling convention will be used by a future version of the Objective-Cruntime and should therefore still be considered experimental at this time.Although this convention was created to optimize certain runtime calls tothe Objective-C runtime, it is not limited to this runtime and might be usedby other runtimes in the future too. The current implementation onlysupports X86-64 and AArch64, but the intention is to support more architecturesin the future.
preserve_none¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
On X86-64 and AArch64 targets, this attribute changes the calling convention of a function.Thepreserve_none
calling convention tries to preserve as few generalregisters as possible. So all general registers are caller saved registers. Italso uses more general registers to pass arguments. This attribute doesn’timpact floating-point registers.preserve_none
’s ABI is still unstable, andmay be changed in the future.
On X86-64, only RSP and RBP are preserved by the callee.Registers R12, R13, R14, R15, RDI, RSI, RDX, RCX, R8, R9, R11, and RAX now canbe used to pass function arguments. Floating-point registers (XMMs/YMMs) stillfollow the C calling convention.
On AArch64, only LR and FP are preserved by the callee.Registers X20-X28, X0-X7, and X9-X14 are used to pass function arguments.X8, X16-X19, SIMD and floating-point registers follow the AAPCS callingconvention. X15 is not available for argument passing on Windows, but isused to pass arguments on other platforms.
regcall¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
On x86 targets, this attribute changes the calling convention to__regcall convention. This convention aims to pass as many argumentsas possible in registers. It also tries to utilize registers for thereturn value whenever it is possible.
regparm¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
On 32-bit x86 targets, the regparm attribute causes the compiler to passthe first three integer parameters in EAX, EDX, and ECX instead of on thestack. This attribute has no effect on variadic functions, and all parametersare passed via the stack as normal.
riscv::vector_cc, riscv_vector_cc, clang::riscv_vector_cc¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Theriscv_vector_cc
attribute can be applied to a function. It preserves 15registers namely, v1-v7 and v24-v31 as callee-saved. Callers thus don’t needto save these registers before function calls, and callees only need to savethem if they use them.
riscv::vls_cc, riscv_vls_cc, clang::riscv_vls_cc¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Theriscv_vls_cc
attribute can be applied to a function. Functionsdeclared with this attribute will utilize the standard fixed-length vectorcalling convention variant instead of the default calling convention defined bythe ABI. This variant aims to pass fixed-length vectors via vector registers,if possible, rather than through general-purpose registers.
stdcall¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
On 32-bit x86 targets, this attribute changes the calling convention of afunction to clear parameters off of the stack on return. This convention doesnot support variadic calls or unprototyped functions in C, and has no effect onx86_64 targets. This calling convention is used widely by the Windows API andCOM applications. See the documentation for__stdcall on MSDN.
sysv_abi¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
On Windows x86_64 targets, this attribute changes the calling convention of afunction to match the default convention used on Sys V targets such as Linux,Mac, and BSD. This attribute has no effect on other targets.
thiscall¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
On 32-bit x86 targets, this attribute changes the calling convention of afunction to use ECX for the first parameter (typically the implicitthis
parameter of C++ methods) and clear parameters off of the stack on return. Thisconvention does not support variadic calls or unprototyped functions in C, andhas no effect on x86_64 targets. See the documentation for__thiscall onMSDN.
vectorcall¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
On 32-bit x86and x86_64 targets, this attribute changes the callingconvention of a function to pass vector parameters in SSE registers.
On 32-bit x86 targets, this calling convention is similar to__fastcall
.The first two integer parameters are passed in ECX and EDX. Subsequent integerparameters are passed in memory, and callee clears the stack. On x86_64targets, the callee doesnot clear the stack, and integer parameters arepassed in RCX, RDX, R8, and R9 as is done for the default Windows x64 callingconvention.
On both 32-bit x86 and x86_64 targets, vector and floating point arguments arepassed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements arepassed in sequential SSE registers if enough are available. If AVX is enabled,256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type thatcannot be passed in registers for any reason is passed by reference, whichallows the caller to align the parameter memory.
See the documentation for__vectorcall on MSDN for more details.
Consumed Annotation Checking¶
Clang supports additional attributes for checking basic resource managementproperties, specifically for unique objects that have a single owning reference.The following attributes are currently supported, althoughthe implementationfor these annotations is currently in development and are subject to change.
callable_when¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
Use__attribute__((callable_when(...)))
to indicate what states a methodmay be called in. Valid states are unconsumed, consumed, or unknown. Eachargument to this attribute must be a quoted string. E.g.:
__attribute__((callable_when("unconsumed","unknown")))
consumable¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
Eachclass
that uses any of the typestate annotations must first be markedusing theconsumable
attribute. Failure to do so will result in a warning.
This attribute accepts a single parameter that must be one of the following:unknown
,consumed
, orunconsumed
.
param_typestate¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
This attribute specifies expectations about function parameters. Calls to anfunction with annotated parameters will issue a warning if the correspondingargument isn’t in the expected state. The attribute is also used to set theinitial state of the parameter when analyzing the function’s body.
return_typestate¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
Thereturn_typestate
attribute can be applied to functions or parameters.When applied to a function the attribute specifies the state of the returnedvalue. The function’s body is checked to ensure that it always returns a valuein the specified state. On the caller side, values returned by the annotatedfunction are initialized to the given state.
When applied to a function parameter it modifies the state of an argument aftera call to the function returns. The function’s body is checked to ensure thatthe parameter is in the expected state before returning.
set_typestate¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
Annotate methods that transition an object into a new state with__attribute__((set_typestate(new_state)))
. The new state must beunconsumed, consumed, or unknown.
test_typestate¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
Use__attribute__((test_typestate(tested_state)))
to indicate that a methodreturns true if the object is in the specified state..
Customizing Swift Import¶
Clang supports additional attributes for customizing how APIs are imported intoSwift.
swift_async¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theswift_async
attribute specifies if and how a particular function orObjective-C method is imported into a swift async method. For instance:
@interfaceMyClass :NSObject-(void)notActuallyAsync:(int)p1withCompletionHandler:(void(^)())handler__attribute__((swift_async(none)));-(void)actuallyAsync:(int)p1callThisAsync:(void(^)())fun__attribute__((swift_async(swift_private,1)));@end
Here,notActuallyAsync:withCompletionHandler
would have been imported asasync
(because it’s last parameter’s selector piece iswithCompletionHandler
) if not for theswift_async(none)
attribute.Conversely,actuallyAsync:callThisAsync
wouldn’t have been imported asasync
if not for theswift_async
attribute because it doesn’t match thenaming convention.
When usingswift_async
to enable importing, the first argument to theattribute is eitherswift_private
ornot_swift_private
to indicatewhether the function/method is private to the current framework, and the secondargument is the index of the completion handler parameter.
swift_async_error¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theswift_async_error
attribute specifies how an error state will berepresented in a swift async method. It’s a bit analogous to theswift_error
attribute for the generated async method. Theswift_async_error
attributecan indicate a variety of different ways of representing an error.
__attribute__((swift_async_error(zero_argument,N)))
, specifies that theasync method is considered to have failed if the Nth argument to thecompletion handler is zero.__attribute__((swift_async_error(nonzero_argument,N)))
, specifies thatthe async method is considered to have failed if the Nth argument to thecompletion handler is non-zero.__attribute__((swift_async_error(nonnull_error)))
, specifies that theasync method is considered to have failed if theNSError*
argument to thecompletion handler is non-null.__attribute__((swift_async_error(none)))
, specifies that the async methodcannot fail.
For instance:
@interfaceMyClass :NSObject-(void)asyncMethod:(void(^)(char,int,float))handler__attribute__((swift_async(swift_private,1)))__attribute__((swift_async_error(zero_argument,2)));@end
Here, theswift_async
attribute specifies thathandler
is the completionhandler for this method, and theswift_async_error
attribute specifies thattheint
parameter is the one that represents the error.
swift_async_name¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
Theswift_async_name
attribute provides the name of theasync
overload forthe given declaration in Swift. If this attribute is absent, the name istransformed according to the algorithm built into the Swift compiler.
The argument is a string literal that contains the Swift name of the function ormethod. The name may be a compound Swift name. The function or method with suchan attribute must have more than zero parameters, as its last parameter isassumed to be a callback that’s eliminated in the Swiftasync
name.
@interfaceURL+(void)loadContentsFrom:(URL*)urlcallback:(void(^)(NSData*))data__attribute__((__swift_async_name__("URL.loadContentsFrom(_:)")))@end
swift_attr¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
Theswift_attr
provides a Swift-specific annotation for the declarationor type to which the attribute appertains to. It can be used on any declarationor type in Clang. This kind of annotation is ignored by Clang as it doesn’t have anysemantic meaning in languages supported by Clang. The Swift compiler caninterpret these annotations according to its own rules when importing C orObjective-C declarations.
swift_bridge¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
Theswift_bridge
attribute indicates that the declaration to which theattribute appertains is bridged to the named Swift type.
__attribute__((__objc_root__))@interfaceBase-(instancetype)init;@end__attribute__((__swift_bridge__("BridgedI")))@interfaceI :Base@end
In this example, the Objective-C interfaceI
will be made available to Swiftwith the nameBridgedI
. It would be possible for the compiler to refer toI
still in order to bridge the type back to Objective-C.
swift_bridged¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
Theswift_bridged_typedef
attribute indicates that when the typedef to whichthe attribute appertains is imported into Swift, it should refer to the bridgedSwift type (e.g. Swift’sString
) rather than the Objective-C type as written(e.g.NSString
).
@interfaceNSString;typedefNSString*AliasedString__attribute__((__swift_bridged_typedef__));externvoidacceptsAliasedString(AliasedString_Nonnullparameter);
In this case, the functionacceptsAliasedString
will be imported into Swiftas a function which accepts aString
type parameter.
swift_error¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
Theswift_error
attribute controls whether a particular function (orObjective-C method) is imported into Swift as a throwing function, and if so,which dynamic convention it uses.
All of these conventions exceptnone
require the function to have an errorparameter. Currently, the error parameter is always the last parameter of typeNSError**
orCFErrorRef*
. Swift will remove the error parameter fromthe imported API. When calling the API, Swift will always pass a valid addressinitialized to a null pointer.
swift_error(none)
means that the function should not be imported asthrowing. The error parameter and result type will be imported normally.swift_error(null_result)
means that calls to the function should beconsidered to have thrown if they return a null value. The return type must bea pointer type, and it will be imported into Swift with a non-optional type.This is the default error convention for Objective-C methods that returnpointers.swift_error(zero_result)
means that calls to the function should beconsidered to have thrown if they return a zero result. The return type must bean integral type. If the return type would have been imported asBool
, itis instead imported asVoid
. This is the default error convention forObjective-C methods that return a type that would be imported asBool
.swift_error(nonzero_result)
means that calls to the function should beconsidered to have thrown if they return a non-zero result. The return type mustbe an integral type. If the return type would have been imported asBool
,it is instead imported asVoid
.swift_error(nonnull_error)
means that calls to the function should beconsidered to have thrown if they leave a non-null error in the error parameter.The return type is left unmodified.
swift_name¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
Theswift_name
attribute provides the name of the declaration in Swift. Ifthis attribute is absent, the name is transformed according to the algorithmbuilt into the Swift compiler.
The argument is a string literal that contains the Swift name of the function,variable, or type. When renaming a function, the name may be a compound Swiftname. For a type, enum constant, property, or variable declaration, the namemust be a simple or qualified identifier.
@interfaceURL-(void)initWithString:(NSString*)s__attribute__((__swift_name__("URL.init(_:)")))@endvoid__attribute__((__swift_name__("squareRoot()")))sqrt(doublev){}
swift_newtype¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
Theswift_newtype
attribute indicates that the typedef to which theattribute appertains is imported as a new Swift type of the typedef’s name.Previously, the attribute was speltswift_wrapper
. While the behaviour ofthe attribute is identical with either spelling,swift_wrapper
isdeprecated, only exists for compatibility purposes, and should not be used innew code.
swift_newtype(struct)
means that a Swift struct will be created for thistypedef.swift_newtype(enum)
means that a Swift enum will be created for thistypedef.// Import UIFontTextStyle as an enum type, with enumerated values being// constants.typedefNSString*UIFontTextStyle__attribute__((__swift_newtype__(enum)));// Import UIFontDescriptorFeatureKey as a structure type, with enumerated// values being members of the type structure.typedefNSString*UIFontDescriptorFeatureKey__attribute__((__swift_newtype__(struct)));
swift_objc_members¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
This attribute indicates that Swift subclasses and members of Swift extensionsof this class will be implicitly marked with the@objcMembers
Swiftattribute, exposing them back to Objective-C.
swift_private¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
Declarations marked with theswift_private
attribute are hidden from theframework client but are still made available for use within the framework orSwift SDK overlay.
The purpose of this attribute is to permit a more idomatic implementation ofdeclarations in Swift while hiding the non-idiomatic one.
Declaration Attributes¶
Owner¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
Note
This attribute is experimental and its effect on analysis is subject to change ina future version of clang.
The attribute[[gsl::Owner(T)]]
applies to structs and classes that own anobject of typeT
:
class [[gsl::Owner(int)]] IntOwner {private: int value;public: int *getInt() { return &value; }};
The argumentT
is optional and is ignored.This attribute may be used by analysis tools and has no effect on codegeneration. Avoid
argument means that the class can own any type.
SeePointer for an example.
Pointer¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
Note
This attribute is experimental and its effect on analysis is subject to change ina future version of clang.
The attribute[[gsl::Pointer(T)]]
applies to structs and classes that behavelike pointers to an object of typeT
:
class [[gsl::Pointer(int)]] IntPointer {private: int *valuePointer;public: IntPointer(const IntOwner&); int *getInt() { return valuePointer; }};
The argumentT
is optional and is ignored.This attribute may be used by analysis tools and has no effect on codegeneration. Avoid
argument means that the pointer can point to any type.
Example:When constructing an instance of a class annotated like this (a Pointer) froman instance of a class annotated with[[gsl::Owner]]
(an Owner),then the analysis will consider the Pointer to point inside the Owner.When the Owner’s lifetime ends, it will consider the Pointer to be dangling.
intf(){IntPointerP(IntOwner{});// P "points into" a temporary IntOwner objectP.getInt();// P is dangling}
If a template class is annotated with[[gsl::Owner]]
, and the firstinstantiated template argument is a pointer type (raw pointer, or[[gsl::Pointer]]
),the analysis will consider the instantiated class as a container of the pointer.When constructing such an object from a GSL owner object, the analysis willassume that the container holds a pointer to the owner object. Consequently,when the owner object is destroyed, the pointer will be considered dangling.
intf(){std::vector<std::string_view>v={std::string()};// v holds a dangling pointer.std::optional<std::string_view>o=std::string();// o holds a dangling pointer.}
__single_inheritance, __multiple_inheritance, __virtual_inheritance¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
This collection of keywords is enabled under-fms-extensions
and controlsthe pointer-to-member representation used on*-*-win32
targets.
The*-*-win32
targets utilize a pointer-to-member representation whichvaries in size and alignment depending on the definition of the underlyingclass.
However, this is problematic when a forward declaration is only available andno definition has been made yet. In such cases, Clang is forced to utilize themost general representation that is available to it.
These keywords make it possible to use a pointer-to-member representation otherthan the most general one regardless of whether or not the definition will everbe present in the current translation unit.
This family of keywords belong between theclass-key
andclass-name
:
struct__single_inheritanceS;intS::*i;structS{};
This keyword can be applied to class templates but only has an effect when usedon full specializations:
template<typenameT,typenameU>struct__single_inheritanceA;// warning: inheritance model ignored on primary templatetemplate<typenameT>struct__multiple_inheritanceA<T,T>;// warning: inheritance model ignored on partial specializationtemplate<>struct__single_inheritanceA<int,float>;
Note that choosing an inheritance model less general than strictly necessary isan error:
struct__multiple_inheritanceS;// error: inheritance model does not match definitionintS::*i;structS{};
asm¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
This attribute can be used on a function or variable to specify its symbol name.
On some targets, all C symbols are prefixed by default with a single character,typically_
. This was done historically to distinguish them from symbolsused by other languages. (This prefix is also added to the standard ItaniumC++ ABI prefix on “mangled” symbol names, so that e.g. on such targets the truesymbol name for a C++ variable declared asintcppvar;
would be__Z6cppvar
; note the two underscores.) This prefix isnot added to thesymbol names specified by theasm
attribute; programmers wishing to match aC symbol name must compensate for this.
For example, consider the following C code:
intvar1asm("altvar")=1;// "altvar" in symbol table.intvar2=1;// "_var2" in symbol table.voidfunc1(void)asm("altfunc");voidfunc1(void){}// "altfunc" in symbol table.voidfunc2(void){}// "_func2" in symbol table.
Clang’s implementation of this attribute is compatible with GCC’s,documented here.
While it is possible to use this attribute to name a special symbol usedinternally by the compiler, such as an LLVM intrinsic, this is neitherrecommended nor supported and may cause the compiler to crash or miscompile.Users who wish to gain access to intrinsic behavior are strongly encouraged torequest new builtin functions.
coro_await_elidable¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
The[[clang::coro_await_elidable]]
is a class attribute which can beapplied to a coroutine return type. It provides a hint to the compiler to applyHeap Allocation Elision more aggressively.
When a coroutine function returns such a type, a direct call expression thereinthat returns a prvalue of a type attributed[[clang::coro_await_elidable]]
is said to be under a safe elide context if one of the following is true:- it is the immediate right-hand side operand to a co_await expression.- it is an argument to a[[clang::coro_await_elidable_argument]]
parameteror parameter pack of another direct call expression under a safe elide context.
Do note that the safe elide context applies only to the call expression itself,and the context does not transitively include any of its subexpressions unlessexceptional rules of[[clang::coro_await_elidable_argument]]
apply.
The compiler performs heap allocation elision on call expressions under a safeelide context, if the callee is a coroutine.
Example:
class[[clang::coro_await_elidable]]Task{...};Taskfoo();Taskbar(){co_awaitfoo();// foo()'s coroutine frame on this line is elidableautot=foo();// foo()'s coroutine frame on this line is NOT elidableco_awaitt;}
Such elision replaces the heap allocated activation frame of the callee coroutinewith a local variable within the enclosing braces in the caller’s stack frame.The local variable, like other variables in coroutines, may be collected into thecoroutine frame, which may be allocated on the heap. The behavior is undefinedif the caller coroutine is destroyed earlier than the callee coroutine.
coro_await_elidable_argument¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
The[[clang::coro_await_elidable_argument]]
is a function parameter attribute.It works in conjunction with[[clang::coro_await_elidable]]
to propagate asafe elide context to a parameter or parameter pack if the function is calledunder a safe elide context.
This is sometimes necessary on utility functions used to compose or modify thebehavior of a callee coroutine.
Example:
template<typenameT>class[[clang::coro_await_elidable]]Task{...};template<typename...T>class[[clang::coro_await_elidable]]WhenAll{...};// `when_all` is a utility function that composes coroutines. It does not// need to be a coroutine to propagate.template<typename...T>WhenAll<T...>when_all([[clang::coro_await_elidable_argument]]Task<T>tasks...);Task<int>foo();Task<int>bar();Task<void>example1(){// `when_all``, `foo``, and `bar` are all elide safe because `when_all` is// under a safe elide context and, thanks to the [[clang::coro_await_elidable_argument]]// attribute, such context is propagated to foo and bar.co_awaitwhen_all(foo(),bar());}Task<void>example2(){// `when_all` and `bar` are elide safe. `foo` is not elide safe.autof=foo();co_awaitwhen_all(f,bar());}Task<void>example3(){// None of the calls are elide safe.autot=when_all(foo(),bar());co_awaitt;}
coro_disable_lifetimebound, coro_lifetimebound¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
The[[clang::coro_lifetimebound]]
is a class attribute which can be appliedto a coroutine return type (coro_return_type, coro_wrapper) (i.e.it should also be annotated with[[clang::coro_return_type]]
).
All parameters of a function are considered to be lifetime bound if the function returns acoroutine return type (CRT) annotated with[[clang::coro_lifetimebound]]
.This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the functionwith[[clang::coro_disable_lifetimebound]]
function attribute .See documentation oflifetimebound for details about lifetime bound analysis.
Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
For example,
task<int>coro(constint&a){co_returna+1;}task<int>dangling_refs(inta){// `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.autofoo=coro(1);// `coro` captures reference to local variable `a` which is destroyed after the return.returncoro(a);}
Lifetime bound static analysis can be used to detect such instances when coroutines capture referenceswhich may die earlier than the coroutine frame itself. In the above example, if the CRTtask is annotated with[[clang::coro_lifetimebound]]
, then lifetime bound analysis would detect capturing reference totemporaries or return address of a local variable.
Both coroutines and coroutine wrappers are part of this analysis.
template<typenameT>struct[[clang::coro_return_type,clang::coro_lifetimebound]]Task{usingpromise_type=some_promise_type;};Task<int>coro(constint&a){co_returna+1;}[[clang::coro_wrapper]]Task<int>coro_wrapper(constint&a,constint&b){returna>b?coro(a):coro(b);}Task<int>temporary_reference(){autofoo=coro(1);// warning: capturing reference to a temporary which would die after the expression.inta=1;autobar=coro_wrapper(a,0);// warning: `b` captures reference to a temporary.co_returnco_awaitcoro(1);// fine.}[[clang::coro_wrapper]]Task<int>stack_reference(inta){returncoro(a);// warning: returning address of stack variable `a`.}
This analysis can be disabled for all calls to a particular function by annotating the functionwith function attribute[[clang::coro_disable_lifetimebound]]
.For example, this could be useful for coroutine wrappers which accept reference parametersbut do not pass them to the underlying coroutine or pass them by value.
Task<int>coro(inta){co_returna+1;}[[clang::coro_wrapper,clang::coro_disable_lifetimebound]]Task<int>coro_wrapper(constint&a){returncoro(a+1);}voiduse(){autotask=coro_wrapper(1);// use of temporary is fine as the argument is not lifetime bound.}
coro_only_destroy_when_complete¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Thecoro_only_destroy_when_complete attribute should be marked on a C++ class. The coroutineswhose return type is marked with the attribute are assumed to be destroyed only after the coroutine hasreached the final suspend point.
This is helpful for the optimizers to reduce the size of the destroy function for the coroutines.
For example,
Afoo(){dtord;co_awaitsomething();dtord1;co_awaitsomething();dtord2;co_return43;}
The compiler may generate the following pseudocode:
voidfoo.destroy(foo.Frame*frame){switch(frame->suspend_index()){case1:frame->d.~dtor();break;case2:frame->d.~dtor();frame->d1.~dtor();break;case3:frame->d.~dtor();frame->d1.~dtor();frame->d2.~dtor();break;default:// coroutine completed or haven't startedbreak;}frame->promise.~promise_type();deleteframe;}
Thefoo.destroy() function’s purpose is to release all of the resourcesinitialized for the coroutine when it is destroyed in a suspended state.However, if the coroutine is only ever destroyed at the final suspend state,the rest of the conditions are superfluous.
The user can use thecoro_only_destroy_when_complete attributo suppressgeneration of the other destruction cases, optimizing the abovefoo.destroy to:
voidfoo.destroy(foo.Frame*frame){frame->promise.~promise_type();deleteframe;}
coro_return_type, coro_wrapper¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
The[[clang::coro_return_type]]
attribute is used to help static analyzers to recognizecoroutines from the function signatures.
Thecoro_return_type
attribute should be marked on a C++ class to mark it asacoroutine return type (CRT).
A functionRfunc(P1,..,PN)
has a coroutine return type (CRT)R
ifR
is marked by[[clang::coro_return_type]]
andR
has a promise type associated to it(i.e., std::coroutine_traits<R, P1, .., PN>::promise_type is a valid promise type).
If the return type of a function is aCRT
then the function must be a coroutine.Otherwise the program is invalid. It is allowed for a non-coroutine to return aCRT
if the function is marked with[[clang::coro_wrapper]]
.
The[[clang::coro_wrapper]]
attribute should be marked on a C++ function to mark it asacoroutine wrapper. A coroutine wrapper is a function which returns aCRT
,is not a coroutine itself and is marked with[[clang::coro_wrapper]]
.
Clang will enforce that all functions that return aCRT
are either coroutines or markedwith[[clang::coro_wrapper]]
. Clang will enforce this with an error.
From a language perspective, it is not possible to differentiate between a coroutine and afunction returning a CRT by merely looking at the function signature.
Coroutine wrappers, in particular, are susceptible to capturingreferences to temporaries and other lifetime issues. This allows to avoid such lifetimeissues with coroutine wrappers.
For example,
// This is a CRT.template<typenameT>struct[[clang::coro_return_type]]Task{usingpromise_type=some_promise_type;};Task<int>increment(inta){co_returna+1;}// Fine. This is a coroutine.Task<int>foo(){returnincrement(1);}// Error. foo is not a coroutine.// Fine for a coroutine wrapper to return a CRT.[[clang::coro_wrapper]]Task<int>foo(){returnincrement(1);}voidbar(){// Invalid. This intantiates a function which returns a CRT but is not marked as// a coroutine wrapper.std::function<Task<int>(int)>f=increment;}
Note:a_promise_type::get_return_object
is exempted from this analysis as it is a necessaryimplementation detail of any coroutine library.
deprecated¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
Thedeprecated
attribute can be applied to a function, a variable, or atype. This is useful when identifying functions, variables, or types that areexpected to be removed in a future version of a program.
Consider the function declaration for a hypothetical functionf
:
voidf(void)__attribute__((deprecated("message","replacement")));
When spelled as__attribute__((deprecated))
, the deprecated attribute can havetwo optional string arguments. The first one is the message to display whenemitting the warning; the second one enables the compiler to provide a Fix-Itto replace the deprecated name with a new name. Otherwise, when spelled as[[gnu::deprecated]]
or[[deprecated]]
, the attribute can have one optionalstring argument which is the message to display when emitting the warning.
empty_bases¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The empty_bases attribute permits the compiler to utilize theempty-base-optimization more frequently.This attribute only applies to struct, class, and union types.It is only supported when using the Microsoft C++ ABI.
enum_extensibility¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Attributeenum_extensibility
is used to distinguish between enum definitionsthat are extensible and those that are not. The attribute can take eitherclosed
oropen
as an argument.closed
indicates a variable of theenum type takes a value that corresponds to one of the enumerators listed in theenum definition or, when the enum is annotated withflag_enum
, a value thatcan be constructed using values corresponding to the enumerators.open
indicates a variable of the enum type can take any values allowed by thestandard and instructs clang to be more lenient when issuing warnings.
enum__attribute__((enum_extensibility(closed)))ClosedEnum{A0,A1};enum__attribute__((enum_extensibility(open)))OpenEnum{B0,B1};enum__attribute__((enum_extensibility(closed),flag_enum))ClosedFlagEnum{C0=1<<0,C1=1<<1};enum__attribute__((enum_extensibility(open),flag_enum))OpenFlagEnum{D0=1<<0,D1=1<<1};voidfoo1(){enumClosedEnumce;enumOpenEnumoe;enumClosedFlagEnumcfe;enumOpenFlagEnumofe;ce=A1;// no warningsce=100;// warning issuedoe=B1;// no warningsoe=100;// no warningscfe=C0|C1;// no warningscfe=C0|C1|4;// warning issuedofe=D0|D1;// no warningsofe=D0|D1|4;// no warnings}
external_source_symbol¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theexternal_source_symbol
attribute specifies that a declaration originatesfrom an external source and describes the nature of that source.
The fact that Clang is capable of recognizing declarations that were definedexternally can be used to provide better tooling support for mixed-languageprojects or projects that rely on auto-generated code. For instance, an IDE thatuses Clang and that supports mixed-language projects can use this attribute toprovide a correct ‘jump-to-definition’ feature. For a concrete example,consider a protocol that’s defined in a Swift file:
@objcpublicprotocolSwiftProtocol{funcmethod()}
This protocol can be used from Objective-C code by including a header file thatwas generated by the Swift compiler. The declarations in that header can usetheexternal_source_symbol
attribute to make Clang aware of the factthatSwiftProtocol
actually originates from a Swift module:
__attribute__((external_source_symbol(language="Swift",defined_in="module")))@protocolSwiftProtocol@required-(void)method;@end
Consequently, when ‘jump-to-definition’ is performed at a location thatreferencesSwiftProtocol
, the IDE can jump to the original definition inthe Swift source file rather than jumping to the Objective-C declaration in theauto-generated header file.
Theexternal_source_symbol
attribute is a comma-separated list that includesclauses that describe the origin and the nature of the particular declaration.Those clauses can be:
- language=string-literal
The name of the source language in which this declaration was defined.
- defined_in=string-literal
The name of the source container in which the declaration was defined. Theexact definition of source container is language-specific, e.g. Swift’ssource containers are modules, so
defined_in
should specify the Swiftmodule name.- USR=string-literal
String that specifies a unified symbol resolution (USR) value for thisdeclaration. USR string uniquely identifies this particular declaration, andis typically used when constructing an index of a codebase.The USR value in this attribute is expected to be generated by an externalcompiler that compiled the native declaration using its original sourcelanguage. The exact format of the USR string and its other attributesare determined by the specification of this declaration’s source language.When not specified, Clang’s indexer will use the Clang USR for this symbol.User can query to see if Clang supports the use of the
USR
clause intheexternal_source_symbol
attribute with__has_attribute(external_source_symbol)>=20230206
.- generated_declaration
This declaration was automatically generated by some tool.
The clauses can be specified in any order. The clauses that are listed above areall optional, but the attribute has to have at least one clause.
flag_enum¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
This attribute can be added to an enumerator to signal to the compiler that itis intended to be used as a flag type. This will cause the compiler to assumethat the range of the type includes all of the values that you can get bymanipulating bits of the enumerator when issuing warnings.
grid_constant¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
The__grid_constant__
attribute can be applied to aconst
-qualified kernelfunction argument and allows compiler to take the address of that argument withoutmaking a copy. The argument applies to sm_70 or newer GPUs, during compilationwith CUDA-11.7(PTX 7.7) or newer, and is ignored otherwise.
layout_version¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The layout_version attribute requests that the compiler utilize the classlayout rules of a particular compiler version.This attribute only applies to struct, class, and union types.It is only supported when using the Microsoft C++ ABI.
lto_visibility_public¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
SeeLTO Visibility.
managed¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
The__managed__
attribute can be applied to a global variable declaration in HIP.A managed variable is emitted as an undefined global symbol in the device binary and isregistered by__hipRegisterManagedVariable
in init functions. The HIP runtime allocatesmanaged memory and uses it to define the symbol when loading the device binary.A managed variable can be accessed in both device and host code.
no_init_all¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__declspec(no_init_all)
attribute disables the automatic initialization that the-ftrivial-auto-var-init flag would have applied to locals in a marked function, or instances ofa marked type. Note that this attribute has no effect for locals that are automatically initializedwithout the-ftrivial-auto-var-init flag.
no_specializations¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
[[clang::no_specializations]]
can be applied to function, class, or variabletemplates which should not be explicitly specialized by users. This is primarilyused to diagnose user specializations of standard library type traits.
nonstring¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Thenonstring
attribute can be applied to the declaration of a variable ora field whose type is a character array to specify that the character array isnot intended to behave like a null-terminated string. This will silencediagnostics with code like:
charBadStr[3]="foo";// No space for the null terminator, diagnosed__attribute__((nonstring))charNotAStr[3]="foo";// Not diagnosed
novtable¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
This attribute can be added to a class declaration or definition to signal tothe compiler that constructors and destructors will not reference the virtualfunction table. It is only supported when using the Microsoft C++ ABI.
ns_error_domain¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
In Cocoa frameworks in Objective-C, one can group related error codes in enumsand categorize these enums with error domains.
Thens_error_domain
attribute indicates a globalNSString
orCFString
constant representing the error domain that an error code belongsto. For pointer uniqueness and code size this is a constant symbol, not aliteral.
The domain and error code need to be used together. Thens_error_domain
attribute links error codes to their domain at the source level.
This metadata is useful for documentation purposes, for static analysis, and forimproving interoperability between Objective-C and Swift. It is not used forcode generation in Objective-C.
For example:
#define NS_ERROR_ENUM(_type, _name, _domain) \ enum _name : _type _name; enum __attribute__((ns_error_domain(_domain))) _name : _typeexternNSString*constMyErrorDomain;typedefNS_ERROR_ENUM(unsignedchar,MyErrorEnum,MyErrorDomain){MyErrFirst,MyErrSecond,};
objc_boxable¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Structs and unions marked with theobjc_boxable
attribute can be usedwith the Objective-C boxed expression syntax,@(...)
.
Usage:__attribute__((objc_boxable))
. This attributecan only be placed on a declaration of a trivially-copyable struct or union:
struct__attribute__((objc_boxable))some_struct{inti;};union__attribute__((objc_boxable))some_union{inti;floatf;};typedefstruct__attribute__((objc_boxable))_some_structsome_struct;// ...some_structss;NSValue*boxed=@(ss);
objc_direct¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theobjc_direct
attribute can be used to mark an Objective-C method asbeingdirect. A direct method is treated statically like an ordinary method,but dynamically it behaves more like a C function. This lowers some of the costsassociated with the method but also sacrifices some of the ordinary capabilitiesof Objective-C methods.
A message send of a direct method calls the implementation directly, as if itwere a C function, rather than using ordinary Objective-C method dispatch. Thisis substantially faster and potentially allows the implementation to be inlined,but it also means the method cannot be overridden in subclasses or replaceddynamically, as ordinary Objective-C methods can.
Furthermore, a direct method is not listed in the class’s method lists. Thissubstantially reduces the code-size overhead of the method but also means itcannot be called dynamically using ordinary Objective-C method dispatch at all;in particular, this means that it cannot override a superclass method or satisfya protocol requirement.
Because a direct method cannot be overridden, it is an error to performasuper
message send of one.
Although a message send of a direct method causes the method to be calleddirectly as if it were a C function, it still obeys Objective-C semantics in otherways:
If the receiver is
nil
, the message send does nothing and returns the zero valuefor the return type.A message send of a direct class method will cause the class to be initialized,including calling the
+initialize
method if present.The implicit
_cmd
parameter containing the method’s selector is still defined.In order to minimize code-size costs, the implementation will not emit a referenceto the selector if the parameter is unused within the method.
Symbols for direct method implementations are implicitly given hiddenvisibility, meaning that they can only be called within the same linkage unit.
It is an error to do any of the following:
declare a direct method in a protocol,
declare an override of a direct method with a method in a subclass,
declare an override of a non-direct method with a direct method in a subclass,
declare a method with different directness in different class interfaces, or
implement a non-direct method (as declared in any class interface) with a direct method.
If any of these rules would be violated if every method defined in an@implementation
within a single linkage unit were declared in anappropriate class interface, the program is ill-formed with no diagnosticrequired. If a violation of this rule is not diagnosed, behavior remainswell-defined; this paragraph is simply reserving the right to diagnose suchconflicts in the future, not to treat them as undefined behavior.
Additionally, Clang will warn about any@selector
expression thatnames a selector that is only known to be used for direct methods.
For the purpose of these rules, a “class interface” includes a class’s primary@interface
block, its class extensions, its categories, its declared protocols,and all the class interfaces of its superclasses.
An Objective-C property can be declared with thedirect
propertyattribute. If a direct property declaration causes an implicit declaration ofa getter or setter method (that is, if the given method is not explicitlydeclared elsewhere), the method is declared to be direct.
Some programmers may wish to make many methods direct at once. In orderto simplify this, theobjc_direct_members
attribute is provided; see itsdocumentation for more information.
objc_direct_members¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theobjc_direct_members
attribute can be placed on an Objective-C@interface
or@implementation
to mark that methods declaredtherein should be considered direct by default. See the documentationforobjc_direct
for more information about direct methods.
Whenobjc_direct_members
is placed on an@interface
block, everymethod in the block is considered to be declared as direct. This includes anyimplicit method declarations introduced by property declarations. If the methodredeclares a non-direct method, the declaration is ill-formed, exactly as if themethod was annotated with theobjc_direct
attribute.
Whenobjc_direct_members
is placed on an@implementation
block,methods defined in the block are considered to be declared as direct unlessthey have been previously declared as non-direct in any interface of the class.This includes the implicit method definitions introduced by synthesizedproperties, including auto-synthesized properties.
objc_non_runtime_protocol¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theobjc_non_runtime_protocol
attribute can be used to mark that anObjective-C protocol is only used during static type-checking and doesn’t needto be represented dynamically. This avoids several small code-size and run-timeoverheads associated with handling the protocol’s metadata. A non-runtimeprotocol cannot be used as the operand of a@protocol
expression, anddynamic attempts to find it withobjc_getProtocol
will fail.
If a non-runtime protocol inherits from any ordinary protocols, classes andderived protocols that declare conformance to the non-runtime protocol willdynamically list their conformance to those bare protocols.
objc_nonlazy_class¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
This attribute can be added to an Objective-C@interface
or@implementation
declaration to add the class to the list of non-lazilyinitialized classes. A non-lazy class will be initialized eagerly when theObjective-C runtime is loaded. This is required for certain system classes whichhave instances allocated in non-standard ways, such as the classes for blocksand constant strings. Adding this attribute is essentially equivalent toproviding a trivial+load
method but avoids the (fairly small) load-timeoverheads associated with defining and calling such a method.
objc_runtime_name¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
By default, the Objective-C interface or protocol identifier is usedin the metadata name for that object. Theobjc_runtime_name
attribute allows annotated interfaces or protocols to use thespecified string argument in the object’s metadata name instead of thedefault name.
Usage:__attribute__((objc_runtime_name("MyLocalName")))
. This attributecan only be placed before an @protocol or @interface declaration:
__attribute__((objc_runtime_name("MyLocalName")))@interfaceMessage@end
objc_runtime_visible¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
This attribute specifies that the Objective-C class to which it applies isvisible to the Objective-C runtime but not to the linker. Classes annotatedwith this attribute cannot be subclassed and cannot have categories defined forthem.
objc_subclassing_restricted¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
This attribute can be added to an Objective-C@interface
declaration toensure that this class cannot be subclassed.
preferred_name¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
Thepreferred_name
attribute can be applied to a class template, andspecifies a preferred way of naming a specialization of the template. Thepreferred name will be used whenever the corresponding template specializationwould otherwise be printed in a diagnostic or similar context.
The preferred name must be a typedef or type alias declaration that refers to aspecialization of the class template (not including any type qualifiers). Ingeneral this requires the template to be declared at least twice. For example:
template<typenameT>structbasic_string;usingstring=basic_string<char>;usingwstring=basic_string<wchar_t>;template<typenameT>struct[[clang::preferred_name(string),clang::preferred_name(wstring)]]basic_string{// ...};
Note that thepreferred_name
attribute will be ignored when the compilerwrites a C++20 Module interface now. This is due to a compiler issue(https://github.com/llvm/llvm-project/issues/56490) that blocks users to modularizedeclarations withpreferred_name. This is intended to be fixed in the future.
randomize_layout, no_randomize_layout¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
The attributerandomize_layout
, when attached to a C structure, selects itfor structure layout field randomization; a compile-time hardening technique. A“seed” value, is specified via the-frandomize-layout-seed=
command line flag.For example:
SEED=`od-An-tx8-N32/dev/urandom|tr-d' \n'`make...CFLAGS="-frandomize-layout-seed=$SEED"...
You can also supply the seed in a file with-frandomize-layout-seed-file=
.For example:
od-An-tx8-N32/dev/urandom|tr-d' \n'>/tmp/seed_file.txtmake...CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt"...
The randomization is deterministic based for a given seed, so the entireprogram should be compiled with the same seed, but keep the seed safeotherwise.
The attributeno_randomize_layout
, when attached to a C structure,instructs the compiler that this structure should not have its field layoutrandomized.
selectany¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
This attribute appertains to a global symbol, causing it to have a weakdefinition (linkonce), allowing the linker to select any definition.
For more information seegcc documentationormsvc documentation.
transparent_union¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
This attribute can be applied to a union to change the behavior of calls tofunctions that have an argument with a transparent union type. The compilerbehavior is changed in the following manner:
A value whose type is any member of the transparent union can be passed as anargument without the need to cast that value.
The argument is passed to the function using the calling convention of thefirst member of the transparent union. Consequently, all the members of thetransparent union should have the same calling convention as its first member.
Transparent unions are not supported in C++.
trivial_abi¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
Thetrivial_abi
attribute can be applied to a C++ class, struct, or union.It instructs the compiler to pass and return the type using the C ABI for theunderlying type when the type would otherwise be considered non-trivial for thepurpose of calls.A class annotated withtrivial_abi
can have non-trivial destructors orcopy/move constructors without automatically becoming non-trivial for thepurposes of calls. For example:
// A is trivial for the purposes of calls because ``trivial_abi`` makes the// user-provided special functions trivial.struct__attribute__((trivial_abi))A{~A();A(constA&);A(A&&);intx;};// B's destructor and copy/move constructor are considered trivial for the// purpose of calls because A is trivial.structB{Aa;};
If a type is trivial for the purposes of calls, has a non-trivial destructor,and is passed as an argument by value, the convention is that the callee willdestroy the object before returning. The lifetime of the copy of the parameterin the caller ends without a destructor call when the call begins.
If a type is trivial for the purpose of calls, it is assumed to be triviallyrelocatable for the purpose of__is_trivially_relocatable
and__builtin_is_cpp_trivially_relocatable
.When a type marked with[[trivial_abi]]
is used as a function argument,the compiler may omit the call to the copy constructor.Thus, side effects of the copy constructor are potentially not performed.For example, objects that contain pointers to themselves or otherwise dependon their address (or the address or their subobjects) should not be declared[[trivial_abi]]
.
Attributetrivial_abi
has no effect in the following cases:
The class directly declares a virtual base or virtual methods.
Copy constructors and move constructors of the class are all deleted.
The class has a base class that is non-trivial for the purposes of calls.
The class has a non-static data member whose type is non-trivial for thepurposes of calls, which includes:
classes that are non-trivial for the purposes of calls
__weak-qualified types in Objective-C++
arrays of any of the above
using_if_exists¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
Theusing_if_exists
attribute applies to a using-declaration. It allowsprogrammers to import a declaration that potentially does not exist, insteaddeferring any errors to the point of use. For instance:
namespaceempty_namespace{};__attribute__((using_if_exists))usingempty_namespace::does_not_exist;// no error!does_not_existx;// error: use of unresolved 'using_if_exists'
The C++ spelling of the attribute ([[clang::using_if_exists]]) is alsosupported as a clang extension, since ISO C++ doesn’t support attributes in thisposition. If the entity referred to by the using-declaration is found by namelookup, the attribute has no effect. This attribute is useful for libraries(primarily, libc++) that wish to redeclare a set of declarations in anothernamespace, when the availability of those declarations is difficult orimpossible to detect at compile time with the preprocessor.
weak¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
In supported output formats theweak
attribute can be used tospecify that a variable or function should be emitted as a symbol withweak
(if a definition) orextern_weak
(if a declaration of anexternal symbol)linkage.
If there is a non-weak definition of the symbol the linker will selectthat over the weak. They must have same type and alignment (variablesmust also have the same size), but may have a different value.
If there are multiple weak definitions of same symbol, but no non-weakdefinition, they should have same type, size, alignment and value, thelinker will select one of them (see alsoselectany attribute).
If theweak
attribute is applied to aconst
qualified variabledefinition that variable is no longer consider a compiletime constantas its value can change during linking (or dynamic linking). Thismeans that it can e.g no longer be part of an initializer expression.
constintANSWER__attribute__((weak))=42;/* This function may be replaced link-time */__attribute__((weak))voiddebug_log(constchar*msg){fprintf(stderr,"DEBUG: %s\n",msg);}intmain(intargc,constchar**argv){debug_log("Starting up...");/* This may print something else than "6 * 7 = 42", if there is a non-weak definition of "ANSWER" in an object linked in */printf("6 * 7 = %d\n",ANSWER);return0;}
If an external declaration is marked weak and that symbol does notexist during linking (possibly dynamic) the address of the symbol willevaluate to NULL.
voidmay_not_exist(void)__attribute__((weak));intmain(intargc,constchar**argv){if(may_not_exist){may_not_exist();}else{printf("Function did not exist\n");}return0;}
Field Attributes¶
counted_by, counted_by_or_null, sized_by, sized_by_or_null¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Clang supports thecounted_by
attribute on the flexible array member of astructure in C. The argument for the attribute is the name of a field memberholding the count of elements in the flexible array. This information can beused to improve the results of the array bound sanitizer and the__builtin_dynamic_object_size
builtin. Thecount
field member must bewithin the same non-anonymous, enclosing struct as the flexible array member.
This example specifies that the flexible array memberarray
has the numberof elements allocated for it incount
:
structbar;structfoo{size_tcount;charother;structbar*array[]__attribute__((counted_by(count)));};
This establishes a relationship betweenarray
andcount
. Specifically,array
must have at leastcount
number of elements available. It’s theuser’s responsibility to ensure that this relationship is maintained throughchanges to the structure.
In the following example, the allocated array erroneously has fewer elementsthan what’s specified byp->count
. This would result in an out-of-boundsaccess not being detected.
#define SIZE_INCR 42structfoo*p;voidfoo_alloc(size_tcount){p=malloc(MAX(sizeof(structfoo),offsetof(structfoo,array[0])+count*sizeof(structbar*)));p->count=count+SIZE_INCR;}
The next example updatesp->count
, but breaks the relationship requirementthatp->array
must have at leastp->count
number of elements available:
#define SIZE_INCR 42structfoo*p;voidfoo_alloc(size_tcount){p=malloc(MAX(sizeof(structfoo),offsetof(structfoo,array[0])+count*sizeof(structbar*)));p->count=count;}voiduse_foo(intindex,intval){p->count+=SIZE_INCR+1;/* 'count' is now larger than the number of elements of 'array'. */p->array[index]=val;/* The sanitizer can't properly check this access. */}
In this example, an update top->count
maintains the relationshiprequirement:
voiduse_foo(intindex,intval){if(p->count==0)return;--p->count;p->array[index]=val;}
no_unique_address¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
Theno_unique_address
attribute allows tail padding in a non-static datamember to overlap other members of the enclosing class (and in the specialcase when the type is empty, permits it to fully overlap other members).The field is laid out as if a base class were encountered at the correspondingpoint within the class (except that it does not share a vptr with the enclosingobject).
Example usage:
template<typenameT,typenameAlloc>structmy_vector{T*p;[[no_unique_address]]Allocalloc;// ...};static_assert(sizeof(my_vector<int,std::allocator<int>>)==sizeof(int*));
[[no_unique_address]]
is a standard C++20 attribute. Clang supports its usein C++11 onwards.
On MSVC targets,[[no_unique_address]]
is ignored; use[[msvc::no_unique_address]]
instead. Currently there is no guarantee of ABIcompatibility or stability with MSVC.
preferred_type¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
This attribute allows adjusting the type of a bit-field in debug information.This can be helpful when a bit-field is intended to store an enumeration value,but has to be specified as having the enumeration’s underlying type in order tofacilitate compiler optimizations or bit-field packing behavior. Normally, theunderlying type is what is emitted in debug information, which can make it hardfor debuggers to know to map a bit-field’s value back to a particular enumeration.
enumColors{Red,Green,Blue};structS{[[clang::preferred_type(Colors)]]unsignedColorVal:2;[[clang::preferred_type(bool)]]unsignedUseAlternateColorSpace:1;}s={Green,false};
Without the attribute, a debugger is likely to display the value1
forColorVal
and0
forUseAlternateColorSpace
. With the attribute, the debugger may nowdisplayGreen
andfalse
instead.
This can be used to map a bit-field to an arbitrary type that isn’t integralor an enumeration type. For example:
structA{shorta1;shorta2;};structB{[[clang::preferred_type(A)]]unsignedb1:32=0x000F'000C;};
will associate the typeA
with theb1
bit-field and is intended to displaysomething like this in the debugger:
Process 2755547 stopped* thread #1, name = 'test-preferred-', stop reason = step in frame #0: 0x0000555555555148 test-preferred-type`main at test.cxx:13:14 10 int main() 11 { 12 B b;-> 13 return b.b1; 14 }(lldb) v -T(B) b = { (A:32) b1 = { (short) a1 = 12 (short) a2 = 15 }}
Note that debuggers may not be able to handle more complex mappings, and sothis usage is debugger-dependent.
require_explicit_initialization¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theclang::require_explicit_initialization
attribute indicates that afield of an aggregate must be initialized explicitly by the user when an objectof the aggregate type is constructed. The attribute supports both C and C++,but its usage is invalid on non-aggregates.
Note that this attribute isnot a memory safety feature, and isnot intendedto guard against use of uninitialized memory.
Rather, it is intended for use in “parameter-objects”, used to simulate,for example, the passing of named parameters.Except inside unevaluated contexts, the attribute generates a warning whenexplicit initializers for such variables are not provided (this occursregardless of whether any in-class field initializers exist):
structBuffer{void*address[[clang::require_explicit_initialization]];size_tlength[[clang::require_explicit_initialization]]=0;};structArrayIOParams{size_tcount[[clang::require_explicit_initialization]];size_telement_size[[clang::require_explicit_initialization]];intflags=0;};size_tReadArray(FILE*file,structBufferbuffer,structArrayIOParamsparams);intmain(){unsignedintbuf[512];ReadArray(stdin,{buf// warning: field 'length' is not explicitly initialized},{.count=sizeof(buf)/sizeof(*buf),// warning: field 'element_size' is not explicitly initialized// (Note that a missing initializer for 'flags' is not diagnosed, because// the field is not marked as requiring explicit initialization.)});}
Function Attributes¶
#pragma omp declare simd¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
`` declare simd`` |
Thedeclaresimd
construct can be applied to a function to enable the creationof one or more versions that can process multiple arguments using SIMDinstructions from a single invocation in a SIMD loop. Thedeclaresimd
directive is a declarative directive. There may be multipledeclaresimd
directives for a function. The use of adeclaresimd
construct on a functionenables the creation of SIMD versions of the associated function that can beused to process multiple arguments from a single invocation from a SIMD loopconcurrently.The syntax of thedeclaresimd
construct is as follows:
#pragma omp declare simd [clause[[,] clause] ...] new-line[#pragma omp declare simd [clause[[,] clause] ...] new-line][...]function definition or declaration
where clause is one of the following:
simdlen(length)linear(argument-list[:constant-linear-step])aligned(argument-list[:alignment])uniform(argument-list)inbranchnotinbranch
#pragma omp declare target¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
`` declare target`` |
Thedeclaretarget
directive specifies that variables and functions are mappedto a device for OpenMP offload mechanism.
The syntax of the declare target directive is as follows:
#pragma omp declare target new-linedeclarations-definition-seq#pragma omp end declare target new-line
or
#pragma omp declare target (extended-list) new-line
or
#pragma omp declare target clause[ [,] clause ... ] new-line
where clause is one of the following:
to(extended-list)link(list)device_type(host|nohost|any)
#pragma omp declare variant¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
`` declare variant`` |
Thedeclarevariant
directive declares a specialized variant of a basefunction and specifies the context in which that specialized variant is used.The declare variant directive is a declarative directive.The syntax of thedeclarevariant
construct is as follows:
#pragma omp declare variant(variant-func-id) clause new-line[#pragma omp declare variant(variant-func-id) clause new-line][...]function definition or declaration
where clause is one of the following:
match(context-selector-specification)
and wherevariant-func-id
is the name of a function variant that is either abase language identifier or, for C++, a template-id.
Clang provides the following context selector extensions, used viaimplementation={extension(EXTENSION)}
:
match_allmatch_anymatch_nonedisable_implicit_baseallow_templatesbind_to_declaration
The match extensions change when theentire context selector is considered amatch for an OpenMP context. The default isall
, withnone
no trait in theselector is allowed to be in the OpenMP context, withany
a single trait inboth the selector and OpenMP context is sufficient. Only a single matchextension trait is allowed per context selector.The disable extensions remove default effects of thebegindeclarevariant
applied to a definition. Ifdisable_implicit_base
is given, we will notintroduce an implicit base function for a variant if no base function wasfound. The variant is still generated but will never be called, due to theabsence of a base function and consequently calls to a base function.The allow extensions change when thebegindeclarevariant
effect isapplied to a definition. Ifallow_templates
is given, template functiondefinitions are considered as specializations of existing or assumed templatedeclarations with the same name. The template parameters for the base functionsare used to instantiate the specialization. Ifbind_to_declaration
is given,apply the same variant rules to function declarations. This allows the user tooverride declarations with only a function declaration.
RootSignature¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
TheRootSignature
attribute applies to HLSL entry functions to define whattypes of resources are bound to the graphics pipeline.
For details about the use and specification of Root Signatures please see here:https://learn.microsoft.com/en-us/windows/win32/direct3d12/root-signatures
WaveSize¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
TheWaveSize
attribute specify a wave size on a shader entry point in orderto indicate either that a shader depends on or strongly prefers a specific wavesize.There’re 2 versions of the attribute:WaveSize
andRangedWaveSize
.The syntax forWaveSize
is:
``[WaveSize(<numLanes>)]``
The allowed wave sizes that an HLSL shader may specify are the powers of 2between 4 and 128, inclusive.In other words, the set: [4, 8, 16, 32, 64, 128].
The syntax forRangedWaveSize
is:
``[WaveSize(<minWaveSize>, <maxWaveSize>, [prefWaveSize])]``
Where minWaveSize is the minimum wave size supported by the shader representingthe beginning of the allowed range, maxWaveSize is the maximum wave sizesupported by the shader representing the end of the allowed range, andprefWaveSize is the optional preferred wave size representing the size expectedto be the most optimal for this shader.
WaveSize
is available for HLSL shader model 6.6 and later.RangedWaveSize
available for HLSL shader model 6.8 and later.
The full documentation is available here:https://microsoft.github.io/DirectX-Specs/d3d/HLSL_SM_6_6_WaveSize.htmlandhttps://microsoft.github.io/hlsl-specs/proposals/0013-wave-size-range.html
_Noreturn¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
A function declared as_Noreturn
shall not return to its caller. Thecompiler will generate a diagnostic for a function declared as_Noreturn
that appears to be capable of returning to its caller. Despite being a typespecifier, the_Noreturn
attribute cannot be specified on a functionpointer type.
abi_tag¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
Theabi_tag
attribute can be applied to a function, variable, class orinline namespace declaration to modify the mangled name of the entity. It givesthe ability to distinguish between different versions of the same entity butwith different ABI versions supported. For example, a newer version of a classcould have a different set of data members and thus have a different size. Usingtheabi_tag
attribute, it is possible to have different mangled names fora global variable of the class type. Therefore, the old code could keep usingthe old mangled name and the new code will use the new mangled name with tags.
acquire_capability, acquire_shared_capability¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
Marks a function as acquiring a capability.
alloc_align¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Use__attribute__((alloc_align(<alignment>))
on a functiondeclaration to specify that the return value of the function (which must be apointer type) is at least as aligned as the value of the indicated parameter. Theparameter is given by its index in the list of formal parameters; the firstparameter has index 1 unless the function is a C++ non-static member function,in which case the first parameter has index 2 to account for the implicitthis
parameter.
// The returned pointer has the alignment specified by the first parameter.void*a(size_talign)__attribute__((alloc_align(1)));// The returned pointer has the alignment specified by the second parameter.void*b(void*v,size_talign)__attribute__((alloc_align(2)));// The returned pointer has the alignment specified by the second visible// parameter, however it must be adjusted for the implicit 'this' parameter.void*Foo::b(void*v,size_talign)__attribute__((alloc_align(3)));
Note that this attribute merely informs the compiler that a function alwaysreturns a sufficiently aligned pointer. It does not cause the compiler toemit code to enforce that alignment. The behavior is undefined if the returnedpointer is not sufficiently aligned.
alloc_size¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Thealloc_size
attribute can be placed on functions that return pointers inorder to hint to the compiler how many bytes of memory will be available at thereturned pointer.alloc_size
takes one or two arguments.
alloc_size(N)
implies that argument number N equals the number ofavailable bytes at the returned pointer.alloc_size(N,M)
implies that the product of argument number N andargument number M equals the number of available bytes at the returnedpointer.
Argument numbers are 1-based.
An example of how to usealloc_size
void*my_malloc(inta)__attribute__((alloc_size(1)));void*my_calloc(inta,intb)__attribute__((alloc_size(1,2)));intmain(){void*constp=my_malloc(100);assert(__builtin_object_size(p,0)==100);void*consta=my_calloc(20,5);assert(__builtin_object_size(a,0)==100);}
Note
This attribute works differently in clang than it does in GCC.Specifically, clang will only traceconst
pointers (as above); we give upon pointers that are not marked asconst
. In the vast majority of cases,this is unimportant, because LLVM has support for thealloc_size
attribute. However, this may cause mildly unintuitive behavior when used withother attributes, such asenable_if
.
allocator¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__declspec(allocator)
attribute is applied to functions that allocatememory, such as operator new in C++. When CodeView debug information is emitted(enabled byclang-gcodeview
orclang-cl/Z7
), Clang will attempt torecord the code offset of heap allocation call sites in the debug info. It willalso record the type being allocated using some local heuristics. The VisualStudio debugger uses this information toprofile memory usage.
This attribute does not affect optimizations in any way, unlike GCC’s__attribute__((malloc))
.
always_inline, __force_inline¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
| Yes |
Inlining heuristics are disabled and inlining is always attempted regardless ofoptimization level.
[[clang::always_inline]]
spelling can be used as a statement attribute; otherspellings of the attribute are not supported on statements. If a statement ismarked[[clang::always_inline]]
and contains calls, the compiler attemptsto inline those calls.
intexample(void){inti;[[clang::always_inline]]foo();// attempts to inline foo[[clang::always_inline]]i=bar();// attempts to inline bar[[clang::always_inline]]returnf(42,baz(bar()));// attempts to inline everything}
A declaration statement, which is a statement, is not a statement that can have anattribute associated with it (the attribute applies to the declaration, not thestatement in that case). So this use case will not work:
intexample(void){[[clang::always_inline]]inti=bar();returni;}
This attribute does not guarantee that inline substitution actually occurs.
<ins>Note: applying this attribute to a coroutine at the-O0 optimization levelhas no effect; other optimization levels may only partially inline and result in adiagnostic.</ins>
See alsothe Microsoft Docs on Inline Functions,the GCC Common FunctionAttribute docs, andthe GCC Inline docs.
artificial¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Theartificial
attribute can be applied to an inline function. If such afunction is inlined, the attribute indicates that debuggers should associatethe resulting instructions with the call site, rather than with thecorresponding line within the inlined callee.
assert_capability, assert_shared_capability¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
Marks a function that dynamically tests whether a capability is held, and haltsthe program if it is not held.
assume¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
Clang supports the[[omp::assume("assumption")]]
attribute toprovide additional information to the optimizer. The string-literal, here“assumption”, will be attached to the function declaration such that lateranalysis and optimization passes can assume the “assumption” to hold.This is similar to__builtin_assume butinstead of an expression that can be assumed to be non-zero, the assumption isexpressed as a string and it holds for the entire function.
A function can have multiple assume attributes and they propagate from priordeclarations to later definitions. Multiple assumptions are aggregated into asingle comma separated string. Thus, one can provide multiple assumptions viaa comma separated string, i.a.,[[omp::assume("assumption1,assumption2")]]
.
While LLVM plugins might provide more assumption strings, the default LLVMoptimization passes are aware of the following assumptions:
"omp_no_openmp""omp_no_openmp_routines""omp_no_parallelism""omp_no_openmp_constructs"
The OpenMP standard defines the meaning of OpenMP assumptions (“omp_XYZ” isspelled “XYZ” in theOpenMP 5.1 Standard).
assume_aligned¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Use__attribute__((assume_aligned(<alignment>[,<offset>]))
on a functiondeclaration to specify that the return value of the function (which must be apointer type) has the specified offset, in bytes, from an address with thespecified alignment. The offset is taken to be zero if omitted.
// The returned pointer value has 32-byte alignment.void*a()__attribute__((assume_aligned(32)));// The returned pointer value is 4 bytes greater than an address having// 32-byte alignment.void*b()__attribute__((assume_aligned(32,4)));
Note that this attribute provides information to the compiler regarding acondition that the code already ensures is true. It does not cause the compilerto enforce the provided alignment assumption.
availability¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theavailability
attribute can be placed on declarations to describe thelifecycle of that declaration relative to operating system versions. Considerthe function declaration for a hypothetical functionf
:
voidf(void)__attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
The availability attribute states thatf
was introduced in macOS 10.4,deprecated in macOS 10.6, and obsoleted in macOS 10.7. This informationis used by Clang to determine when it is safe to usef
: for example, ifClang is instructed to compile code for macOS 10.5, a call tof()
succeeds. If Clang is instructed to compile code for macOS 10.6, the callsucceeds but Clang emits a warning specifying that the function is deprecated.Finally, if Clang is instructed to compile code for macOS 10.7, the callfails becausef()
is no longer available.
Clang is instructed to compile code for a minimum deployment version usingthe-target
or-mtargetos
command line arguments. For example,macOS 10.7 would be specified as-targetx86_64-apple-macos10.7
or-mtargetos=macos10.7
. Variants like Mac Catalyst are specified as-targetarm64-apple-ios15.0-macabi
or-mtargetos=ios15.0-macabi
The availability attribute is a comma-separated list starting with theplatform name and then including clauses specifying important milestones in thedeclaration’s lifetime (in any order) along with additional information. Thoseclauses can be:
- introduced=version
The first version in which this declaration was introduced.
- deprecated=version
The first version in which this declaration was deprecated, meaning thatusers should migrate away from this API.
- obsoleted=version
The first version in which this declaration was obsoleted, meaning that itwas removed completely and can no longer be used.
- unavailable
This declaration is never available on this platform.
- message=string-literal
Additional message text that Clang will provide when emitting a warning orerror about use of a deprecated or obsoleted declaration. Useful to directusers to replacement APIs.
- replacement=string-literal
Additional message text that Clang will use to provide Fix-It when emittinga warning about use of a deprecated declaration. The Fix-It will replacethe deprecated declaration with the new declaration specified.
- environment=identifier
Target environment in which this declaration is available. If present,the availability attribute applies only to targets with the same platformand environment. The parameter is currently supported only in HLSL.
Multiple availability attributes can be placed on a declaration, which maycorrespond to different platforms. For most platforms, the availabilityattribute with the platform corresponding to the target platform will be used;any others will be ignored. However, the availability forwatchOS
andtvOS
can be implicitly inferred from aniOS
availability attribute.Any explicit availability attributes for those platforms are still preferred overthe implicitly inferred availability attributes. If no availability attributespecifies availability for the current target platform, the availabilityattributes are ignored. Supported platforms are:
iOS
macOS
tvOS
watchOS
iOSApplicationExtension
macOSApplicationExtension
tvOSApplicationExtension
watchOSApplicationExtension
macCatalyst
macCatalystApplicationExtension
visionOS
visionOSApplicationExtension
driverkit
swift
android
fuchsia
ohos
zos
ShaderModel
Some platforms have alias names:
ios
macos
macosx(deprecated)
tvos
watchos
ios_app_extension
macos_app_extension
macosx_app_extension(deprecated)
tvos_app_extension
watchos_app_extension
maccatalyst
maccatalyst_app_extension
visionos
visionos_app_extension
shadermodel
Supported environment names for the ShaderModel platform:
pixel
vertex
geometry
hull
domain
compute
raygeneration
intersection
anyhit
closesthit
miss
callable
mesh
amplification
library
A declaration can typically be used even when deploying back to a platformversion prior to when the declaration was introduced. When this happens, thedeclaration isweakly linked,as if theweak_import
attribute were added to the declaration. Aweakly-linked declaration may or may not be present a run-time, and a programcan determine whether the declaration is present by checking whether theaddress of that declaration is non-NULL.
The flagstrict
disallows using API when deploying back to aplatform version prior to when the declaration was introduced. Anattempt to use such API before its introduction causes a hard error.Weakly-linking is almost always a better API choice, since it allowsusers to query availability at runtime.
If there are multiple declarations of the same entity, the availabilityattributes must either match on a per-platform basis or laterdeclarations must not have availability attributes for thatplatform. For example:
voidg(void)__attribute__((availability(macos,introduced=10.4)));voidg(void)__attribute__((availability(macos,introduced=10.4)));// okay, matchesvoidg(void)__attribute__((availability(ios,introduced=4.0)));// okay, adds a new platformvoidg(void);// okay, inherits both macos and ios availability from above.voidg(void)__attribute__((availability(macos,introduced=10.5)));// error: mismatch
When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
@interfaceA-(id)method__attribute__((availability(macos,introduced=10.4)));-(id)method2__attribute__((availability(macos,introduced=10.4)));@end@interfaceB :A-(id)method__attribute__((availability(macos,introduced=10.3)));// okay: method moved into base class later-(id)method__attribute__((availability(macos,introduced=10.5)));// error: this method was available via the base class in 10.4@end
Starting with the macOS 10.12 SDK, theAPI_AVAILABLE
macro from<os/availability.h>
can simplify the spelling:
@interfaceA-(id)methodAPI_AVAILABLE(macos(10.11)));-(id)otherMethodAPI_AVAILABLE(macos(10.11),ios(11.0));@end
Availability attributes can also be applied using a#pragmaclangattribute
.Any explicit availability attribute whose platform corresponds to the targetplatform is applied to a declaration regardless of the availability attributesspecified in the pragma. For example, in the code below,hasExplicitAvailabilityAttribute
will use themacOS
availabilityattribute that is specified with the declaration, whereasgetsThePragmaAvailabilityAttribute
will use themacOS
availabilityattribute that is applied by the pragma.
#pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function)voidgetsThePragmaAvailabilityAttribute(void);voidhasExplicitAvailabilityAttribute(void)__attribute__((availability(macos,introduced=10.4)));#pragma clang attribute pop
For platforms likewatchOS
andtvOS
, whose availability attributes canbe implicitly inferred from aniOS
availability attribute, the logic isslightly more complex. The explicit and the pragma-applied availabilityattributes whose platform corresponds to the target platform are applied asdescribed in the previous paragraph. However, the implicitly inferred attributesare applied to a declaration only when there is no explicit or pragma-appliedavailability attribute whose platform corresponds to the target platform. Forexample, the function below will receive thetvOS
availability from thepragma rather than using the inferrediOS
availability from the declaration:
#pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function)voidgetsThePragmaTVOSAvailabilityAttribute(void)__attribute__((availability(iOS,introduced=11.0)));#pragma clang attribute pop
The compiler is also able to apply implicitly inferred attributes from a pragmaas well. For example, when targetingtvOS
, the function below will receiveatvOS
availability attribute that is implicitly inferred from theiOS
availability attribute applied by the pragma:
#pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function)voidinfersTVOSAvailabilityFromPragma(void);#pragma clang attribute pop
The implicit attributes that are inferred from explicitly specified attributeswhose platform corresponds to the target platform are applied to the declarationeven if there is an availability attribute that can be inferred from a pragma.For example, the function below will receive thetvOS,introduced=11.0
availability that is inferred from the attribute on the declaration rather thaninferring availability from the pragma:
#pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function)voidinfersTVOSAvailabilityFromAttributeNextToDeclaration(void)__attribute__((availability(iOS,introduced=11.0)));#pragma clang attribute pop
Also see the documentation for@available
btf_decl_tag¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang supports the__attribute__((btf_decl_tag("ARGUMENT")))
attribute forall targets. This attribute may be attached to a struct/union, struct/unionfield, function, function parameter, variable or typedef declaration. If -g isspecified, theARGUMENT
info will be preserved in IR and be emitted todwarf. For BPF targets, theARGUMENT
info will be emitted to .BTF ELFsection too.
callback¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Thecallback
attribute specifies that the annotated function may invoke thespecified callback zero or more times. The callback, as well as the passedarguments, are identified by their parameter name or position (starting with1!) in the annotated function. The first position in the attribute identifiesthe callback callee, the following positions declare describe its arguments.The callback callee is required to be callable with the number, and order, ofthe specified arguments. The index0
, or the identifierthis
, is used torepresent an implicit “this” pointer in class methods. If there is no implicit“this” pointer it shall not be referenced. The index ‘-1’, or the name “__”,represents an unknown callback callee argument. This can be a value which isnot present in the declared parameter list, or one that is, but is potentiallyinspected, captured, or modified. Parameter names and indices can be mixed inthe callback attribute.
Thecallback
attribute, which is directly translated tocallback
metadata <http://llvm.org/docs/LangRef.html#callback-metadata>, make theconnection between the call to the annotated function and the callback callee.This can enable interprocedural optimizations which were otherwise impossible.If a function parameter is mentioned in thecallback
attribute, through itsposition, it is undefined if that parameter is used for anything other than theactual callback. Inspected, captured, or modified parameters shall not belisted in thecallback
metadata.
Example encodings for the callback performed bypthread_create
are shownbelow. The explicit attribute annotation indicates that the third parameter(start_routine
) is called zero or more times by thepthread_create
function,and that the fourth parameter (arg
) is passed along. Note that the callbackbehavior ofpthread_create
is automatically recognized by Clang. In addition,the declarations of__kmpc_fork_teams
and__kmpc_fork_call
, generated for#pragmaomptargetteams
and#pragmaompparallel
, respectively, are alsoautomatically recognized as broker functions. Further functions might be addedin the future.
__attribute__((callback(start_routine,arg)))intpthread_create(pthread_t*thread,constpthread_attr_t*attr,void*(*start_routine)(void*),void*arg);__attribute__((callback(3,4)))intpthread_create(pthread_t*thread,constpthread_attr_t*attr,void*(*start_routine)(void*),void*arg);
carries_dependency¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
Thecarries_dependency
attribute specifies dependency propagation into andout of functions.
When specified on a function or Objective-C method, thecarries_dependency
attribute means that the return value carries a dependency out of the function,so that the implementation need not constrain ordering upon return from thatfunction. Implementations of the function and its caller may choose to preservedependencies instead of emitting memory ordering instructions such as fences.
Note, this attribute does not change the meaning of the program, but may resultin generation of more efficient code.
cf_consumed, cf_returns_not_retained, cf_returns_retained, ns_consumed, ns_consumes_self, ns_returns_autoreleased, ns_returns_not_retained, ns_returns_retained, os_consumed, os_consumes_this, os_returns_not_retained, os_returns_retained, os_returns_retained_on_non_zero, os_returns_retained_on_zero¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
The behavior of a function with respect to reference counting for Foundation(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a namingconvention (e.g. functions starting with “get” are assumed to return at+0
).
It can be overridden using a family of the following attributes. InObjective-C, the annotation__attribute__((ns_returns_retained))
applied toa function communicates that the object is returned at+1
, and the calleris responsible for freeing it.Similarly, the annotation__attribute__((ns_returns_not_retained))
specifies that the object is returned at+0
and the ownership remains withthe callee.The annotation__attribute__((ns_consumes_self))
specifies thatthe Objective-C method call consumes the reference toself
, e.g. byattaching it to a supplied parameter.Additionally, parameters can have an annotation__attribute__((ns_consumed))
, which specifies that passing an owned objectas that parameter effectively transfers the ownership, and the caller is nolonger responsible for it.These attributes affect code generation when interacting with ARC code, andthey are used by the Clang Static Analyzer.
In C programs using CoreFoundation, a similar set of attributes:__attribute__((cf_returns_not_retained))
,__attribute__((cf_returns_retained))
and__attribute__((cf_consumed))
have the same respective semantics when applied to CoreFoundation objects.These attributes affect code generation when interacting with ARC code, andthey are used by the Clang Static Analyzer.
Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),the same attribute family is present:__attribute__((os_returns_not_retained))
,__attribute__((os_returns_retained))
and__attribute__((os_consumed))
,with the same respective semantics.Similar to__attribute__((ns_consumes_self))
,__attribute__((os_consumes_this))
specifies that the method call consumesthe reference to “this” (e.g., when attaching it to a different object suppliedas a parameter).Out parameters (parameters the function is meant to write into,either via pointers-to-pointers or references-to-pointers)may be annotated with__attribute__((os_returns_retained))
or__attribute__((os_returns_not_retained))
which specifies that the objectwritten into the out parameter should (or respectively should not) be releasedafter use.Since often out parameters may or may not be written depending on the exitcode of the function,annotations__attribute__((os_returns_retained_on_zero))
and__attribute__((os_returns_retained_on_non_zero))
specify thatan out parameter at+1
is written if and only if the function returns a zero(respectively non-zero) error code.Observe that return-code-dependent out parameter annotations are onlyavailable for retained out parameters, as non-retained object do not have to bereleased by the callee.These attributes are only used by the Clang Static Analyzer.
The family of attributesX_returns_X_retained
can be added to functions,C++ methods, and Objective-C methods and properties.AttributesX_consumed
can be added to parameters of methods, functions,and Objective-C methods.
cfi_canonical_jump_table¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Use__attribute__((cfi_canonical_jump_table))
on a function declaration tomake the function’s CFI jump table canonical. Seethe CFI documentation for more details.
clang::builtin_alias, clang_builtin_alias¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
This attribute is used in the implementation of the C intrinsics.It allows the C intrinsic functions to be declared using the names definedin target builtins, and still be recognized as clang builtins equivalent to theunderlying name. For example,riscv_vector.h
declares the functionvadd
with__attribute__((clang_builtin_alias(__builtin_rvv_vadd_vv_i8m1)))
.This ensures that both functions are recognized as that clang builtin,and in the latter case, the choice of which builtin to identify thefunction as can be deferred until after overload resolution.
This attribute can only be used to set up the aliases for certain ARM/RISC-VC intrinsic functions; it is intended for use only insidearm_*.h
andriscv_*.h
and is not a general mechanism for declaring arbitrary aliasesfor clang builtin functions.
clang_arm_builtin_alias¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
This attribute is used in the implementation of the ACLE intrinsics.It allows the intrinsic functions tobe declared using the names defined in ACLE, and still be recognizedas clang builtins equivalent to the underlying name. For example,arm_mve.h
declares the functionvaddq_u32
with__attribute__((__clang_arm_mve_alias(__builtin_arm_mve_vaddq_u32)))
,and similarly, one of the type-overloaded declarations ofvaddq
will have the same attribute. This ensures that both functions arerecognized as that clang builtin, and in the latter case, the choiceof which builtin to identify the function as can be deferred untilafter overload resolution.
This attribute can only be used to set up the aliases for certain Armintrinsic functions; it is intended for use only insidearm_*.h
and is not a general mechanism for declaring arbitrary aliases forclang builtin functions.
In order to avoid duplicating the attribute definitions for similarpurpose for other architecture, there is a general form for theattributeclang_builtin_alias.
clspv_libclc_builtin¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Attribute used byclspv (OpenCL-C to Vulkan SPIR-V compiler) to identify functions coming fromlibclc (OpenCL-C builtin library).
void__attribute__((clspv_libclc_builtin))libclc_builtin(){}
cmse_nonsecure_entry¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
This attribute declares a function that can be called from non-secure state, orfrom secure state. Entering from and returning to non-secure state would switchto and from secure state, respectively, and prevent flow of informationto non-secure state, except via return values. SeeARMv8-M Security Extensions:Requirements on Development Tools - Engineering Specification Documentation for more information.
code_seg¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__declspec(code_seg)
attribute enables the placement of code into separatenamed segments that can be paged or locked in memory individually. This attributeis used to control the placement of instantiated templates and compiler-generatedcode. See the documentation for__declspec(code_seg) on MSDN.
cold¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
__attribute__((cold))
marks a function as cold, as a manual alternative to PGO hotness data.If PGO data is available, the profile count based hotness overrides the__attribute__((cold))
annotation (unlike__attribute__((hot))
).
constant_id¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
Thevk::constant_id
attribute specifies the id for a SPIR-V specializationconstant. The attribute applies to const global scalar variables. The variable must be initialized with a C++11 constexpr.In SPIR-V, thevariable will be replaced with anOpSpecConstant with the given id.The syntax is:
``[[vk::constant_id(<Id>)]] const T Name = <Init>``
constructor, destructor¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theconstructor
attribute causes the function to be called before enteringmain()
, and thedestructor
attribute causes the function to be calledafter returning frommain()
or when theexit()
function has beencalled. Note,quick_exit()
,_Exit()
, andabort()
prevent a functionmarkeddestructor
from being called.
The constructor or destructor function should not accept any arguments and itsreturn type should bevoid
.
The attributes accept an optional argument used to specify the priority orderin which to execute constructor and destructor functions. The priority isgiven as an integer constant expression between 101 and 65535 (inclusive).Priorities outside of that range are reserved for use by the implementation. Alower value indicates a higher priority of initialization. Note that only therelative ordering of values is important. For example:
__attribute__((constructor(200)))voidfoo(void);__attribute__((constructor(101)))voidbar(void);
bar()
will be called beforefoo()
, and both will be called beforemain()
. If no argument is given to theconstructor
ordestructor
attribute, they default to the value65535
.
convergent¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theconvergent
attribute can be placed on a function declaration. It istranslated into the LLVMconvergent
attribute, which indicates that the callinstructions of a function with this attribute cannot be made control-dependenton any additional values.
This attribute is different fromnoduplicate
because it allows duplicatingfunction calls if it can be proved that the duplicated function calls arenot made control-dependent on any additional values, e.g., unrolling a loopexecuted by all work items.
Sample usage:
voidconvfunc(void)__attribute__((convergent));// Setting it as a C++11 attribute is also valid in a C++ program.// void convfunc(void) [[clang::convergent]];
cpu_dispatch, cpu_specific¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
| Yes |
Thecpu_specific
andcpu_dispatch
attributes are used to define andresolve multiversioned functions. This form of multiversioning provides amechanism for declaring versions across translation units and manuallyspecifying the resolved function list. A specified CPU defines a set of minimumfeatures that are required for the function to be called. The result of this isthat future processors execute the most restrictive version of the function thenew processor can execute.
In addition, unlike the ICC implementation of this feature, the selection of theversion does not consider the manufacturer or microarchitecture of the processor.It tests solely the list of features that are both supported by the specifiedprocessor and present in the compiler-rt library. This can be surprising at times,as the runtime processor may be from a completely different manufacturer, as longas it supports the same feature set.
This can additionally be surprising, as some processors are indistringuishable fromothers based on the list of testable features. When this happens, the variantis selected in an unspecified manner.
Function versions are defined withcpu_specific
, which takes one or more CPUnames as a parameter. For example:
// Declares and defines the ivybridge version of single_cpu.__attribute__((cpu_specific(ivybridge)))voidsingle_cpu(void){}// Declares and defines the atom version of single_cpu.__attribute__((cpu_specific(atom)))voidsingle_cpu(void){}// Declares and defines both the ivybridge and atom version of multi_cpu.__attribute__((cpu_specific(ivybridge,atom)))voidmulti_cpu(void){}
A dispatching (or resolving) function can be declared anywhere in a project’ssource code withcpu_dispatch
. This attribute takes one or more CPU namesas a parameter (likecpu_specific
). Functions marked withcpu_dispatch
are not expected to be defined, only declared. If such a marked function has adefinition, any side effects of the function are ignored; trivial functionbodies are permissible for ICC compatibility.
// Creates a resolver for single_cpu above.__attribute__((cpu_dispatch(ivybridge,atom)))voidsingle_cpu(void){}// Creates a resolver for multi_cpu, but adds a 3rd version defined in another// translation unit.__attribute__((cpu_dispatch(ivybridge,atom,sandybridge)))voidmulti_cpu(void){}
Note that it is possible to have a resolving function that dispatches based onmore or fewer options than are present in the program. Specifying fewer willresult in the omitted options not being considered during resolution. Specifyinga version for resolution that isn’t defined in the program will result in alinking failure.
It is also possible to specify a CPU name ofgeneric
which will be resolvedif the executing processor doesn’t satisfy the features required in the CPUname. The behavior of a program executing on a processor that doesn’t satisfyany option of a multiversioned function is undefined.
device_kernel, sycl_kernel, nvptx_kernel, amdgpu_kernel, kernel, __kernel¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
These attributes specify that the function represents a kernel for device offloading.The specific semantics depend on the offloading language, target, and attribute spelling.Thesycl_kernel
attribute specifies that a function template will be usedto outline device code and to generate an OpenCL kernel.Here is a code example of the SYCL program, which demonstrates the compiler’soutlining job:
intfoo(intx){return++x;}usingnamespacecl::sycl;queueQ;buffer<int,1>a(range<1>{1024});Q.submit([&](handler&cgh){autoA=a.get_access<access::mode::write>(cgh);cgh.parallel_for<init_a>(range<1>{1024},[=](id<1>index){A[index]=index[0]+foo(42);});}
A C++ function object passed to theparallel_for
is called a “SYCL kernel”.A SYCL kernel defines the entry point to the “device part” of the code. Thecompiler will emit all symbols accessible from a “kernel”. In this codeexample, the compiler will emit “foo” function. More details about thecompilation of functions for the device part can be found in the SYCL 1.2.1specification Section 6.4.To show to the compiler entry point to the “device part” of the code, the SYCLruntime can use thesycl_kernel
attribute in the following way:
namespacecl{namespacesycl{classhandler{template<typenameKernelName,typenameKernelType/*, ...*/>__attribute__((sycl_kernel))voidsycl_kernel_function(KernelTypeKernelFuncObj){// ...KernelFuncObj();}template<typenameKernelName,typenameKernelType,intDims>voidparallel_for(range<Dims>NumWorkItems,KernelTypeKernelFunc){#ifdef __SYCL_DEVICE_ONLY__sycl_kernel_function<KernelName,KernelType,Dims>(KernelFunc);#else// Host implementation#endif}};}// namespace sycl}// namespace cl
The compiler will also generate an OpenCL kernel using the function marked withthesycl_kernel
attribute.Here is the list of SYCL device compiler expectations with regard to thefunction marked with thesycl_kernel
attribute:
The function must be a template with at least two type template parameters.The compiler generates an OpenCL kernel and uses the first template parameteras a unique name for the generated OpenCL kernel. The host application usesthis unique name to invoke the OpenCL kernel generated for the SYCL kernelspecialized by this name and second template parameter
KernelType
(whichmight be an unnamed function object type).The function must have at least one parameter. The first parameter isrequired to be a function object type (named or unnamed i.e. lambda). Thecompiler uses function object type fields to generate OpenCL kernelparameters.
The function must return void. The compiler reuses the body of marked functions togenerate the OpenCL kernel body, and the OpenCL kernel must return
void
.
The SYCL kernel in the previous code sample meets these expectations.
diagnose_as_builtin¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Thediagnose_as_builtin
attribute indicates that Fortify diagnostics are tobe applied to the declared function as if it were the function specified by theattribute. The builtin function whose diagnostics are to be mimicked should begiven. In addition, the order in which arguments should be applied must alsobe given.
For example, the attribute can be used as follows.
__attribute__((diagnose_as_builtin(__builtin_memset,3,2,1)))void*mymemset(intn,intc,void*s){// ...}
This indicates that calls tomymemset
should be diagnosed as if they werecalls to__builtin_memset
. The arguments3,2,1
indicate by index theorder in which arguments ofmymemset
should be applied to__builtin_memset
. The third argument should be applied first, then thesecond, and then the first. Thus (when Fortify warnings are enabled) the callmymemset(n,c,s)
will diagnose overflows as if it were the call__builtin_memset(s,c,n)
.
For variadic functions, the variadic arguments must come in the same order asthey would to the builtin function, after all normal arguments. For instance,to diagnose a new function as if it weresscanf, we can use the attribute asfollows.
__attribute__((diagnose_as_builtin(sscanf,1,2)))intmysscanf(constchar*str,constchar*format,...){// ...}
Then the callmysscanf(“abc def”, “%4s %4s”, buf1, buf2) will be diagnosed asif it were the callsscanf(“abc def”, “%4s %4s”, buf1, buf2).
This attribute cannot be applied to non-static member functions.
diagnose_if¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
Thediagnose_if
attribute can be placed on function declarations to emitwarnings or errors at compile-time if calls to the attributed function meetcertain user-defined criteria. For example:
intabs(inta)__attribute__((diagnose_if(a>=0,"Redundant abs call","warning")));intmust_abs(inta)__attribute__((diagnose_if(a>=0,"Redundant abs call","error")));intval=abs(1);// warning: Redundant abs callintval2=must_abs(1);// error: Redundant abs callintval3=abs(val);intval4=must_abs(val);// Because run-time checks are not emitted for// diagnose_if attributes, this executes without// issue.
diagnose_if
is closely related toenable_if
, with a few key differences:
Overload resolution is not aware of
diagnose_if
attributes: they’reconsidered only after we select the best candidate from a given candidate set.Function declarations that differ only in their
diagnose_if
attributes areconsidered to be redeclarations of the same function (not overloads).If the condition provided to
diagnose_if
cannot be evaluated, nodiagnostic will be emitted.
Otherwise,diagnose_if
is essentially the logical negation ofenable_if
.
As a result of bullet number two,diagnose_if
attributes will stack on thesame function. For example:
intfoo()__attribute__((diagnose_if(1,"diag1","warning")));intfoo()__attribute__((diagnose_if(1,"diag2","warning")));intbar=foo();// warning: diag1// warning: diag2int(*fooptr)(void)=foo;// warning: diag1// warning: diag2constexprintsupportsAPILevel(intN){returnN<5;}intbaz(inta)__attribute__((diagnose_if(!supportsAPILevel(10),"Upgrade to API level 10 to use baz","error")));intbaz(inta)__attribute__((diagnose_if(!a,"0 is not recommended.","warning")));int(*bazptr)(int)=baz;// error: Upgrade to API level 10 to use bazintv=baz(0);// error: Upgrade to API level 10 to use baz
Query for this feature with__has_attribute(diagnose_if)
.
disable_sanitizer_instrumentation¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Use thedisable_sanitizer_instrumentation
attribute on a function,Objective-C method, or global variable, to specify that no sanitizerinstrumentation should be applied.
This is not the same as__attribute__((no_sanitize(...)))
, which dependingon the tool may still insert instrumentation to prevent false positive reports.
disable_tail_calls¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Thedisable_tail_calls
attribute instructs the backend to not perform tailcall optimization inside the marked function.
For example:
intcallee(int);intfoo(inta)__attribute__((disable_tail_calls)){returncallee(a);// This call is not tail-call optimized.}
Marking virtual functions asdisable_tail_calls
is legal.
intcallee(int);classBase{public:[[clang::disable_tail_calls]]virtualintfoo1(){returncallee();// This call is not tail-call optimized.}};classDerived1:publicBase{public:intfoo1()override{returncallee();// This call is tail-call optimized.}};
enable_if¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
Note
Some features of this attribute are experimental. The meaning ofmultiple enable_if attributes on a single declaration is subject to change ina future version of clang. Also, the ABI is not standardized and the namemangling may change in future versions. To avoid that, use asm labels.
Theenable_if
attribute can be placed on function declarations to controlwhich overload is selected based on the values of the function’s arguments.When combined with theoverloadable
attribute, this feature is alsoavailable in C.
intisdigit(intc);intisdigit(intc)__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")));voidfoo(charc){isdigit(c);isdigit(10);isdigit(-10);// results in a compile-time error.}
The enable_if attribute takes two arguments, the first is an expression writtenin terms of the function parameters, the second is a string explaining why thisoverload candidate could not be selected to be displayed in diagnostics. Theexpression is part of the function signature for the purposes of determiningwhether it is a redeclaration (following the rules used when determiningwhether a C++ template specialization is ODR-equivalent), but is not part ofthe type.
The enable_if expression is evaluated as if it were the body of abool-returning constexpr function declared with the arguments of the functionit is being applied to, then called with the parameters at the call site. If theresult is false or could not be determined through constant expressionevaluation, then this overload will not be chosen and the provided string maybe used in a diagnostic if the compile fails as a result.
Because the enable_if expression is an unevaluated context, there are no globalstate changes, nor the ability to pass information from the enable_ifexpression to the function body. For example, suppose we want calls tostrnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size ofstrbuf) only if the size of strbuf can be determined:
__attribute__((always_inline))staticinlinesize_tstrnlen(constchar*s,size_tmaxlen)__attribute__((overloadable))__attribute__((enable_if(__builtin_object_size(s,0)!=-1))),"chosen when the buffer size is known but 'maxlen' is not"))){returnstrnlen_chk(s,maxlen,__builtin_object_size(s,0));}
Multiple enable_if attributes may be applied to a single declaration. In thiscase, the enable_if expressions are evaluated from left to right in thefollowing manner. First, the candidates whose enable_if expressions evaluate tofalse or cannot be evaluated are discarded. If the remaining candidates do notshare ODR-equivalent enable_if expressions, the overload resolution isambiguous. Otherwise, enable_if overload resolution continues with the nextenable_if attribute on the candidates that have not been discarded and haveremaining enable_if attributes. In this way, we pick the most specificoverload out of a number of viable overloads using enable_if.
voidf()__attribute__((enable_if(true,"")));// #1voidf()__attribute__((enable_if(true,"")))__attribute__((enable_if(true,"")));// #2voidg(inti,intj)__attribute__((enable_if(i,"")));// #1voidg(inti,intj)__attribute__((enable_if(j,"")))__attribute__((enable_if(true)));// #2
In this example, a call to f() is always resolved to #2, as the first enable_ifexpression is ODR-equivalent for both declarations, but #1 does not have anotherenable_if expression to continue evaluating, so the next round of evaluation hasonly a single candidate. In a call to g(1, 1), the call is ambiguous even though#2 has more enable_if attributes, because the first enable_if expressions arenot ODR-equivalent.
Query for this feature with__has_attribute(enable_if)
.
Note that functions with one or moreenable_if
attributes may not havetheir address taken, unless all of the conditions specified by saidenable_if
are constants that evaluate totrue
. For example:
constintTrueConstant=1;constintFalseConstant=0;intf(inta)__attribute__((enable_if(a>0,"")));intg(inta)__attribute__((enable_if(a==0||a!=0,"")));inth(inta)__attribute__((enable_if(1,"")));inti(inta)__attribute__((enable_if(TrueConstant,"")));intj(inta)__attribute__((enable_if(FalseConstant,"")));voidfn(){int(*ptr)(int);ptr=&f;// error: 'a > 0' is not always trueptr=&g;// error: 'a == 0 || a != 0' is not a truthy constantptr=&h;// OK: 1 is a truthy constantptr=&i;// OK: 'TrueConstant' is a truthy constantptr=&j;// error: 'FalseConstant' is a constant, but not truthy}
Becauseenable_if
evaluation happens during overload resolution,enable_if
may give unintuitive results when used with templates, dependingon when overloads are resolved. In the example below, clang will emit adiagnostic about no viable overloads forfoo
inbar
, but not inbaz
:
doublefoo(inti)__attribute__((enable_if(i>0,"")));void*foo(inti)__attribute__((enable_if(i<=0,"")));template<intI>autobar(){returnfoo(I);}template<typenameT>autobaz(){returnfoo(T::number);}structWithNumber{constexprstaticintnumber=1;};voidcallThem(){bar<sizeof(WithNumber)>();baz<WithNumber>();}
This is because, inbar
,foo
is resolved prior to templateinstantiation, so the value forI
isn’t known (thus, bothenable_if
conditions forfoo
fail). However, inbaz
,foo
is resolved duringtemplate instantiation, so the value forT::number
is known.
enforce_tcb¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
- The
enforce_tcb
attribute can be placed on functions to enforce that a trusted compute base (TCB) does not call out of the TCB. This generates awarning every time a function not marked with an
enforce_tcb
attribute iscalled from a function with theenforce_tcb
attribute. A function may be apart of multiple TCBs. Invocations through function pointers are currentlynot checked. Builtins are considered to a part of every TCB.enforce_tcb(Name)
indicates that this function is a part of the TCB namedName
enforce_tcb_leaf¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
- The
enforce_tcb_leaf
attribute satisfies the requirement enforced by enforce_tcb
for the marked function to be in the named TCB but does notcontinue to check the functions called from within the leaf function.enforce_tcb_leaf(Name)
indicates that this function is a part of the TCB namedName
error, warning¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theerror
andwarning
function attributes can be used to specify acustom diagnostic to be emitted when a call to such a function is noteliminated via optimizations. This can be used to create compile timeassertions that depend on optimizations, while providing diagnosticspointing to precise locations of the call site in the source.
__attribute__((warning("oh no")))voiddontcall();voidfoo(){if(someCompileTimeAssertionThatsTrue)dontcall();// Warningdontcall();// Warningif(someCompileTimeAssertionThatsFalse)dontcall();// No Warningsizeof(dontcall());// No Warning}
exclude_from_explicit_instantiation¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theexclude_from_explicit_instantiation
attribute opts-out a member of aclass template from being part of explicit template instantiations of thatclass template. This means that an explicit instantiation will not instantiatemembers of the class template marked with the attribute, but also that codewhere an extern template declaration of the enclosing class template is visiblewill not take for granted that an external instantiation of the class templatewould provide those members (which would otherwise be a link error, since theexplicit instantiation won’t provide those members). For example, let’s say wedon’t want thedata()
method to be part of libc++’s ABI. To make sure itis not exported from the dylib, we give it hidden visibility:
// in <string>template<classCharT>classbasic_string{public:__attribute__((__visibility__("hidden")))constvalue_type*data()constnoexcept{...}};templateclassbasic_string<char>;
Since an explicit template instantiation declaration forbasic_string<char>
is provided, the compiler is free to assume thatbasic_string<char>::data()
will be provided by another translation unit, and it is free to produce anexternal call to this function. However, sincedata()
has hidden visibilityand the explicit template instantiation is provided in a shared library (asopposed to simply another translation unit),basic_string<char>::data()
won’t be found and a link error will ensue. This happens because the compilerassumes thatbasic_string<char>::data()
is part of the explicit templateinstantiation declaration, when it really isn’t. To tell the compiler thatdata()
is not part of the explicit template instantiation declaration, theexclude_from_explicit_instantiation
attribute can be used:
// in <string>template<classCharT>classbasic_string{public:__attribute__((__visibility__("hidden")))__attribute__((exclude_from_explicit_instantiation))constvalue_type*data()constnoexcept{...}};templateclassbasic_string<char>;
Now, the compiler won’t assume thatbasic_string<char>::data()
is providedexternally despite there being an explicit template instantiation declaration:the compiler will implicitly instantiatebasic_string<char>::data()
in theTUs where it is used.
This attribute can be used on static and non-static member functions of classtemplates, static data members of class templates and member classes of classtemplates.
export_name, __funcref¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
| Yes |
Clang supports the__attribute__((export_name(<name>)))
attribute for the WebAssembly target. This attribute may be attached to afunction declaration, where it modifies how the symbol is to be exportedfrom the linked WebAssembly.
WebAssembly functions are exported via string name. By default when a symbolis exported, the export name for C/C++ symbols are the same as their C/C++symbol names. This attribute can be used to override the default behavior, andrequest a specific string name be used instead.
ext_vector_type¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Theext_vector_type(N)
attribute specifies that a type is a vector with Nelements, directly mapping to an LLVM vector type. Originally from OpenCL, itallows element access the array subscript operator[]
,sN
where N isa hexadecimal value, orx,y,z,w
for graphics-style indexing.This attribute enables efficient SIMD operations and is usable ingeneral-purpose code.
template<typenameT,uint32_tN>constexprTsimd_reduce(T[[clang::ext_vector_type(N)]]v){static_assert((N&(N-1))==0,"N must be a power of two");ifconstexpr(N==1)returnv[0];elsereturnsimd_reduce<T,N/2>(v.hi+v.lo);}
The vector type also supports swizzling up to sixteen elements. This can be doneusing the object accessors. The OpenCL documentation lists all of the acceptedvalues.
usingf16_x16=_Float16__attribute__((ext_vector_type(16)));f16_x16reverse(f16_x16v){returnv.sfedcba9876543210;}
See the OpenCL documentation for some more complete examples.
flatten¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theflatten
attribute causes calls within the attributed function tobe inlined unless it is impossible to do so, for example if the body of thecallee is unavailable or if the callee has thenoinline
attribute.
force_align_arg_pointer¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Use this attribute to force stack alignment.
Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions(like ‘movaps’) that work with the stack require operands to be 16-byte aligned.This attribute realigns the stack in the function prologue to make sure thestack can be used with SSE instructions.
Note that the x86_64 ABI forces 16-byte stack alignment at the call site.Because of this, ‘force_align_arg_pointer’ is not needed on x86_64, except inrare cases where the caller does not align the stack properly (e.g. flowjumps from i386 arch code).
__attribute__((force_align_arg_pointer))voidf(){...}
format¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Clang supports theformat
attribute, which indicates that the functionaccepts (among other possibilities) aprintf
orscanf
-like format stringand corresponding arguments or ava_list
that contains these arguments.
Please seeGCC documentation about format attribute to find detailsabout attribute syntax.
Clang implements two kinds of checks with this attribute.
Clang checks that the function with the
format
attribute is called witha format string that uses format specifiers that are allowed, and thatarguments match the format string. This is the-Wformat
warning, it ison by default.Clang checks that the format string argument is a literal string. This isthe
-Wformat-nonliteral
warning, it is off by default.Clang implements this mostly the same way as GCC, but there is a differencefor functions that accept a
va_list
argument (for example,vprintf
).GCC does not emit-Wformat-nonliteral
warning for calls to suchfunctions. Clang does not warn if the format string comes from a functionparameter, where the function is annotated with a compatible attribute,otherwise it warns. For example:__attribute__((__format__(__scanf__,1,3)))voidfoo(constchar*s,char*buf,...){va_listap;va_start(ap,buf);vprintf(s,ap);// warning: format string is not a string literal}
In this case we warn because
s
contains a format string for ascanf
-like function, but it is passed to aprintf
-like function.If the attribute is removed, clang still warns, because the format string isnot a string literal.
Another example:
__attribute__((__format__(__printf__,1,3)))voidfoo(constchar*s,char*buf,...){va_listap;va_start(ap,buf);vprintf(s,ap);// warning}
In this case Clang does not warn because the format string
s
andthe corresponding arguments are annotated. If the arguments areincorrect, the caller offoo
will receive a warning.
As an extension to GCC’s behavior, Clang accepts theformat
attribute onnon-variadic functions. Clang checks non-variadic format functions for the sameclasses of issues that can be found on variadic functions, as controlled by thesame warning flags, except that the types of formatted arguments is forced bythe function signature. For example:
__attribute__((__format__(__printf__,1,2)))voidfmt(constchar*s,constchar*a,intb);voidbar(void){fmt("%s %i","hello",123);// OKfmt("%i %g","hello",123);// warning: arguments don't match formatexternconstchar*fmt;fmt(fmt,"hello",123);// warning: format string is not a string literal}
When using the format attribute on a variadic function, the first data parameter_must_ be the index of the ellipsis in the parameter list. Clang will generatea diagnostic otherwise, as it wouldn’t be possible to forward that argument listtoprintf-family functions. For instance, this is an error:
__attribute__((__format__(__printf__,1,2)))voidfmt(constchar*s,intb,...);// ^ error: format attribute parameter 3 is out of bounds// (must be __printf__, 1, 3)
Using theformat
attribute on a non-variadic function emits a GCCcompatibility diagnostic.
format_matches¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Theformat
attribute is the basis for the enforcement of diagnostics in the-Wformat
family, but it only handles the case where the format string ispassed along with the arguments it is going to format. It cannot handle the casewhere the format string and the format arguments are passed separately from eachother. For instance:
staticconstchar*first_name;staticdoubletodays_temperature;staticintwind_speed;voidsay_hi(constchar*fmt){printf(fmt,first_name,todays_temperature);// ^ warning: format string is not a string literalprintf(fmt,first_name,wind_speed);// ^ warning: format string is not a string literal}intmain(){say_hi("hello %s, it is %g degrees outside");say_hi("hello %s, it is %d degrees outside!");// ^ no diagnostic, but %d cannot format doubles}
In this example,fmt
is expected to format aconstchar*
and adouble
, but these values are not passed tosay_hi
. Without theformat
attribute (which cannot apply in this case), the -Wformat-nonliteraldiagnostic unnecessarily triggers in the body ofsay_hi
, and incorrectsay_hi
call sites do not trigger a diagnostic.
To complement theformat
attribute, Clang also defines theformat_matches
attribute. Its syntax is similar to theformat
attribute’s, but instead of taking the index of the first formatted valueargument, it takes a C string literal with the expected specifiers:
staticconstchar*first_name;staticdoubletodays_temperature;staticintwind_speed;__attribute__((__format_matches__(printf,1,"%s %g")))voidsay_hi(constchar*fmt){printf(fmt,first_name,todays_temperature);// no dignosticprintf(fmt,first_name,wind_speed);// warning: format specifies type 'int' but the argument has type 'double'}intmain(){say_hi("hello %s, it is %g degrees outside");say_hi("it is %g degrees outside, have a good day %s!");// warning: format specifies 'double' where 'const char *' is required// warning: format specifies 'const char *' where 'double' is required}
The third argument toformat_matches
is expected to evaluate to aC stringliteral even when the format string would normally be a different type for thegiven flavor, like aCFStringRef
or aNSString*
.
The only requirement on the format string literal is that it has specifiersthat are compatible with the arguments that will be used. It can containarbitrary non-format characters. For instance, for the purposes of compile-timevalidation,"%sscored%g%%onhertest"
and"%s%g"
are interchangeableas the format string argument. As a means of self-documentation, users mayprefer the former when it provides a useful example of an expected formatstring.
In the implementation of a function with theformat_matches
attribute,format verification works as if the format string was identical to the onespecified in the attribute.
__attribute__((__format_matches__(printf,1,"%s %g")))voidsay_hi(constchar*fmt){printf(fmt,"person",546);// ^ warning: format specifies type 'double' but the// argument has type 'int'// note: format string is defined here:// __attribute__((__format_matches__(printf, 1, "%s %g")))// ^~}
At the call sites of functions with theformat_matches
attribute, formatverification instead compares the two format strings to evaluate theirequivalence. Each format flavor defines equivalence between format specifiers.Generally speaking, two specifiers are equivalent if they format the same type.For instance, in theprintf
flavor,%2i
and%-0.5d
are compatible.When-Wformat-signedness
is disabled,%d
and%u
are compatible. Fora negative example,%ld
is incompatible with%d
.
Do note the following un-obvious cases:
Passing
NULL
as the format string does not trigger format diagnostics.When the format string is not NULL, it cannot _miss_ specifiers, even intrailing positions. For instance,
%d
is not accepted when the requiredformat is%d%d%d
.While checks for the
format
attribute tolerate sone size mismatchesthat standard argument promotion renders immaterial (such as formatting anint
with%hhd
, which specifies achar
-sized integer), checks forformat_matches
require specified argument sizes to match exactly.Format strings expecting a variable modifier (such as
%*s
) areincompatible with format strings that would itemize the variable modifiers(such as%i%s
), even if the two specify ABI-compatible argument lists.All pointer specifiers, modifiers aside, are mutually incompatible. Forinstance,
%s
is not compatible with%p
, and%p
is not compatiblewith%n
, and%hhn
is incompatible with%s
, even if the pointersare ABI-compatible or identical on the selected platform. However,%0.5s
is compatible with%s
, since the difference only exists in modifier flags.This is not overridable with-Wformat-pedantic
or its inverse, whichcontrol similar behavior in-Wformat
.
At this time, clang implementsformat_matches
only for format types in theprintf
family. This includes variants such as Apple’s NSString format andthe FreeBSDkprintf
, but excludesscanf
. Using a known but unsupportedformat silently fails in order to be compatible with other implementations thatwould support these formats.
function_return¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
The attributefunction_return
can replace return instructions with jumps totarget-specific symbols. This attribute supports 2 possible values,corresponding to the values supported by the-mfunction-return=
commandline flag:
__attribute__((function_return("keep")))
to disable related transforms.This is useful for undoing global setting from-mfunction-return=
locallyfor individual functions.__attribute__((function_return("thunk-extern")))
to replace returns withjumps, while NOT emitting the thunk.
The valuesthunk
andthunk-inline
from GCC are not supported.
The symbol used forthunk-extern
is target specific:* X86:__x86_return_thunk
As such, this function attribute is currently only supported on X86 targets.
gnu_inline¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Thegnu_inline
changes the meaning ofexterninline
to use GNU inlinesemantics, meaning:
If any declaration that is declared
inline
is not declaredextern
,then theinline
keyword is just a hint. In particular, an out-of-linedefinition is still emitted for a function with external linkage, even if allcall sites are inlined, unlike in C99 and C++ inline semantics.If all declarations that are declared
inline
are also declaredextern
, then the function body is present only for inlining and noout-of-line version is emitted.
Some important consequences:staticinline
emits an out-of-lineversion if needed, a plaininline
definition emits an out-of-line versionalways, and anexterninline
definition (in a header) followed by a(non-extern
)inline
declaration in a source file emits an out-of-lineversion of the function in that source file but provides the function body forinlining to all includers of the header.
Either__GNUC_GNU_INLINE__
(GNU inline semantics) or__GNUC_STDC_INLINE__
(C99 semantics) will be defined (they are mutuallyexclusive). If__GNUC_STDC_INLINE__
is defined, then thegnu_inline
function attribute can be used to get GNU inline semantics on a per functionbasis. If__GNUC_GNU_INLINE__
is defined, then the translation unit isalready being compiled with GNU inline semantics as the implied default. It isunspecified which macro is defined in a C++ compilation.
GNU inline semantics are the default behavior with-std=gnu89
,-std=c89
,-std=c94
, or-fgnu89-inline
.
guard¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
| Yes |
Code can indicate CFG checks are not wanted with the__declspec(guard(nocf))
attribute. This directs the compiler to not insert any CFG checks for the entirefunction. This approach is typically used only sparingly in specific situationswhere the programmer has manually inserted “CFG-equivalent” protection. Theprogrammer knows that they are calling through some read-only function tablewhose address is obtained through read-only memory references and for which theindex is masked to the function table limit. This approach may also be appliedto small wrapper functions that are not inlined and that do nothing more thanmake a call through a function pointer. Since incorrect usage of this directivecan compromise the security of CFG, the programmer must be very careful usingthe directive. Typically, this usage is limited to very small functions thatonly call one function.
Control Flow Guard documentation <https://docs.microsoft.com/en-us/windows/win32/secbp/pe-metadata>
hot¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
__attribute__((hot))
marks a function as hot, as a manual alternative to PGO hotness data.If PGO data is available, the annotation__attribute__((hot))
overrides the profile count based hotness (unlike__attribute__((cold))
).
hybrid_patchable¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
| Yes |
Thehybrid_patchable
attribute declares an ARM64EC function with an additionalx86-64 thunk, which may be patched at runtime.
For more information seeARM64EC ABI documentation.
ifunc¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
__attribute__((ifunc("resolver")))
is used to mark that the address of adeclaration should be resolved at runtime by calling a resolver function.
The symbol name of the resolver function is given in quotes. A function withthis name (after mangling) must be defined in the current translation unit; itmay bestatic
. The resolver function should return a pointer.
Theifunc
attribute may only be used on a function declaration. A functiondeclaration with anifunc
attribute is considered to be a definition of thedeclared entity. The entity must not have weak linkage; for example, in C++,it cannot be applied to a declaration if a definition at that location would beconsidered inline.
Not all targets support this attribute:
ELF target support depends on both the linker and runtime linker, and isavailable in at least lld 4.0 and later, binutils 2.20.1 and later, glibcv2.11.1 and later, and FreeBSD 9.1 and later.
Mach-O targets support it, but with slightly different semantics: the resolveris run at first call, instead of at load time by the runtime linker.
Windows target supports it on AArch64, but with different semantics: the
ifunc
is replaced with a global function pointer, and the call is replacedwith an indirect call. The function pointer is initialized by a constructorthat calls the resolver.Baremetal target supports it on AVR.
Other targets currently do not support this attribute.
import_module¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang supports the__attribute__((import_module(<module_name>)))
attribute for the WebAssembly target. This attribute may be attached to afunction declaration, where it modifies how the symbol is to be importedwithin the WebAssembly linking environment.
WebAssembly imports use a two-level namespace scheme, consisting of a modulename, which typically identifies a module from which to import, and a fieldname, which typically identifies a field from that module to import. Bydefault, module names for C/C++ symbols are assigned automatically by thelinker. This attribute can be used to override the default behavior, andrequest a specific module name be used instead.
import_name¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang supports the__attribute__((import_name(<name>)))
attribute for the WebAssembly target. This attribute may be attached to afunction declaration, where it modifies how the symbol is to be importedwithin the WebAssembly linking environment.
WebAssembly imports use a two-level namespace scheme, consisting of a modulename, which typically identifies a module from which to import, and a fieldname, which typically identifies a field from that module to import. Bydefault, field names for C/C++ symbols are the same as their C/C++ symbolnames. This attribute can be used to override the default behavior, andrequest a specific field name be used instead.
internal_linkage¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theinternal_linkage
attribute changes the linkage type of the declarationto internal. This is similar to C-stylestatic
, but can be used on classesand class methods. When applied to a class definition, this attribute affectsall methods and static data members of that class. This can be used to containthe ABI of a C++ library by excluding unwanted class methods from the exporttables.
interrupt (ARM)¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Clang supports the GNU style__attribute__((interrupt("TYPE")))
attribute onARM targets. This attribute may be attached to a function definition andinstructs the backend to generate appropriate function entry/exit code so thatit can be used directly as an interrupt service routine.
The parameter passed to the interrupt attribute is optional, but ifprovided it must be a string literal with one of the following values: “IRQ”,“FIQ”, “SWI”, “ABORT”, “UNDEF”.
The semantics are as follows:
If the function is AAPCS, Clang instructs the backend to realign the stack to8 bytes on entry. This is a general requirement of the AAPCS at publicinterfaces, but may not hold when an exception is taken. Doing this allowsother AAPCS functions to be called.
If the CPU is M-class this is all that needs to be done since the architectureitself is designed in such a way that functions obeying the normal AAPCS ABIconstraints are valid exception handlers.
If the CPU is not M-class, the prologue and epilogue are modified to save allnon-banked registers that are used, so that upon return the user-mode statewill not be corrupted. Note that to avoid unnecessary overhead, onlygeneral-purpose (integer) registers are saved in this way. If VFP operationsare needed, that state must be saved manually.
Specifically, interrupt kinds other than “FIQ” will save all core registersexcept “lr” and “sp”. “FIQ” interrupts will save r0-r7.
If the CPU is not M-class, the return instruction is changed to one of thecanonical sequences permitted by the architecture for exception return. Wherepossible the function itself will make the necessary “lr” adjustments so thatthe “preferred return address” is selected.
Unfortunately the compiler is unable to make this guarantee for an “UNDEF”handler, where the offset from “lr” to the preferred return address depends onthe execution state of the code which generated the exception. In this casea sequence equivalent to “movs pc, lr” will be used.
interrupt (AVR)¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang supports the GNU style__attribute__((interrupt))
attribute onAVR targets. This attribute may be attached to a function definition and instructsthe backend to generate appropriate function entry/exit code so that it can be useddirectly as an interrupt service routine.
On the AVR, the hardware globally disables interrupts when an interrupt is executed.The first instruction of an interrupt handler declared with this attribute is a SEIinstruction to re-enable interrupts. See also the signal attribute thatdoes not insert a SEI instruction.
interrupt (MIPS)¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang supports the GNU style__attribute__((interrupt("ARGUMENT")))
attribute onMIPS targets. This attribute may be attached to a function definition and instructsthe backend to generate appropriate function entry/exit code so that it can be useddirectly as an interrupt service routine.
By default, the compiler will produce a function prologue and epilogue suitable foran interrupt service routine that handles an External Interrupt Controller (eic)generated interrupt. This behavior can be explicitly requested with the “eic”argument.
Otherwise, for use with vectored interrupt mode, the argument passed should beof the form “vector=LEVEL” where LEVEL is one of the following values:“sw0”, “sw1”, “hw0”, “hw1”, “hw2”, “hw3”, “hw4”, “hw5”. The compiler willthen set the interrupt mask to the corresponding level which will mask allinterrupts up to and including the argument.
The semantics are as follows:
The prologue is modified so that the Exception Program Counter (EPC) andStatus coprocessor registers are saved to the stack. The interrupt mask isset so that the function can only be interrupted by a higher priorityinterrupt. The epilogue will restore the previous values of EPC and Status.
The prologue and epilogue are modified to save and restore all non-kernelregisters as necessary.
The FPU is disabled in the prologue, as the floating pointer registers are notspilled to the stack.
The function return sequence is changed to use an exception return instruction.
The parameter sets the interrupt mask for the function corresponding to theinterrupt level specified. If no mask is specified the interrupt maskdefaults to “eic”.
interrupt (RISC-V)¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang supports the GNU style__attribute__((interrupt))
attribute on RISCVtargets. This attribute may be attached to a function definition and instructsthe backend to generate appropriate function entry/exit code so that it can beused directly as an interrupt service routine.
Permissible values for this parameter aremachine
,supervisor
,qci-nest
,qci-nonest
,SiFive-CLIC-preemptible
, andSiFive-CLIC-stack-swap
. If there is no parameter, then it defaults tomachine
.
Theqci-nest
andqci-nonest
values require Qualcomm’s Xqciint extensionand are used for Machine-mode Interrupts and Machine-mode Non-maskableinterrupts. These use the following instructions from Xqciint to save andrestore interrupt state to the stack – theqci-nest
value will useqc.c.mienter.nest
and theqci-nonest
value will useqc.c.mienter
tobegin the interrupt handler. Both of these will useqc.c.mileaveret
torestore the state and return to the previous context.
TheSiFive-CLIC-preemptible
andSiFive-CLIC-stack-swap
values are usedfor machine-mode interrupts. ForSiFive-CLIC-preemptible
interrupts, thevalues ofmcause
andmepc
are saved onto the stack, and interrupts arere-enabled. ForSiFive-CLIC-stack-swap
interrupts, the stack pointer isswapped withmscratch
before its first use and after its last use.
The SiFive CLIC values may be combined with each other and with themachine
attribute value. Any other combination of different values is not allowed.
Repeated interrupt attribute on the same declaration will cause a warningto be emitted. In case of repeated declarations, the last one prevails.
Refer to:https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.htmlhttps://riscv.org/specifications/privileged-isa/The RISC-V Instruction Set Manual Volume II: Privileged ArchitectureVersion 1.10.https://github.com/quic/riscv-unified-db/releases/tag/Xqci-0.13.0https://sifive.cdn.prismic.io/sifive/d1984d2b-c9b9-4c91-8de0-d68a5e64fa0f_sifive-interrupt-cookbook-v1p2.pdf
interrupt (X86)¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Clang supports the GNU style__attribute__((interrupt))
attribute on X86targets. This attribute may be attached to a function definition and instructsthe backend to generate appropriate function entry/exit code so that it can beused directly as an interrupt service routine.
Interrupt handlers have access to the stack frame pushed onto the stack by the processor,and return using theIRET
instruction. All registers in an interrupt handler are callee-saved.Exception handlers also have access to the error code pushed onto the stack by the processor,when applicable.
An interrupt handler must take the following arguments:
__attribute__((interrupt))voidf(structstack_frame*frame){...}Where
structstack_frame
is a suitable struct matching the stack frame pushed by theprocessor.
An exception handler must take the following arguments:
__attribute__((interrupt))voidg(structstack_frame*frame,unsignedlongcode){...}On 32-bit targets, the
code
argument should be of typeunsignedint
.
Exception handlers should only be used when an error code is pushed by the processor.Using the incorrect handler type will crash the system.
Interrupt and exception handlers cannot be called by other functions and must have return typevoid
.
Interrupt and exception handlers should only call functions with the ‘no_caller_saved_registers’attribute, or should be compiled with the ‘-mgeneral-regs-only’ flag to avoid saving unusednon-GPR registers.
interrupt_save_fp (ARM)¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
Clang supports the GNU style__attribute__((interrupt_save_fp("TYPE")))
on ARM targets. This attribute behaves the same way as the ARM interruptattribute, except the general purpose floating point registers are also saved,along with FPEXC and FPSCR. Note, even on M-class CPUs, where the floatingpoint context can be automatically saved depending on the FPCCR, the generalpurpose floating point registers will be saved.
lifetime_capture_by¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
Similar tolifetimebound, thelifetime_capture_by(X)
attribute on afunction parameter or implicit object parameter indicates that the capturingentityX
may refer to the object referred by that parameter.
Below is a list of types of the parameters and what they’re considered to refer to:
A reference param (of non-view type) is considered to refer to its referenced object.
A pointer param (of non-view type) is considered to refer to its pointee.
View type param (type annotated with
[[gsl::Pointer()]]
) is considered to referto its pointee (gsl owner). This holds true even if the view type appears as a referencein the parameter. For example, bothstd::string_view
andconststd::string_view&
are considered to refer to astd::string
.A
std::initializer_list<T>
is considered to refer to its underlying array.Aggregates (arrays and simple
struct
s) are considered to refer to allobjects that their transitive subobjects refer to.
Clang would diagnose when a temporary object is used as an argument to such anannotated parameter.In this case, the capturing entityX
could capture a dangling reference to thistemporary object.
voidaddToSet(std::string_viewa[[clang::lifetime_capture_by(s)]],std::set<std::string_view>&s){s.insert(a);}voiduse(){std::set<std::string_view>s;addToSet(std::string(),s);// Warning: object whose reference is captured by 's' will be destroyed at the end of the full-expression.// ^^^^^^^^^^^^^std::stringlocal;addToSet(local,s);// Ok.}
The capturing entityX
can be one of the following:
Another (named) function parameter.
voidaddToSet(std::string_viewa[[clang::lifetime_capture_by(s)]],std::set<std::string_view>&s){s.insert(a);}
this
(in case of member functions).classS{voidaddToSet(std::string_viewa[[clang::lifetime_capture_by(this)]]){s.insert(a);}std::set<std::string_view>s;};
Note: When applied to a constructor parameter,[[clang::lifetime_capture_by(this)]] is just an alias of[[clang::lifetimebound]].
global,unknown.
std::set<std::string_view>s;voidaddToSet(std::string_viewa[[clang::lifetime_capture_by(global)]]){s.insert(a);}voidaddSomewhere(std::string_viewa[[clang::lifetime_capture_by(unknown)]]);
The attribute can be applied to the implicitthis
parameter of a memberfunction by writing the attribute after the function type:
structS{constchar*data(std::set<S*>&s)[[clang::lifetime_capture_by(s)]]{s.insert(this);}};
The attribute supports specifying more than one capturing entities:
voidaddToSets(std::string_viewa[[clang::lifetime_capture_by(s1,s2)]],std::set<std::string_view>&s1,std::set<std::string_view>&s2){s1.insert(a);s2.insert(a);}
Limitation: The capturing entityX
is not used by the analysis and isused for documentation purposes only. This is because the analysis isstatement-local and only detects use of a temporary as an argument to theannotated parameter.
voidaddToSet(std::string_viewa[[clang::lifetime_capture_by(s)]],std::set<std::string_view>&s);voiduse(){std::set<std::string_view>s;if(foo()){std::stringstr;addToSet(str,s);// Not detected.}}
lifetimebound¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
Thelifetimebound
attribute on a function parameter or implicit objectparameter indicates that objects that are referred to by that parameter mayalso be referred to by the return value of the annotated function (or, for aparameter of a constructor, by the value of the constructed object).
By default, a reference is considered to refer to its referenced object, apointer is considered to refer to its pointee, astd::initializer_list<T>
is considered to refer to its underlying array, and aggregates (arrays andsimplestruct
s) are considered to refer to all objects that theirtransitive subobjects refer to.
Clang warns if it is able to detect that an object or reference refers toanother object with a shorter lifetime. For example, Clang will warn if afunction returns a reference to a local variable, or if a reference is bound toa temporary object whose lifetime is not extended. By using thelifetimebound
attribute, this determination can be extended to look throughuser-declared functions. For example:
#include<map>#include<string>usingnamespacestd::literals;// Returns m[key] if key is present, or default_value if not.template<typenameT,typenameU>constU&get_or_default(conststd::map<T,U>&m[[clang::lifetimebound]],constT&key,/* note, not lifetimebound */constU&default_value[[clang::lifetimebound]]){if(autoiter=m.find(key);iter!=m.end())returniter->second;elsereturndefault_value;}intmain(){std::map<std::string,std::string>m;// warning: temporary bound to local reference 'val1' will be destroyed// at the end of the full-expressionconststd::string&val1=get_or_default(m,"foo"s,"bar"s);// No warning in this case.std::stringdef_val="bar"s;conststd::string&val2=get_or_default(m,"foo"s,def_val);return0;}
The attribute can be applied to the implicitthis
parameter of a memberfunction by writing the attribute after the function type:
structstring{// The returned pointer should not outlive ``*this``.constchar*data()const[[clang::lifetimebound]];};
This attribute is inspired by the C++ committee paperP0936R0, but does not affect whether temporary objectshave their lifetimes extended.
long_call, far¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang supports the__attribute__((long_call))
,__attribute__((far))
,and__attribute__((near))
attributes on MIPS targets. These attributes mayonly be added to function declarations and change the code generatedby the compiler when directly calling the function. Thenear
attributeallows calls to the function to be made using thejal
instruction, whichrequires the function to be located in the same naturally aligned 256MBsegment as the caller. Thelong_call
andfar
attributes are synonymsand require the use of a different call sequence that works regardlessof the distance between the functions.
These attributes have no effect for position-independent code.
These attributes take priority over command line switches suchas-mlong-calls
and-mno-long-calls
.
malloc¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
| Yes |
Themalloc
attribute has two forms with different functionality. The firstis when it is used without arguments, where it marks that a function acts likea system memory allocation function, returning a pointer to allocated storagethat does not alias storage from any other object accessible to the caller.
The second form is whenmalloc
takes one or two arguments. The firstargument names a function that should be associated with this function as itsdeallocation function. When this form is used, it enables the compiler todiagnose when the incorrect deallocation function is used with this variable.However the associated warning, spelled-Wmismatched-dealloc in GCC, is notyet implemented in clang.
micromips, nomicromips¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang supports the GNU style__attribute__((micromips))
and__attribute__((nomicromips))
attributes on MIPS targets. These attributesmay be attached to a function definition and instructs the backend to generateor not to generate microMIPS code for that function.
These attributes override the-mmicromips
and-mno-micromips
optionson the command line.
mig_server_routine¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
The Mach Interface Generator release-on-success convention dictatesfunctions that follow it to only release arguments passed to them when theyreturn “success” (akern_return_t
error code that indicates thatno errors have occurred). Otherwise the release is performed by the MIG clientthat called the function. The annotation__attribute__((mig_server_routine))
is applied in order to specify which functions are expected to follow theconvention. This allows the Static Analyzer to find bugs caused by violations ofthat convention. The attribute would normally appear on the forward declarationof the actual server routine in the MIG server header, but it may also beadded to arbitrary functions that need to follow the same convention - forexample, a user can add them to auxiliary functions called by the server routinethat have their return value of typekern_return_t
unconditionally returnedfrom the routine. The attribute can be applied to C++ methods, and in this caseit will be automatically applied to overrides if the method is virtual. Theattribute can also be written using C++11 syntax:[[mig::server_routine]]
.
min_vector_width¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang supports the__attribute__((min_vector_width(width)))
attribute. Thisattribute may be attached to a function and informs the backend that thisfunction desires vectors of at least this width to be generated. Target-specificmaximum vector widths still apply. This means even if you ask for somethinglarger than the target supports, you will only get what the target supports.This attribute is meant to be a hint to control target heuristics that maygenerate narrower vectors than what the target hardware supports.
This is currently used by the X86 target to allow some CPUs that support 512-bitvectors to be limited to using 256-bit vectors to avoid frequency penalties.This is currently enabled with the-prefer-vector-width=256
command lineoption. Themin_vector_width
attribute can be used to prevent the backendfrom trying to split vector operations to match theprefer-vector-width
. AllX86 vector intrinsics from x86intrin.h already set this attribute. Additionally,use of any of the X86-specific vector builtins will implicitly set thisattribute on the calling function. The intent is that explicitly writing vectorcode using the X86 intrinsics will preventprefer-vector-width
fromaffecting the code.
minsize¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
This function attribute indicates that optimization passes and code generator passesmake choices that keep the function code size as small as possible. Optimizations mayalso sacrifice runtime performance in order to minimize the size of the generated code.
no_builtin¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
The__attribute__((no_builtin))
is similar to the-fno-builtin
flagexcept it is specific to the body of a function. The attribute may also beapplied to a virtual function but has no effect on the behavior of overridingfunctions in a derived class.
It accepts one or more strings corresponding to the specific names of thebuiltins to disable (e.g. “memcpy”, “memset”).If the attribute is used without parameters it will disable all buitins atonce.
// The compiler is not allowed to add any builtin to foo's body.voidfoo(char*data,size_tcount)__attribute__((no_builtin)){// The compiler is not allowed to convert the loop into// `__builtin_memset(data, 0xFE, count);`.for(size_ti=0;i<count;++i)data[i]=0xFE;}// The compiler is not allowed to add the `memcpy` builtin to bar's body.voidbar(char*data,size_tcount)__attribute__((no_builtin("memcpy"))){// The compiler is allowed to convert the loop into// `__builtin_memset(data, 0xFE, count);` but cannot generate any// `__builtin_memcpy`for(size_ti=0;i<count;++i)data[i]=0xFE;}
no_caller_saved_registers¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Use this attribute to indicate that the specified function has nocaller-saved registers. That is, all registers are callee-saved except forregisters used for passing parameters to the function or returning parametersfrom the function.The compiler saves and restores any modified registers that were not used forpassing or returning arguments to the function.
The user can call functions specified with the ‘no_caller_saved_registers’attribute from an interrupt handler without saving and restoring allcall-clobbered registers.
Functions specified with the ‘no_caller_saved_registers’ attribute should onlycall other functions with the ‘no_caller_saved_registers’ attribute, or should becompiled with the ‘-mgeneral-regs-only’ flag to avoid saving unused non-GPR registers.
Note that ‘no_caller_saved_registers’ attribute is not a calling convention.In fact, it only overrides the decision of which registers should be saved bythe caller, but not how the parameters are passed from the caller to the callee.
For example:
__attribute__((no_caller_saved_registers,fastcall))voidf(intarg1,intarg2){...}In this case parameters ‘arg1’ and ‘arg2’ will be passed in registers.In this case, on 32-bit x86 targets, the function ‘f’ will use ECX and EDX asregister parameters. However, it will not assume any scratch registers andshould save and restore any modified registers except for ECX and EDX.
no_profile_instrument_function¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Use theno_profile_instrument_function
attribute on a function declarationto denote that the compiler should not instrument the function withprofile-related instrumentation, such as via the-fprofile-generate
/-fprofile-instr-generate
/-fcs-profile-generate
/-fprofile-arcs
flags.
no_sanitize¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Use theno_sanitize
attribute on a function or a global variabledeclaration to specify that a particular instrumentation or set ofinstrumentations should not be applied.
The attribute takes a list of string literals with the following acceptedvalues:* all values accepted by-fno-sanitize=
;*coverage
, to disable SanitizerCoverage instrumentation.
For example,__attribute__((no_sanitize("address","thread")))
specifiesthat AddressSanitizer and ThreadSanitizer should not be applied to the functionor variable. Using__attribute__((no_sanitize("coverage")))
specifies thatSanitizerCoverage should not be applied to the function.
SeeControlling Code Generation for afull list of supported sanitizer flags.
no_sanitize_address, no_address_safety_analysis¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Use__attribute__((no_sanitize_address))
on a function or a globalvariable declaration to specify that address safety instrumentation(e.g. AddressSanitizer) should not be applied.
no_sanitize_memory¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Use__attribute__((no_sanitize_memory))
on a function declaration tospecify that checks for uninitialized memory should not be inserted(e.g. by MemorySanitizer). The function may still be instrumented by the toolto avoid false positives in other places.
no_sanitize_thread¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Use__attribute__((no_sanitize_thread))
on a function declaration tospecify that checks for data races on plain (non-atomic) memory accesses shouldnot be inserted by ThreadSanitizer. The function is still instrumented by thetool to avoid false positives and provide meaningful stack traces.
no_speculative_load_hardening¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
- This attribute can be applied to a function declaration in order to indicate
thatSpeculative Load Hardeningisnot needed for the function body. This can also be applied to a methodin Objective C. This attribute will take precedence over the command line flag inthe case where-mspeculative-load-hardening is specified.
Warning: This attribute may not prevent Speculative Load Hardening from beingenabled for a function which inlines a function that has the‘speculative_load_hardening’ attribute. This is intended to provide amaximally conservative model where the code that is marked with the‘speculative_load_hardening’ attribute will always (even when inlined)be hardened. A user of this attribute may want to mark functions called bya function they do not want to be hardened with the ‘noinline’ attribute.
For example:
__attribute__((speculative_load_hardening))intfoo(inti){returni;}// Note: bar() may still have speculative load hardening enabled if// foo() is inlined into bar(). Mark foo() with __attribute__((noinline))// to avoid this situation.__attribute__((no_speculative_load_hardening))intbar(inti){returnfoo(i);}
no_split_stack¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theno_split_stack
attribute disables the emission of the split stackpreamble for a particular function. It has no effect if-fsplit-stack
is not specified.
no_stack_protector, safebuffers¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
| Yes |
Clang supports the GNU style__attribute__((no_stack_protector))
and Microsoftstyle__declspec(safebuffers)
attribute which disablesthe stack protector on the specified function. This attribute is useful forselectively disabling the stack protector on some functions when building with-fstack-protector
compiler option.
For example, it disables the stack protector for the functionfoo
but functionbar
will still be built with the stack protector with the-fstack-protector
option.
int__attribute__((no_stack_protector))foo(intx);// stack protection will be disabled for foo.intbar(inty);// bar can be built with the stack protector.
noalias¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
Thenoalias
attribute indicates that the only memory accesses insidefunction are loads and stores from objects pointed to by its pointer-typedarguments, with arbitrary offsets.
nocf_check¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Jump Oriented Programming attacks rely on tampering with addresses used byindirect call / jmp, e.g. redirect control-flow to non-programmerintended bytes in the binary.X86 Supports Indirect Branch Tracking (IBT) as part of Control-FlowEnforcement Technology (CET). IBT instruments ENDBR instructions used tospecify valid targets of indirect call / jmp.Thenocf_check
attribute has two roles:1. Appertains to a function - do not add ENDBR instruction at the beginning ofthe function.2. Appertains to a function pointer - do not track the target function of thispointer (by adding nocf_check prefix to the indirect-call instruction).
noconvergent¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
| Yes |
This attribute prevents a function from being treated as convergent; when afunction is markednoconvergent
, calls to that function are notautomatically assumed to be convergent, unless such calls are explicitly markedasconvergent
. If a statement is marked asnoconvergent
, any calls toinlineasm
in that statement are no longer treated as convergent.
In languages following SPMD/SIMT programming model, e.g., CUDA/HIP, functiondeclarations and inline asm calls are treated as convergent by default forcorrectness. Thisnoconvergent
attribute is helpful for developers toprevent them from being treated as convergent when it’s safe.
__device__floatbar(float);__device__floatfoo(float)__attribute__((noconvergent)){}__device__intexample(void){floatx;[[clang::noconvergent]]x=bar(x);// no effect on convergence[[clang::noconvergent]]{asmvolatile("nop");}// the asm call is non-convergent}
nodiscard, warn_unused_result¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang supports the ability to diagnose when the results of a function callexpression are discarded under suspicious circumstances. A diagnostic isgenerated when a function or its return type is marked with[[nodiscard]]
(or__attribute__((warn_unused_result))
) and the function call appears as apotentially-evaluated discarded-value expression that is not explicitly cast tovoid
.
A string literal may optionally be provided to the attribute, which will bereproduced in any resulting diagnostics. Redeclarations using different formsof the attribute (with or without the string literal or with different stringliteral contents) are allowed. If there are redeclarations of the entity withdiffering string literals, it is unspecified which one will be used by Clangin any resulting diagnostics.
struct[[nodiscard]]error_info{/*...*/};error_infoenable_missile_safety_mode();voidlaunch_missiles();voidtest_missiles(){enable_missile_safety_mode();// diagnoseslaunch_missiles();}error_info&foo();voidf(){foo();}// Does not diagnose, error_info is a reference.
Additionally, discarded temporaries resulting from a call to a constructormarked with[[nodiscard]]
or a constructor of a type marked[[nodiscard]]
will also diagnose. This also applies to type conversions thatuse the annotated[[nodiscard]]
constructor or result in an annotated type.
struct[[nodiscard]]marked_type{/*..*/};structmarked_ctor{[[nodiscard]]marked_ctor();marked_ctor(int);};structS{operatormarked_type()const;[[nodiscard]]operatorint()const;};voidusages(){marked_type();// diagnoses.marked_ctor();// diagnoses.marked_ctor(3);// Does not diagnose, int constructor isn't marked nodiscard.Ss;static_cast<marked_type>(s);// diagnoses(int)s;// diagnoses}
noduplicate¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Thenoduplicate
attribute can be placed on function declarations to controlwhether function calls to this function can be duplicated or not as a result ofoptimizations. This is required for the implementation of functions withcertain special requirements, like the OpenCL “barrier” function, that mightneed to be run concurrently by all the threads that are executing in lockstepon the hardware. For example this attribute applied on the function“nodupfunc” in the code below avoids that:
voidnodupfunc()__attribute__((noduplicate));// Setting it as a C++11 attribute is also valid// void nodupfunc() [[clang::noduplicate]];voidfoo();voidbar();nodupfunc();if(a>n){foo();}else{bar();}
gets possibly modified by some optimizations into code similar to this:
if(a>n){nodupfunc();foo();}else{nodupfunc();bar();}
where the call to “nodupfunc” is duplicated and sunk into the two branchesof the condition.
noinline¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
| Yes |
This function attribute suppresses the inlining of a function at the call sitesof the function.
[[clang::noinline]]
spelling can be used as a statement attribute; otherspellings of the attribute are not supported on statements. If a statement ismarked[[clang::noinline]]
and contains calls, those calls inside thestatement will not be inlined by the compiler.
__noinline__
can be used as a keyword in CUDA/HIP languages. This is toavoid diagnostics due to usage of__attribute__((__noinline__))
with__noinline__
defined as a macro as__attribute__((noinline))
.
intexample(void){intr;[[clang::noinline]]foo();[[clang::noinline]]r=bar();returnr;}
noreturn, _Noreturn¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
A function declared as[[noreturn]]
shall not return to its caller. Thecompiler will generate a diagnostic for a function declared as[[noreturn]]
that appears to be capable of returning to its caller.
The[[_Noreturn]]
spelling is deprecated and only exists to ease codemigration for code using[[noreturn]]
after including<stdnoreturn.h>
.
not_tail_called¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Thenot_tail_called
attribute prevents tail-call optimization on staticallybound calls. Objective-c methods, and functions marked asalways_inline
cannot be marked asnot_tail_called
.
For example, it prevents tail-call optimization in the following case:
int__attribute__((not_tail_called))foo1(int);intfoo2(inta){returnfoo1(a);// No tail-call optimization on direct calls.}
However, it doesn’t prevent tail-call optimization in this case:
int__attribute__((not_tail_called))foo1(int);intfoo2(inta){int(*fn)(int)=&foo1;// not_tail_called has no effect on an indirect call even if the call can// be resolved at compile time.return(*fn)(a);}
Generally, marking an overriding virtual function asnot_tail_called
isnot useful, because this attribute is a property of the static type. Callsmade through a pointer or reference to the base class type will respectthenot_tail_called
attribute of the base class’s member function,regardless of the runtime destination of the call:
structFoo{virtualvoidf();};structBar:Foo{[[clang::not_tail_called]]voidf()override;};voidcallera(Bar&bar){Foo&foo=bar;// not_tail_called has no effect on here, even though the// underlying method is f from Bar.foo.f();bar.f();// No tail-call optimization on here.}
nothrow¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
| Yes |
Clang supports the GNU style__attribute__((nothrow))
and Microsoft style__declspec(nothrow)
attribute as an equivalent ofnoexcept
on functiondeclarations. This attribute informs the compiler that the annotated functiondoes not throw an exception. This prevents exception-unwinding. This attributeis particularly useful on functions in the C Standard Library that areguaranteed to not throw an exception.
nouwtable¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang supports thenouwtable
attribute which skips emittingthe unwind table entry for the specified function. This attribute is useful forselectively emitting the unwind table entry on some functions when building with-funwind-tables
compiler option.
numthreads¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
Thenumthreads
attribute applies to HLSL shaders where explcit thread countsare required. TheX
,Y
, andZ
values provided to the attributedictate the thread id. Total number of threads executed isX*Y*Z
.
The full documentation is available here:https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-numthreads
objc_method_family¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Many methods in Objective-C have conventional meanings determined by theirselectors. It is sometimes useful to be able to mark a method as having aparticular conventional meaning despite not having the right selector, or asnot having the conventional meaning that its selector would suggest. For theseuse cases, we provide an attribute to specifically describe the “method family”that a method belongs to.
Usage:__attribute__((objc_method_family(X)))
, whereX
is one ofnone
,alloc
,copy
,init
,mutableCopy
, ornew
. Thisattribute can only be placed at the end of a method declaration:
-(NSString*)initMyStringValue__attribute__((objc_method_family(none)));
Users who do not wish to change the conventional meaning of a method, and whomerely want to document its non-standard retain and release semantics, shoulduse the retaining behavior attributes (ns_returns_retained
,ns_returns_not_retained
, etc).
Query for this feature with__has_attribute(objc_method_family)
.
objc_requires_super¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Some Objective-C classes allow a subclass to override a particular method in aparent class but expect that the overriding method also calls the overriddenmethod in the parent class. For these cases, we provide an attribute todesignate that a method requires a “call tosuper
” in the overridingmethod in the subclass.
Usage:__attribute__((objc_requires_super))
. This attribute can onlybe placed at the end of a method declaration:
-(void)foo__attribute__((objc_requires_super));
This attribute can only be applied the method declarations within a class, andnot a protocol. Currently this attribute does not enforce any placement ofwhere the call occurs in the overriding method (such as in the case of-dealloc
where the call must appear at the end). It checks only that itexists.
Note that on both OS X and iOS that the Foundation framework provides aconvenience macroNS_REQUIRES_SUPER
that provides syntactic sugar for thisattribute:
-(void)fooNS_REQUIRES_SUPER;
This macro is conditionally defined depending on the compiler’s support forthis attribute. If the compiler does not support the attribute the macroexpands to nothing.
Operationally, when a method has this annotation the compiler will warn if theimplementation of an override in a subclass does not call super. For example:
warning:methodpossiblymissinga[superAnnotMeth]call-(void)AnnotMeth{};^
optnone¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theoptnone
attribute suppresses essentially all optimizationson a function or method, regardless of the optimization level applied tothe compilation unit as a whole. This is particularly useful when youneed to debug a particular function, but it is infeasible to build theentire application without optimization. Avoiding optimization on thespecified function can improve the quality of the debugging informationfor that function.
This attribute is incompatible with thealways_inline
andminsize
attributes.
Note that this attribute does not apply recursively to nested functions such aslambdas or blocks when using declaration-specific attribute syntaxes such as doublesquare brackets ([[]]
) or__attribute__
. The#pragma
syntax can beused to apply the attribute to all functions, including nested functions, in arange of source code.
overloadable¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang provides support for C++ function overloading in C. Function overloadingin C is introduced using theoverloadable
attribute. For example, onemight provide several overloaded versions of atgsin
function that invokesthe appropriate standard function computing the sine of a value withfloat
,double
, orlongdouble
precision:
#include<math.h>float__attribute__((overloadable))tgsin(floatx){returnsinf(x);}double__attribute__((overloadable))tgsin(doublex){returnsin(x);}longdouble__attribute__((overloadable))tgsin(longdoublex){returnsinl(x);}
Given these declarations, one can calltgsin
with afloat
value toreceive afloat
result, with adouble
to receive adouble
result,etc. Function overloading in C follows the rules of C++ function overloadingto pick the best overload given the call arguments, with a few C-specificsemantics:
Conversion from
float
ordouble
tolongdouble
is ranked as afloating-point promotion (per C99) rather than as a floating-point conversion(as in C++).A conversion from a pointer of type
T*
to a pointer of typeU*
isconsidered a pointer conversion (with conversion rank) ifT
andU
arecompatible types.A conversion from type
T
to a value of typeU
is permitted ifT
andU
are compatible types. This conversion is given “conversion” rank.If no viable candidates are otherwise available, we allow a conversion from apointer of type
T*
to a pointer of typeU*
, whereT
andU
areincompatible. This conversion is ranked below all other types of conversions.Please note:U
lacking qualifiers that are present onT
is sufficientforT
andU
to be incompatible.
The declaration ofoverloadable
functions is restricted to functiondeclarations and definitions. If a function is marked with theoverloadable
attribute, then all declarations and definitions of functions with that name,except for at most one (see the note below about unmarked overloads), must havetheoverloadable
attribute. In addition, redeclarations of a function withtheoverloadable
attribute must have theoverloadable
attribute, andredeclarations of a function without theoverloadable
attribute mustnothave theoverloadable
attribute. e.g.,
intf(int)__attribute__((overloadable));floatf(float);// error: declaration of "f" must have the "overloadable" attributeintf(int);// error: redeclaration of "f" must have the "overloadable" attributeintg(int)__attribute__((overloadable));intg(int){}// error: redeclaration of "g" must also have the "overloadable" attributeinth(int);inth(int)__attribute__((overloadable));// error: declaration of "h" must not// have the "overloadable" attribute
Functions markedoverloadable
must have prototypes. Therefore, thefollowing code is ill-formed:
inth()__attribute__((overloadable));// error: h does not have a prototype
However,overloadable
functions are allowed to use a ellipsis even if thereare no named parameters (as is permitted in C++). This feature is particularlyuseful when combined with theunavailable
attribute:
voidhoneypot(...)__attribute__((overloadable,unavailable));// calling me is an error
Functions declared with theoverloadable
attribute have their names mangledaccording to the same rules as C++ function names. For example, the threetgsin
functions in our motivating example get the mangled names_Z5tgsinf
,_Z5tgsind
, and_Z5tgsine
, respectively. There are twocaveats to this use of name mangling:
Future versions of Clang may change the name mangling of functions overloadedin C, so you should not depend on an specific mangling. To be completelysafe, we strongly urge the use of
staticinline
withoverloadable
functions.The
overloadable
attribute has almost no meaning when used in C++,because names will already be mangled and functions are already overloadable.However, when anoverloadable
function occurs within anextern"C"
linkage specification, its namewill be mangled in the same way as itwould in C.
For the purpose of backwards compatibility, at most one function with the samename as otheroverloadable
functions may omit theoverloadable
attribute. In this case, the function without theoverloadable
attributewill not have its name mangled.
For example:
// Notes with mangled names assume Itanium mangling.intf(int);intf(double)__attribute__((overloadable));voidfoo(){f(5);// Emits a call to f (not _Z1fi, as it would with an overload that// was marked with overloadable).f(1.0);// Emits a call to _Z1fd.}
Support for unmarked overloads is not present in some versions of clang. You mayquery for it using__has_extension(overloadable_unmarked)
.
Query for this attribute with__has_attribute(overloadable)
.
ownership_holds, ownership_returns, ownership_takes (Clang Static Analyzer)¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Note
In order for the Clang Static Analyzer to acknowledge these attributes, theOptimistic
config needs to be set to true for the checkerunix.DynamicMemoryModeling
:
-Xclang-analyzer-config-Xclangunix.DynamicMemoryModeling:Optimistic=true
These attributes are used by the Clang Static Analyzer’s dynamic memory modelingfacilities to mark custom allocating/deallocating functions.
All 3 attributes’ first parameter of type string is the type of the allocation:malloc
,new
, etc. to allow for catchingmismatched deallocation bugs. The allocation type can be any string, e.g.a function annotated withreturning a piece of memory of typelasagna
but freed with a functionannotated to releasecheese
typed memory will result in mismatcheddeallocation warning.
The (currently) only allocation type having special meaning ismalloc
–the Clang Static Analyzer makes sure that allocating functions annotated withmalloc
are treated like they used the standardmalloc()
, and can besafely deallocated with the standardfree()
.
Use
ownership_returns
to mark a function as an allocating function. Takes1 parameter to denote the allocation type.Use
ownership_takes
to mark a function as a deallocating function. Takes 2parameters: the allocation type, and the index of the parameter that is beingdeallocated (counting from 1).Use
ownership_holds
to mark that a function takes over the ownership of apiece of memory and will free it at some unspecified point in the future. Likeownership_takes
, this takes 2 parameters: the allocation type, and theindex of the parameter whose ownership will be taken over (counting from 1).
The annotationsownership_takes
andownership_holds
both prevent memoryleak reports (concerning the specified argument); the difference between themis that using taken memory is a use-after-free error, while using held memoryis assumed to be legitimate.
Example:
// Denotes that my_malloc will return with a dynamically allocated piece of// memory using malloc().void__attribute((ownership_returns(malloc)))*my_malloc(size_t);// Denotes that my_free will deallocate its parameter using free().void__attribute((ownership_takes(malloc,1)))my_free(void*);// Denotes that my_hold will take over the ownership of its parameter that was// allocated via malloc().void__attribute((ownership_holds(malloc,1)))my_hold(void*);
Further reading about dynamic memory modeling in the Clang Static Analyzer isfound in these checker docs:unix.Malloc,unix.MallocSizeof,unix.MismatchedDeallocator,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,optin.taint.TaintedAlloc.Mind that many more checkers are affected by dynamic memory modeling changes tosome extent.
Further reading for other annotations:Source Annotations in the Clang Static Analyzer.
packoffset¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The packoffset attribute is used to change the layout of a cbuffer.Attribute spelling in HLSL is:packoffset(c[Subcomponent][.component])
.A subcomponent is a register number, which is an integer. A component is in the form of [.xyzw].
Examples:
cbufferA{float3a:packoffset(c0.y);float4b:packoffset(c4);}
The full documentation is available here:https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-packoffset
patchable_function_entry¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
__attribute__((patchable_function_entry(N,M,Section)))
is used to generate MNOPs before the function entry and N-M NOPs after the function entry, with a record ofthe entry stored in sectionSection
. This attribute takes precedence over thecommand line option-fpatchable-function-entry=N,M,Section
.M
defaults to 0if omitted.``Section`` defaults to the-fpatchable-function-entry
section name ifset, or to__patchable_function_entries
otherwise.
This attribute is only supported onaarch64/aarch64-be/loongarch32/loongarch64/riscv32/riscv64/i386/x86-64/ppc/ppc64 targets.For ppc/ppc64 targets, AIX is still not supported.
preserve_access_index¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang supports the__attribute__((preserve_access_index))
attribute for the BPF target. This attribute may be attached to astruct or union declaration, where if -g is specified, it enablespreserving struct or union member access debuginfo indices of thisstruct or union, similar to clang__builtin_preserve_access_index()
.
preserve_static_offset¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang supports the__attribute__((preserve_static_offset))
attribute for the BPF target. This attribute may be attached to astruct or union declaration. Reading or writing fields of types havingsuch annotation is guaranteed to generate LDX/ST/STX instruction withoffset corresponding to the field.
For example:
structfoo{inta;intb;};structbar{inta;structfoob;}__attribute__((preserve_static_offset));voidbuz(structbar*g){g->b.a=42;}
The assignment tog
’s field would produce an ST instruction withoffset 8:*(u32)(r1+8)=42;
.
Without this attribute generated instructions might be different,depending on optimizations behavior. E.g. the example above could berewritten asr1+=8;*(u32)(r1+0)=42;
.
register¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The resource binding attribute sets the virtual register and logical register space for a resource.Attribute spelling in HLSL is:register(slot[,space])
.slot
takes the format[type][number]
,wheretype
is a single character specifying the resource type andnumber
is the virtual register number.
Register types are:t for shader resource views (SRV),s for samplers,u for unordered access views (UAV),b for constant buffer views (CBV).
Register space is specified in the formatspace[number]
and defaults tospace0
if omitted.Here’re resource binding examples with and without space:
RWBuffer<float>Uav:register(u3,space1);Buffer<float>Buf:register(t1);
The full documentation is available here:https://docs.microsoft.com/en-us/windows/win32/direct3d12/resource-binding-in-hlsl
reinitializes¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
Thereinitializes
attribute can be applied to a non-static, non-const C++member function to indicate that this member function reinitializes the entireobject to a known state, independent of the previous state of the object.
This attribute can be interpreted by static analyzers that warn about uses of anobject that has been left in an indeterminate state by a move operation. If amember function marked with thereinitializes
attribute is called on amoved-from object, the analyzer can conclude that the object is no longer in anindeterminate state.
A typical example where this attribute would be used is on functions that cleara container class:
template<classT>classContainer{public:...[[clang::reinitializes]]voidClear();...};
release_capability, release_shared_capability¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
Marks a function as releasing a capability.
retain¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
This attribute, when attached to a function or variable definition, preventssection garbage collection in the linker. It does not prevent other discardmechanisms, such as archive member selection, and COMDAT group resolution.
If the compiler does not emit the definition, e.g. because it was not used inthe translation unit or the compiler was able to eliminate all of the uses,this attribute has no effect. This attribute is typically combined with theused
attribute to force the definition to be emitted and preserved into thefinal linked image.
This attribute is only necessary on ELF targets; other targets prevent sectiongarbage collection by the linker when using theused
attribute alone.Using the attributes together should result in consistent behavior acrosstargets.
This attribute requires the linker to support theSHF_GNU_RETAIN
extension.This support is available in GNUld
andgold
as of binutils 2.36, aswell as inld.lld
13.
shader¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
Theshader
type attribute applies to HLSL shader entry functions toidentify the shader type for the entry function.The syntax is:
``[shader(string-literal)]``
where the string literal is one of: “pixel”, “vertex”, “geometry”, “hull”,“domain”, “compute”, “raygeneration”, “intersection”, “anyhit”, “closesthit”,“miss”, “callable”, “mesh”, “amplification”. Normally the shader type is setby shader target with the-T
option like-Tps_6_1
. When compiling to alibrary target likelib_6_3
, the shader type attribute can help thecompiler to identify the shader type. It is mostly used by Raytracing shaderswhere shaders must be compiled into a library and linked at runtime.
short_call, near¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang supports the__attribute__((long_call))
,__attribute__((far))
,__attribute__((short__call))
, and__attribute__((near))
attributeson MIPS targets. These attributes may only be added to function declarationsand change the code generated by the compiler when directly callingthe function. Theshort_call
andnear
attributes are synonyms andallow calls to the function to be made using thejal
instruction, whichrequires the function to be located in the same naturally aligned 256MB segmentas the caller. Thelong_call
andfar
attributes are synonyms andrequire the use of a different call sequence that works regardlessof the distance between the functions.
These attributes have no effect for position-independent code.
These attributes take priority over command line switches suchas-mlong-calls
and-mno-long-calls
.
signal¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang supports the GNU style__attribute__((signal))
attribute onAVR targets. This attribute may be attached to a function definition and instructsthe backend to generate appropriate function entry/exit code so that it can be useddirectly as an interrupt service routine.
Interrupt handler functions defined with the signal attribute do not re-enable interrupts.
speculative_load_hardening¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
- This attribute can be applied to a function declaration in order to indicate
thatSpeculative Load Hardeningshould be enabled for the function body. This can also be applied to a methodin Objective C. This attribute will take precedence over the command line flag inthe case where-mno-speculative-load-hardening is specified.
Speculative Load Hardening is a best-effort mitigation againstinformation leak attacks that make use of control flowmiss-speculation - specifically miss-speculation of whether a branchis taken or not. Typically vulnerabilities enabling such attacks areclassified as “Spectre variant #1”. Notably, this does not attempt tomitigate against miss-speculation of branch target, classified as“Spectre variant #2” vulnerabilities.
When inlining, the attribute is sticky. Inlining a function thatcarries this attribute will cause the caller to gain theattribute. This is intended to provide a maximally conservative modelwhere the code in a function annotated with this attribute will always(even after inlining) end up hardened.
strict_gs_check¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
Clang supports the Microsoft style__declspec((strict_gs_check))
attributewhich upgrades the stack protector check from-fstack-protector
to-fstack-protector-strong
.
For example, it upgrades the stack protector for the functionfoo
to-fstack-protector-strong
but functionbar
will still be built with thestack protector with the-fstack-protector
option.
__declspec((strict_gs_check))intfoo(intx);// stack protection will be upgraded for foo.intbar(inty);// bar can be built with the standard stack protector checks.
sv_dispatchthreadid¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
TheSV_DispatchThreadID
semantic, when applied to an input parameter,specifies a data binding to map the global thread offset within the Dispatchcall (per dimension of the group) to the specified parameter.When applied to a field of a struct, the data binding is specified to the fieldwhen the struct is used as a parameter type.The semantic on the field is ignored when not used as a parameter.This attribute is only supported in compute shaders.
The full documentation is available here:https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-dispatchthreadid
sv_groupid¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
TheSV_GroupID
semantic, when applied to an input parameter, specifies whichthread group a shader is executing in. This attribute is only supported in compute shaders.
The full documentation is available here:https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-groupid
sv_groupindex¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
TheSV_GroupIndex
semantic, when applied to an input parameter, specifies adata binding to map the group index to the specified parameter. This attributeis only supported in compute shaders.
The full documentation is available here:https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-groupindex
sv_groupthreadid¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
TheSV_GroupThreadID
semantic, when applied to an input parameter, specifies whichindividual thread within a thread group is executing in. This attribute isonly supported in compute shaders.
The full documentation is available here:https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-groupthreadid
sv_position¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
TheSV_Position
semantic, when applied to an input parameter in a pixelshader, contains the location of the pixel center (x, y) in screen space.This semantic can be applied to the parameter, or a field in a struct usedas an input parameter.This attribute is supported as an input in pixel, hull, domain and mesh shaders.This attribute is supported as an output in vertex, geometry and domain shaders.
The full documentation is available here:https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-semantics
sycl_kernel_entry_point¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Thesycl_kernel_entry_point
attribute facilitates the generation of anoffload kernel entry point, sometimes called a SYCL kernel caller function,suitable for invoking a SYCL kernel on an offload device. The attribute isintended for use in the implementation of SYCL kernel invocation functionslike thesingle_task
andparallel_for
member functions of thesycl::handler
class specified in section 4.9.4, “Command grouphandler
class”, of the SYCL 2020 specification.
The attribute requires a single type argument that specifies a class type thatmeets the requirements for a SYCL kernel name as described in section 5.2,“Naming of kernels”, of the SYCL 2020 specification. A unique kernel name typeis required for each function declared with the attribute. The attribute maynot first appear on a declaration that follows a definition of the function.
The attribute only appertains to functions and only those that meet thefollowing requirements.
Has a non-deduced
void
return type.Is not a non-static member function, constructor, or destructor.
Is not a C variadic function.
Is not a coroutine.
Is not defined as deleted or as defaulted.
Is not defined with a function try block.
Is not declared with the
constexpr
orconsteval
specifiers.Is not declared with the
[[noreturn]]
attribute.
Use in the implementation of a SYCL kernel invocation function might look asfollows.
namespacesycl{classhandler{template<typenameKernelNameType,typenameKernelType>[[clang::sycl_kernel_entry_point(KernelNameType)]]staticvoidkernel_entry_point(KernelTypekernel){kernel();}public:template<typenameKernelNameType,typenameKernelType>voidsingle_task(KernelTypekernel){// Call kernel_entry_point() to trigger generation of an offload// kernel entry point.kernel_entry_point<KernelNameType>(kernel);// Call functions appropriate for the desired offload backend// (OpenCL, CUDA, HIP, Level Zero, etc...).}};}// namespace sycl
A SYCL kernel is a callable object of class type that is constructed on a host,often via a lambda expression, and then passed to a SYCL kernel invocationfunction to be executed on an offload device. A SYCL kernel invocation functionis responsible for copying the provided SYCL kernel object to an offloaddevice and initiating a call to it. The SYCL kernel object and its data membersconstitute the parameters of an offload kernel.
A SYCL kernel type is required to satisfy the device copyability requirementsspecified in section 3.13.1, “Device copyable”, of the SYCL 2020 specification.Additionally, any data members of the kernel object type are required to satisfysection 4.12.4, “Rules for parameter passing to kernels”. For most types, theserules require that the type is trivially copyable. However, the SYCLspecification mandates that certain special SYCL types, such assycl::accessor
andsycl::stream
be device copyable even if they are nottrivially copyable. These types require special handling because they cannotbe copied to device memory as if bymemcpy()
. Additionally, some offloadbackends, OpenCL for example, require objects of some of these types to bepassed as individual arguments to the offload kernel.
An offload kernel consists of an entry point function that declares theparameters of the offload kernel and the set of all functions and variables thatare directly or indirectly used by the entry point function.
A SYCL kernel invocation function invokes a SYCL kernel on a device byperforming the following tasks (likely with the help of an offload backendlike OpenCL):
Identifying the offload kernel entry point to be used for the SYCL kernel.
Deconstructing the SYCL kernel object, if necessary, to produce the set ofoffload kernel arguments required by the offload kernel entry point.
Copying the offload kernel arguments to device memory.
Initiating execution of the offload kernel entry point.
The offload kernel entry point for a SYCL kernel performs the following tasks:
Reconstituting the SYCL kernel object, if necessary, using the offloadkernel parameters.
Calling the
operator()
member function of the (reconstituted) SYCL kernelobject.
Thesycl_kernel_entry_point
attribute automates generation of an offloadkernel entry point that performs those latter tasks. The parameters and body ofa function declared with thesycl_kernel_entry_point
attribute specify apattern from which the parameters and body of the entry point function arederived. Consider the following call to a SYCL kernel invocation function.
structS{inti;};voidf(sycl::handler&handler,sycl::stream&sout,Ss){handler.single_task<structKN>([=]{sout<<"The value of s.i is "<<s.i<<"\n";});}
The SYCL kernel object is the result of the lambda expression. It has twodata members corresponding to the captures ofsout
ands
. Since oneof these data members corresponds to a special SYCL type that must be passedindividually as an offload kernel parameter, it is necessary to decompose theSYCL kernel object into its constituent parts; the offload kernel will havetwo kernel parameters. Given a SYCL implementation that uses asycl_kernel_entry_point
attributed function like the one shown above, anoffload kernel entry point function will be generated that looks approximatelyas follows.
voidsycl-kernel-caller-for-KN(sycl::streamsout,Ss){kernel-typekernel={sout,s);kernel();}
There are a few items worthy of note:
The name of the generated function incorporates the SYCL kernel name,
KN
, that was passed as theKernelNameType
template parameter tokernel_entry_point()
and provided as the argument to thesycl_kernel_entry_point
attribute. There is a one-to-one correspondencebetween SYCL kernel names and offload kernel entry points.The SYCL kernel is a lambda closure type and therefore has no name;
kernel-type
is substituted above and corresponds to theKernelType
template parameter deduced in the call tokernel_entry_point()
.Lambda types cannot be declared and initialized using the aggregateinitialization syntax used above, but the intended behavior should be clear.S
is a device copyable type that does not directly or indirectly containa data member of a SYCL special type. It therefore does not need to bedecomposed into its constituent members to be passed as a kernel argument.The depiction of the
sycl::stream
parameter as a single self containedkernel parameter is an oversimplification. SYCL special types may requireadditional decomposition such that the generated function might have threeor more parameters depending on how the SYCL library implementation definesthese types.The call to
kernel_entry_point()
has no effect other than to triggeremission of the entry point function. The statments that make up the bodyof the function are not executed when the function is called; they areonly used in the generation of the entry point function.
It is not necessary for a function declared with thesycl_kernel_entry_point
attribute to be called for the offload kernel entry point to be emitted. Forinline functions and function templates, any ODR-use will suffice. For otherfunctions, an ODR-use is not required; the offload kernel entry point will beemitted if the function is defined.
Functions declared with thesycl_kernel_entry_point
attribute are notlimited to the simple example shown above. They may have additional templateparameters, declare additional function parameters, and have complex controlflow in the function body. Function parameter decomposition and reconstitutionis performed for all function parameters. The function must abide by thelanguage feature restrictions described in section 5.4, “Language restrictionsfor device functions” in the SYCL 2020 specification.
target¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang supports the GNU style__attribute__((target("OPTIONS")))
attribute.This attribute may be attached to a function definition and instructsthe backend to use different code generation options than were passed on thecommand line.
The current set of options correspond to the existing “subtarget features” forthe target with or without a “-mno-” in front corresponding to the absenceof the feature, as well asarch="CPU"
which will change the default “CPU”for the function.
For X86, the attribute also allowstune="CPU"
to optimize the generatedcode for the given CPU without changing the available instructions.
For AArch64,arch="Arch"
will set the architecture, similar to the -marchcommand line options.cpu="CPU"
can be used to select a specific cpu,as per the-mcpu
option, similarly fortune=
. The attribute also allows the“branch-protection=<args>” option, where the permissible arguments and theireffect on code generation are the same as for the command-line option-mbranch-protection
.
Example “subtarget features” from the x86 backend include: “mmx”, “sse”, “sse4.2”,“avx”, “xop” and largely correspond to the machine specific options handled bythe front end.
Note that this attribute does not apply transitively to nested functions suchas blocks or C++ lambdas.
Additionally, this attribute supports function multiversioning for ELF basedx86/x86-64 targets, which can be used to create multiple implementations of thesame function that will be resolved at runtime based on the priority of theirtarget
attribute strings. A function is considered a multiversioned functionif either two declarations of the function have differenttarget
attributestrings, or if it has atarget
attribute string ofdefault
. Forexample:
__attribute__((target("arch=atom")))voidfoo(){}// will be called on 'atom' processors.__attribute__((target("default")))voidfoo(){}// will be called on any other processors.
All multiversioned functions must contain adefault
(fallback)implementation, otherwise usages of the function are considered invalid.Additionally, a function may not become multiversioned after its first use.
target_clones¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Clang supports thetarget_clones("OPTIONS")
attribute. This attribute may beattached to a function declaration and causes function multiversioning, wheremultiple versions of the function will be emitted with different codegeneration options. Additionally, these versions will be resolved at runtimebased on the priority of their attribute options. Alltarget_clone
functionsare considered multiversioned functions.
For AArch64 target:The attribute contains comma-separated strings of target features joined by “+”sign. For example:
__attribute__((target_clones("sha2+memtag","fcma+sve2-pmull128")))voidfoo(){}
For every multiversioned function adefault
(fallback) implementationalways generated if not specified directly.
For x86/x86-64 targets:All multiversioned functions must contain adefault
(fallback)implementation, otherwise usages of the function are considered invalid.Additionally, a function may not become multiversioned after its first use.
The options totarget_clones
can either be a target-specific architecture(specified asarch=CPU
), or one of a list of subtarget features.
Example “subtarget features” from the x86 backend include: “mmx”, “sse”, “sse4.2”,“avx”, “xop” and largely correspond to the machine specific options handled bythe front end.
The versions can either be listed as a comma-separated sequence of stringliterals or as a single string literal containing a comma-separated list ofversions. For compatibility with GCC, the two formats can be mixed. Forexample, the following will emit 4 versions of the function:
__attribute__((target_clones("arch=atom,avx2","arch=ivybridge","default")))voidfoo(){}
For targets that support the GNU indirect function (IFUNC) feature, dispatchis performed by emitting an indirect function that is resolved to the appropriatetarget clone at load time. The indirect function is given the name themultiversioned function would have if it had been declared without the attribute.For backward compatibility with earlier Clang releases, a function alias with an.ifunc
suffix is also emitted. The.ifunc
suffixed symbol is a deprecatedfeature and support for it may be removed in the future.
target_version¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
For AArch64 target clang supports function multiversioning by__attribute__((target_version("OPTIONS")))
attribute. When applied to afunction it instructs compiler to emit multiple function versions based ontarget_version
attribute strings, which resolved at runtime depend on theirpriority and target features availability. One of the versions is always( implicitly or explicitly ) thedefault
(fallback). Attribute strings cancontain dependent features names joined by the “+” sign.
For targets that support the GNU indirect function (IFUNC) feature, dispatchis performed by emitting an indirect function that is resolved to the appropriatetarget clone at load time. The indirect function is given the name themultiversioned function would have if it had been declared without the attribute.For backward compatibility with earlier Clang releases, a function alias with an.ifunc
suffix is also emitted. The.ifunc
suffixed symbol is a deprecatedfeature and support for it may be removed in the future.
try_acquire_capability, try_acquire_shared_capability¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
Marks a function that attempts to acquire a capability. This function may fail toactually acquire the capability; they accept a Boolean value determiningwhether acquiring the capability means success (true), or failing to acquirethe capability means success (false).
unsafe_buffer_usage¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
The attribute[[clang::unsafe_buffer_usage]]
should be placed on functionsthat need to be avoided as they are prone to buffer overflows or unsafe bufferstruct fields. It is designed to work together with the off-by-default compilerwarning-Wunsafe-buffer-usage
to help codebases transition away from raw pointerbased buffer management, in favor of safer abstractions such as C++20std::span
.The attribute causes-Wunsafe-buffer-usage
to warn on every use of the function orthe field it is attached to, and it may also lead to emission of automatic fix-ithints which would help the user replace the use of unsafe functions(/fields) with safealternatives, though the attribute can be used even when the fix can’t be automated.
Attribute attached to functions: The attribute suppresses all
-Wunsafe-buffer-usage
warnings within the function it is attached to, as thefunction is now classified as unsafe. The attribute should be used carefully, as itwill silence all unsafe operation warnings inside the function; including any newunsafe operations introduced in the future.The attribute is warranted even if the only way a function can overflowthe buffer is by violating the function’s preconditions. For example, itwould make sense to put the attribute on function
foo()
below becausepassing an incorrect size parameter would cause a buffer overflow:[[clang::unsafe_buffer_usage]]voidfoo(int*buf,size_tsize){for(size_ti=0;i<size;++i){buf[i]=i;}}
The attribute is NOT warranted when the function uses safe abstractions,assuming that these abstractions weren’t misused outside the function.For example, function
bar()
below doesn’t need the attribute,because assuming that the containerbuf
is well-formed (has size thatfits the original buffer it refers to), overflow cannot occur:voidbar(std::span<int>buf){for(size_ti=0;i<buf.size();++i){buf[i]=i;}}
In this case function
bar()
enables the user to keep the buffer“containerized” in a span for as long as possible. On the other hand,Functionfoo()
in the previous example may have internalconsistency, but by accepting a raw buffer it requires the user to unwraptheir span, which is undesirable according to the programming modelbehind-Wunsafe-buffer-usage
.The attribute is warranted when a function accepts a raw buffer only toimmediately put it into a span:
[[clang::unsafe_buffer_usage]]voidbaz(int*buf,size_tsize){std::span<int>sp{buf,size};for(size_ti=0;i<sp.size();++i){sp[i]=i;}}
In this case
baz()
does not contain any unsafe operations, but the awkwardparameter type causes the caller to unwrap the span unnecessarily.Note that regardless of the attribute, code insidebaz()
isn’t flaggedby-Wunsafe-buffer-usage
as unsafe. It is definitely undesirable,but ifbaz()
is on an API surface, there is no way to improve itto make it as safe asbar()
without breaking the source and binarycompatibility with existing users of the function. In such casesthe proper solution would be to create a different function (possiblyan overload ofbaz()
) that accepts a safe container likebar()
,and then use the attribute on the originalbaz()
to help the usersupdate their code to use the new function.Attribute attached to fields: The attribute should only be attached tostruct fields, if the fields can not be updated to a safe type with boundscheck, such as std::span. In other words, the buffers prone to unsafe accessesshould always be updated to use safe containers/views and attaching the attributemust be last resort when such an update is infeasible.
The attribute can be placed on individual fields or a set of them as shown below.
structA{[[clang::unsafe_buffer_usage]]int*ptr1;[[clang::unsafe_buffer_usage]]int*ptr2,buf[10];[[clang::unsafe_buffer_usage]]size_tsz;};
Here, every read/write to the fields ptr1, ptr2, buf and sz will trigger a warningthat the field has been explcitly marked as unsafe due to unsafe-buffer operations.
used¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
This attribute, when attached to a function or variable definition, indicatesthat there may be references to the entity which are not apparent in the sourcecode. For example, it may be referenced from inlineasm
, or it may befound through a dynamic symbol or section lookup.
The compiler must emit the definition even if it appears to be unused, and itmust not apply optimizations which depend on fully understanding how the entityis used.
Whether this attribute has any effect on the linker depends on the target andthe linker. Most linkers support the feature of section garbage collection(--gc-sections
), also known as “dead stripping” (ld64-dead_strip
) ordiscarding unreferenced sections (link.exe/OPT:REF
). On COFF and Mach-Otargets (Windows and Apple platforms), theused attribute prevents symbolsfrom being removed by linker section GC. On ELF targets, it has no effect on itsown, and the linker may remove the definition if it is not otherwise referenced.This linker GC can be avoided by also adding theretain
attribute. Notethatretain
requires special support from the linker; see that attribute’sdocumentation for further information.
xray_always_instrument, xray_never_instrument, xray_log_args¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
__attribute__((xray_always_instrument))
or[[clang::xray_always_instrument]]
is used to mark member functions (in C++),methods (in Objective C), and free functions (in C, C++, and Objective C) to beinstrumented with XRay. This will cause the function to always have space atthe beginning and exit points to allow for runtime patching.
Conversely,__attribute__((xray_never_instrument))
or[[clang::xray_never_instrument]]
will inhibit the insertion of theseinstrumentation points.
If a function has neither of these attributes, they become subject to the XRayheuristics used to determine whether a function should be instrumented orotherwise.
__attribute__((xray_log_args(N)))
or[[clang::xray_log_args(N)]]
isused to preserve N function arguments for the logging function. Currently,only N==1 is supported.
zero_call_used_regs¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
This attribute, when attached to a function, causes the compiler to zero asubset of all call-used registers before the function returns. It’s used toincrease program security by either mitigatingReturn-Oriented Programming(ROP) attacks or preventing information leakage through registers.
The term “call-used” means registers which are not guaranteed to be preservedunchanged for the caller by the current calling convention. This could also bedescribed as “caller-saved” or “not callee-saved”.
Thechoice parameters gives the programmer flexibility to choose the subsetof the call-used registers to be zeroed:
skip
doesn’t zero any call-used registers. This choice overrides anycommand-line arguments.used
only zeros call-used registers used in the function. Byused
, wemean a register whose contents have been set or referenced in the function.used-gpr
only zeros call-used GPR registers used in the function.used-arg
only zeros call-used registers used to pass arguments to thefunction.used-gpr-arg
only zeros call-used GPR registers used to pass arguments tothe function.all
zeros all call-used registers.all-gpr
zeros all call-used GPR registers.all-arg
zeros all call-used registers used to pass arguments to thefunction.all-gpr-arg
zeros all call-used GPR registers used to pass arguments tothe function.
The default for the attribute is controlled by the-fzero-call-used-regs
flag.
Handle Attributes¶
Handles are a way to identify resources like files, sockets, and processes.They are more opaque than pointers and widely used in system programming. Theyhave similar risks such as never releasing a resource associated with a handle,attempting to use a handle that was already released, or trying to release ahandle twice. Using the annotations below it is possible to make the ownershipof the handles clear: whose responsibility is to release them. They can alsoaid static analysis tools to find bugs.
acquire_handle¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
If this annotation is on a function or a function type it is assumed to returna new handle. In case this annotation is on an output parameter,the function is assumed to fill the corresponding argument with a newhandle. The attribute requires a string literal argument which used toidentify the handle with later uses ofuse_handle
orrelease_handle
.
// Output arguments from Zircon.zx_status_tzx_socket_create(uint32_toptions,zx_handle_t__attribute__((acquire_handle("zircon")))*out0,zx_handle_t*out1[[clang::acquire_handle("zircon")]]);// Returned handle.[[clang::acquire_handle("tag")]]intopen(constchar*path,intoflag,...);intopen(constchar*path,intoflag,...)__attribute__((acquire_handle("tag")));
release_handle¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
If a function parameter is annotated withrelease_handle(tag)
it is assumed toclose the handle. It is also assumed to require an open handle to work with. Theattribute requires a string literal argument to identify the handle being released.
zx_status_tzx_handle_close(zx_handle_thandle[[clang::release_handle("tag")]]);
use_handle¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
A function taking a handle by value might close the handle. If a functionparameter is annotated withuse_handle(tag)
it is assumed to not to changethe state of the handle. It is also assumed to require an open handle to work with.The attribute requires a string literal argument to identify the handle being used.
zx_status_tzx_port_wait(zx_handle_thandle[[clang::use_handle("zircon")]],zx_time_tdeadline,zx_port_packet_t*packet);
Nullability Attributes¶
Whether a particular pointer may be “null” is an important concern when workingwith pointers in the C family of languages. The various nullability attributesindicate whether a particular pointer can be null or not, which makes APIs moreexpressive and can help static analysis tools identify bugs involving nullpointers. Clang supports several kinds of nullability attributes: thenonnull
andreturns_nonnull
attributes indicate which function ormethod parameters and result types can never be null, while nullability typequalifiers indicate which pointer types can be null (_Nullable
) or cannotbe null (_Nonnull
).
The nullability (type) qualifiers express whether a value of a given pointertype can be null (the_Nullable
qualifier), doesn’t have a defined meaningfor null (the_Nonnull
qualifier), or for which the purpose of null isunclear (the_Null_unspecified
qualifier). Because nullability qualifiersare expressed within the type system, they are more general than thenonnull
andreturns_nonnull
attributes, allowing one to express (forexample) a nullable pointer to an array of nonnull pointers. Nullabilityqualifiers are written to the right of the pointer to which they apply. Forexample:
// No meaningful result when 'ptr' is null (here, it happens to be undefined behavior).intfetch(int*_Nonnullptr){return*ptr;}// 'ptr' may be null.intfetch_or_zero(int*_Nullableptr){returnptr?*ptr:0;}// A nullable pointer to non-null pointers to const characters.constchar*join_strings(constchar*_Nonnull*_Nullablestrings,unsignedn);
In Objective-C, there is an alternate spelling for the nullability qualifiersthat can be used in Objective-C methods and properties using context-sensitive,non-underscored keywords. For example:
@interfaceNSView :NSResponder-(nullableNSView*)ancestorSharedWithView:(nonnullNSView*)aView;@property(assign,nullable)NSView*superview;@property(readonly,nonnull)NSArray*subviews;@end
As well as built-in pointer types, the nullability attributes can be attachedto C++ classes marked with the_Nullable
attribute.
The following C++ standard library types are considered nullable:unique_ptr
,shared_ptr
,auto_ptr
,exception_ptr
,function
,move_only_function
andcoroutine_handle
.
Types should be marked nullable only where the type itself leaves nullabilityambiguous. For example,std::optional
is not marked_Nullable
, becauseoptional<int>_Nullable
is redundant andoptional<int>_Nonnull
isnot a useful type.std::weak_ptr
is not nullable, because its nullabilitycan change with no visible modification, so static annotation is unlikely to beunhelpful.
_Nonnull¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The_Nonnull
nullability qualifier indicates that null is not a meaningfulvalue for a value of the_Nonnull
pointer type. For example, given adeclaration such as:
intfetch(int*_Nonnullptr);
a caller offetch
should not provide a null value, and the compiler willproduce a warning if it sees a literal null value passed tofetch
. Notethat, unlike the declaration attributenonnull
, the presence of_Nonnull
does not imply that passing null is undefined behavior:fetch
is free to consider null undefined behavior or (perhaps forbackward-compatibility reasons) defensively handle null.
_Null_unspecified¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The_Null_unspecified
nullability qualifier indicates that neither the_Nonnull
nor_Nullable
qualifiers make sense for a particular pointertype. It is used primarily to indicate that the role of null with specificpointers in a nullability-annotated header is unclear, e.g., due tooverly-complex implementations or historical factors with a long-lived API.
_Nullable¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The_Nullable
nullability qualifier indicates that a value of the_Nullable
pointer type can be null. For example, given:
intfetch_or_zero(int*_Nullableptr);
a caller offetch_or_zero
can provide null.
The_Nullable
attribute on classes indicates that the given class canrepresent null values, and so the_Nullable
,_Nonnull
etc qualifiersmake sense for this type. For example:
class_NullableArenaPointer{...};ArenaPointer_Nonnullx=...;ArenaPointer_Nullabley=nullptr;
_Nullable_result¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The_Nullable_result
nullability qualifier means that a value of the_Nullable_result
pointer can benil
, just like_Nullable
. Where thisattribute differs from_Nullable
is when it’s used on a parameter to acompletion handler in a Swift async method. For instance, here:
-(void)fetchSomeDataWithID:(int)identifiercompletionHandler:(void(^)(Data*_Nullable_resultresult,NSError*error))completionHandler;
This method asynchronously callscompletionHandler
when the data isavailable, or calls it with an error._Nullable_result
indicates to theSwift importer that this is the uncommon case whereresult
can getnil
even if no error has occurred, and will therefore import it as a Swift optionaltype. Otherwise, ifresult
was annotated with_Nullable
, the Swiftimporter will assume thatresult
will always be non-nil unless an erroroccurred.
nonnull¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Thenonnull
attribute indicates that some function parameters must not benull, and can be used in several different ways. It’s original usage(from GCC)is as a function (or Objective-C method) attribute that specifies whichparameters of the function are nonnull in a comma-separated list. For example:
externvoid*my_memcpy(void*dest,constvoid*src,size_tlen)__attribute__((nonnull(1,2)));
Here, thenonnull
attribute indicates that parameters 1 and 2cannot have a null value. Omitting the parenthesized list of parameter indicesmeans that all parameters of pointer type cannot be null:
externvoid*my_memcpy(void*dest,constvoid*src,size_tlen)__attribute__((nonnull));
Clang also allows thenonnull
attribute to be placed directly on a function(or Objective-C method) parameter, eliminating the need to specify theparameter index ahead of type. For example:
externvoid*my_memcpy(void*dest__attribute__((nonnull)),constvoid*src__attribute__((nonnull)),size_tlen);
Note that thenonnull
attribute indicates that passing null to a non-nullparameter is undefined behavior, which the optimizer may take advantage of to,e.g., remove null checks. The_Nonnull
type qualifier indicates that apointer cannot be null in a more general manner (because it is part of the typesystem) and does not imply undefined behavior, making it more widely applicable.
returns_nonnull¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Thereturns_nonnull
attribute indicates that a particular function (orObjective-C method) always returns a non-null pointer. For example, aparticular systemmalloc
might be defined to terminate a process whenmemory is not available rather than returning a null pointer:
externvoid*malloc(size_tsize)__attribute__((returns_nonnull));
Thereturns_nonnull
attribute implies that returning a null pointer isundefined behavior, which the optimizer may take advantage of. The_Nonnull
type qualifier indicates that a pointer cannot be null in a more general manner(because it is part of the type system) and does not imply undefined behavior,making it more widely applicable
OpenCL Address Spaces¶
The address space qualifier may be used to specify the region of memory that isused to allocate the object. OpenCL supports the following address spaces:__generic(generic), __global(global), __local(local), __private(private),__constant(constant).
__constantintc=...;__genericint*foo(globalint*g){__localint*l;privateintp;...returnl;}
More details can be found in the OpenCL C language Spec v2.0, Section 6.5.
[[clang::opencl_global_device]], [[clang::opencl_global_host]]¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Theglobal_device
andglobal_host
address space attributes specify thatan object is allocated in global memory on the device/host. It helps todistinguish USM (Unified Shared Memory) pointers that access global devicememory from those that access global host memory. These new address spaces area subset of the__global/opencl_global
address space, the full address spaceset model for OpenCL 2.0 with the extension looks as follows:
generic->global->host->device->private->localconstant
Asglobal_device
andglobal_host
are a subset of__global/opencl_global
address spaces it is allowed to convertglobal_device
andglobal_host
address spaces to__global/opencl_global
address spaces (following ISO/IEC TR 18037 5.1.3“Address space nesting and rules for pointers”).
__constant, constant, [[clang::opencl_constant]]¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
The constant address space attribute signals that an object is located ina constant (non-modifiable) memory region. It is available to all work items.Any type can be annotated with the constant address space attribute. Objectswith the constant address space qualifier can be declared in any scope and musthave an initializer.
__generic, generic, [[clang::opencl_generic]]¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
The generic address space attribute is only available with OpenCL v2.0 and later.It can be used with pointer types. Variables in global and local scope andfunction parameters in non-kernel functions can have the generic address spacetype attribute. It is intended to be a placeholder for any other address spaceexcept for ‘__constant’ in OpenCL code which can be used with multiple addressspaces.
__global, global, [[clang::opencl_global]]¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
The global address space attribute specifies that an object is allocated inglobal memory, which is accessible by all work items. The content stored in thismemory area persists between kernel executions. Pointer types to the globaladdress space are allowed as function parameters or local variables. Startingwith OpenCL v2.0, the global address space can be used with global (programscope) variables and static local variable as well.
__local, local, [[clang::opencl_local]]¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
The local address space specifies that an object is allocated in the local (workgroup) memory area, which is accessible to all work items in the same workgroup. The content stored in this memory region is not accessible afterthe kernel execution ends. In a kernel function scope, any variable can be inthe local address space. In other scopes, only pointer types to the local addressspace are allowed. Local address space variables cannot have an initializer.
__private, private, [[clang::opencl_private]]¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
The private address space specifies that an object is allocated in the private(work item) memory. Other work items cannot access the same memory area and itscontent is destroyed after work item execution ends. Local variables can bedeclared in the private address space. Function arguments are always in theprivate address space. Kernel function arguments of a pointer or an array typecannot point to the private address space.
Performance Constraint Attributes¶
Thenonblocking
,blocking
,nonallocating
andallocating
attributes can be attachedto function types, including blocks, C++ lambdas, and member functions. The attributes declareconstraints about a function’s behavior pertaining to blocking and heap memory allocation.
There are several rules for function types with these attributes, enforced withcompiler warnings:
When assigning or otherwise converting to a function pointer of
nonblocking
ornonallocating
type, the source must also be a function or function pointer ofthat type, unless it is a null pointer, i.e. the attributes should not be “spoofed”. Conversionsthat remove the attributes are transparent and valid.An override of a
nonblocking
ornonallocating
virtual method must also be declaredwith that same attribute (or a stronger one.) An overriding method may add an attribute.A redeclaration of a
nonblocking
ornonallocating
function must also be declared withthe same attribute (or a stronger one). A redeclaration may add an attribute.
The warnings are controlled by-Wfunction-effects
, which is disabled by default.
The compiler also diagnoses function calls fromnonblocking
andnonallocating
functions to other functions which lack the appropriate attribute.
allocating¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Declares that a function potentially allocates heap memory, and prevents any potential inferenceofnonallocating
by the compiler.
blocking¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Declares that a function potentially blocks, and prevents any potential inference ofnonblocking
by the compiler.
nonallocating¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Declares that a function or function type either does or does not allocate heap memory, accordingto the optional, compile-time constant boolean argument, which defaults to true. When the argumentis false, the attribute is equivalent toallocating
.
nonblocking¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Declares that a function or function type either does or does not block in any way, accordingto the optional, compile-time constant boolean argument, which defaults to true. When the argumentis false, the attribute is equivalent toblocking
.
For the purposes of diagnostics,nonblocking
is considered to include thenonallocating
guarantee and is therefore a “stronger” constraint or attribute.
Statement Attributes¶
#pragma clang loop¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
`` loop`` |
The#pragmaclangloop
directive allows loop optimization hints to bespecified for the subsequent loop. The directive allows pipelining to bedisabled, or vectorization, vector predication, interleaving, and unrolling tobe enabled or disabled. Vector width, vector predication, interleave count,unrolling count, and the initiation interval for pipelining can be explicitlyspecified. Seelanguage extensionsfor details.
#pragma unroll, #pragma nounroll¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
`` loop`` |
Loop unrolling optimization hints can be specified with#pragmaunroll
and#pragmanounroll
. The pragma is placed immediately before a for, while,do-while, or c++11 range-based for loop. GCC’s loop unrolling hints#pragmaGCCunroll
and#pragmaGCCnounroll
are also supported and haveidentical semantics to#pragmaunroll
and#pragmanounroll
.
Specifying#pragmaunroll
without a parameter directs the loop unroller toattempt to fully unroll the loop if the trip count is known at compile time andattempt to partially unroll the loop if the trip count is not known at compiletime:
#pragma unrollfor(...){...}
Specifying the optional parameter,#pragmaunroll_value_
, directs theunroller to unroll the loop_value_
times. The parameter may optionally beenclosed in parentheses:
#pragma unroll 16for(...){...}#pragma unroll(16)for(...){...}
Specifying#pragmanounroll
indicates that the loop should not be unrolled:
#pragma nounrollfor(...){...}
#pragmaunroll
and#pragmaunroll_value_
have identical semantics to#pragmaclangloopunroll(enable)
and#pragmaclangloopunroll_count(_value_)
respectively.#pragmanounroll
is equivalent to#pragmaclangloopunroll(disable)
. Seelanguage extensionsfor further details including limitations of the unroll hints.
[loop]¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
The[loop]
directive allows loop optimization hints to bespecified for the subsequent loop. The directive allows unrolling tobe disabled and is not compatible with [unroll(x)].
Specifying the parameter,[loop]
, directs theunroller to not unroll the loop.
[loop]for(...){...}
[loop]while(...){...}
[loop]do{...}while(...)
Seehlsl loop extensionsfor details.
[unroll(x)], [unroll]¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
Loop unrolling optimization hints can be specified with[unroll(x)]
. The attribute is placed immediately before a for, while,or do-while.Specifying the parameter,[unroll(_value_)]
, directs theunroller to unroll the loop_value_
times. Note: [unroll(x)] is not compatible with [loop].
[unroll(4)]for(...){...}
[unroll]for(...){...}
[unroll(4)]while(...){...}
[unroll]while(...){...}
[unroll(4)]do{...}while(...)
[unroll]do{...}while(...)
Seehlsl loop extensionsfor details.
__read_only, __write_only, __read_write (read_only, write_only, read_write)¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The access qualifiers must be used with image object arguments or pipe argumentsto declare if they are being read or written by a kernel or function.
The read_only/__read_only, write_only/__write_only and read_write/__read_writenames are reserved for use as access qualifiers and shall not be used otherwise.
kernelvoidfoo(read_onlyimage2d_timageA,write_onlyimage2d_timageB){...}
In the above example imageA is a read-only 2D image object, and imageB is awrite-only 2D image object.
The read_write (or __read_write) qualifier can not be used with pipe.
More details can be found in the OpenCL C language Spec v2.0, Section 6.6.
assume¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Theassume
attribute is used to indicate to the optimizer that acertain condition is assumed to be true at a certain point in theprogram. If this condition is violated at runtime, the behavior isundefined.assume
can only be applied to a null statement.
Different optimisers are likely to react differently to the presence ofthis attribute; in some cases, addingassume
may affect performancenegatively. It should be used with parsimony and care.
Example:
intf(intx,inty){[[assume(x==27)]];[[assume(x==y)]];returny+1;// May be optimised to `return 28`.}
atomic¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Theatomic
attribute can be applied tocompound statements to override orfurther specify the default atomic code-generation behavior, especially ontargets such as AMDGPU. You can annotate compound statements with optionsto modify how atomic instructions inside that statement are emitted at the IRlevel.
For details, see the documentation for@atomic
constexpr¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
The[[msvc::constexpr]]
attribute can be applied only to a functiondefinition or areturn
statement. It does not impact function declarations.A[[msvc::constexpr]]
function cannot beconstexpr
orconsteval
.A[[msvc::constexpr]]
function is treated as if it were aconstexpr
functionwhen it is evaluated in a constant context of[[msvc::constexpr]]return
statement.Otherwise, it is treated as a regular function.
Semantics of this attribute are enabled only under MSVC compatibility(-fms-compatibility-version
) 19.33 and later.
fallthrough¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Thefallthrough
(orclang::fallthrough
) attribute is usedto annotate intentional fall-throughbetween switch labels. It can only be applied to a null statement placed at apoint of execution between any statement and the next switch label. It iscommon to mark these places with a specific comment, but this attribute ismeant to replace comments with a more strict annotation, which can be checkedby the compiler. This attribute doesn’t change semantics of the code and canbe used wherever an intended fall-through occurs. It is designed to mimiccontrol-flow statements likebreak;
, so it can be placed in most placeswherebreak;
can, but only if there are no statements on the execution pathbetween it and the next switch label.
By default, Clang does not warn on unannotated fallthrough from oneswitch
case to another. Diagnostics on fallthrough without a corresponding annotationcan be enabled with the-Wimplicit-fallthrough
argument.
Here is an example:
// compile with -Wimplicit-fallthroughswitch(n){case22:case33:// no warning: no statements between case labelsf();case44:// warning: unannotated fall-throughg();[[clang::fallthrough]];case55:// no warningif(x){h();break;}else{i();[[clang::fallthrough]];}case66:// no warningp();[[clang::fallthrough]];// warning: fallthrough annotation does not// directly precede case labelq();case77:// warning: unannotated fall-throughr();}
intel_reqd_sub_group_size¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
The optional attribute intel_reqd_sub_group_size can be used to indicate thatthe kernel must be compiled and executed with the specified subgroup size. Whenthis attribute is present, get_max_sub_group_size() is guaranteed to return thespecified integer value. This is important for the correctness of many subgroupalgorithms, and in some cases may be used by the compiler to generate more optimalcode. Seecl_intel_required_subgroup_size<https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.txt>for details.
likely and unlikely¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
Thelikely
andunlikely
attributes are used as compiler hints.The attributes are used to aid the compiler to determine which branch islikely or unlikely to be taken. This is done by marking the branch substatementwith one of the two attributes.
It isn’t allowed to annotate a single statement with bothlikely
andunlikely
. Annotating thetrue
andfalse
branch of anif
statement with the same likelihood attribute will result in a diagnostic andthe attributes are ignored on both branches.
In aswitch
statement it’s allowed to annotate multiplecase
labelsor thedefault
label with the same likelihood attribute. This makes* all labels without an attribute have a neutral likelihood,* all labels marked[[likely]]
have an equally positive likelihood, and* all labels marked[[unlikely]]
have an equally negative likelihood.The neutral likelihood is the more likely of path execution than the negativelikelihood. The positive likelihood is the more likely of path of executionthan the neutral likelihood.
These attributes have no effect on the generated code when usingPGO (Profile-Guided Optimization) or at optimization level 0.
In Clang, the attributes will be ignored if they’re not placed on* thecase
ordefault
label of aswitch
statement,* or on the substatement of anif
orelse
statement,* or on the substatement of anfor
orwhile
statement.The C++ Standard recommends to honor them on every statement in thepath of execution, but that can be confusing:
if(b){[[unlikely]]--b;// In the path of execution,// this branch is considered unlikely.}if(b){--b;if(b)return;[[unlikely]]--b;// Not in the path of execution,}// the branch has no likelihood information.if(b){--b;foo(b);// Whether or not the next statement is in the path of execution depends// on the declaration of foo():// In the path of execution: void foo(int);// Not in the path of execution: [[noreturn]] void foo(int);// This means the likelihood of the branch depends on the declaration// of foo().[[unlikely]]--b;}
Below are some example usages of the likelihood attributes and their effects:
if(b)[[likely]]{// Placement on the first statement in the branch.// The compiler will optimize to execute the code here.}else{}if(b)[[unlikely]]b++;// Placement on the first statement in the branch.else{// The compiler will optimize to execute the code here.}if(b){[[unlikely]]b++;// Placement on the second statement in the branch.}// The attribute will be ignored.if(b)[[likely]]{[[unlikely]]b++;// No contradiction since the second attribute}// is ignored.if(b);else[[likely]]{// The compiler will optimize to execute the code here.}if(b);else// The compiler will optimize to execute the next statement.[[likely]]b=f();if(b)[[likely]];// Both branches are likely. A diagnostic is issuedelse[[likely]];// and the attributes are ignored.if(b)[[likely]]inti=5;// Issues a diagnostic since the attribute// isn't allowed on a declaration.switch(i){[[likely]]case1:// This value is likely...break;[[unlikely]]case2:// This value is unlikely...[[fallthrough]];case3:// No likelihood attribute...[[likely]]break;// No effectcase4:[[likely]]{// attribute on substatement has no effect...break;}[[unlikely]]default:// All other values are unlikely...break;}switch(i){[[likely]]case0:// This value and code path is likely...[[fallthrough]];case1:// No likelihood attribute, code path is neutralbreak;// falling through has no effect on the likelihoodcase2:// No likelihood attribute, code path is neutral[[fallthrough]];[[unlikely]]default:// This value and code path are both unlikelybreak;}for(inti=0;i!=size;++i)[[likely]]{...// The loop is the likely path of execution}for(constauto&E:Elements)[[likely]]{...// The loop is the likely path of execution}while(i!=size)[[unlikely]]{...// The loop is the unlikely path of execution}// The generated code will optimize to skip the loop bodywhile(true)[[unlikely]]{...// The attribute has no effect}// Clang elides the comparison and generates an infinite// loop
musttail¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
If areturn
statement is markedmusttail
, this indicates that thecompiler must generate a tail call for the program to be correct, even whenoptimizations are disabled. This guarantees that the call will not causeunbounded stack growth if it is part of a recursive cycle in the call graph.
If the callee is a virtual function that is implemented by a thunk, there isno guarantee in general that the thunk tail-calls the implementation of thevirtual function, so such a call in a recursive cycle can still result inunbounded stack growth.
clang::musttail
can only be applied to areturn
statement whose valueis the result of a function call (even functions returning void must usereturn
, although no value is returned). The target function must have thesame number of arguments as the caller. The types of the return value and allarguments must be similar according to C++ rules (differing only in cvqualifiers or array size), including the implicit “this” argument, if any.Any variables in scope, including all arguments to the function and thereturn value must be trivially destructible. The calling convention of thecaller and callee must match, and they must not be variadic functions or haveold style K&R C function declarations.
The lifetimes of all local variables and function parameters end immediatelybefore the call to the function. This means that it is undefined behaviour topass a pointer or reference to a local variable to the called function, whichis not the case without the attribute. Clang will emit a warning in commoncases where this happens.
clang::musttail
provides assurances that the tail call can be optimized onall targets, not just one.
nomerge¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
If a statement is markednomerge
and contains call expressions, those callexpressions inside the statement will not be merged during optimization. Thisattribute can be used to prevent the optimizer from obscuring the sourcelocation of certain calls. For example, it will prevent tail merging otherwiseidentical code sequences that raise an exception or terminate the program. Tailmerging normally reduces the precision of source location information, makingstack traces less useful for debugging. This attribute gives the user controlover the tradeoff between code size and debug information precision.
nomerge
attribute can also be used as function attribute to prevent allcalls to the specified function from merging. It has no effect on indirectcalls to such functions. For example:
[[clang::nomerge]]voidfoo(int){}voidbar(intx){auto*ptr=foo;if(x)foo(1);elsefoo(2);// will not be mergedif(x)ptr(1);elseptr(2);// indirect call, can be merged}
nomerge
attribute can also be used for pointers to functions toprevent calls through such pointer from merging. In such case theeffect applies only to a specific function pointer. For example:
[[clang::nomerge]]void(*foo)(int);voidbar(intx){auto*ptr=foo;if(x)foo(1);elsefoo(2);// will not be mergedif(x)ptr(1);elseptr(2);// 'ptr' has no 'nomerge' attribute, can be merged}
opencl_unroll_hint¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The opencl_unroll_hint attribute qualifier can be used to specify that a loop(for, while and do loops) can be unrolled. This attribute qualifier can beused to specify full unrolling or partial unrolling by a specified amount.This is a compiler hint and the compiler may ignore this directive. SeeOpenCL v2.0s6.11.5 for details.
suppress¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Thesuppress
attribute suppresses unwanted warnings coming from staticanalysis tools such as the Clang Static Analyzer. The tool will not reportany issues in source code annotated with the attribute.
The attribute cannot be used to suppress traditional Clang warnings, becausemany such warnings are emitted before the attribute is fully parsed.Consider using#pragmaclangdiagnostic
to control such diagnostics,as described inControlling Diagnostics via Pragmas.
Thesuppress
attribute can be placed on an individual statement in order tosuppress warnings about undesirable behavior occurring at that statement:
intfoo(){int*x=nullptr;...[[clang::suppress]]return*x;// null pointer dereference warning suppressed here}
Putting the attribute on a compound statement suppresses all warnings in scope:
intfoo(){[[clang::suppress]]{int*x=nullptr;...return*x;// warnings suppressed in the entire scope}}
The attribute can also be placed on entire declarations of functions, classes,variables, member variables, and so on, to suppress warnings relatedto the declarations themselves. When used this way, the attribute additionallysuppresses all warnings in the lexical scope of the declaration:
class[[clang::suppress]]C{intfoo(){int*x=nullptr;...return*x;// warnings suppressed in the entire class scope}intbar();};intC::bar(){int*x=nullptr;...return*x;// warning NOT suppressed! - not lexically nested in 'class C{}'}
Some static analysis warnings are accompanied by one or more notes, and theline of code against which the warning is emitted isn’t necessarily the bestfor suppression purposes. In such cases the tools are allowed to implementadditional ways to suppress specific warnings based on the attribute attachedto a note location.
For example, the Clang Static Analyzer suppresses memory leak warnings whenthe suppression attribute is placed at the allocation site (highlited bya “note: memory is allocated”), which may be different from the line of codeat which the program “loses track” of the pointer (where the warningis ultimately emitted):
intbar1(boolcoin_flip){__attribute__((suppress))int*result=(int*)malloc(sizeof(int));if(coin_flip)return1;// warning about this leak path is suppressedreturn*result;// warning about this leak path is also suppressed}intbar2(boolcoin_flip){int*result=(int*)malloc(sizeof(int));if(coin_flip)return1;// leak warning on this path NOT suppressed__attribute__((suppress))return*result;// leak warning is suppressed only on this path}
When written as[[gsl::suppress]]
, this attribute suppresses specificclang-tidy diagnostics for rules of theC++ Core Guidelines in a portableway. The attribute can be attached to declarations, statements, and atnamespace scope.
[[gsl::suppress("Rh-public")]]voidf_(){int*p;[[gsl::suppress("type")]]{p=reinterpret_cast<int*>(7);}}namespaceN{[[clang::suppress("type","bounds")]];...}
sycl_special_class¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
SYCL defines some special classes (accessor, sampler, and stream) which requirespecific handling during the generation of the SPIR entry point.The__attribute__((sycl_special_class))
attribute is used in SYCLheaders to indicate that a class or a struct needs a specific handling whenit is passed from host to device.Special classes will have a mandatory__init
method and an optional__finalize
method (the__finalize
method is used only with thestream
type). Kernel parameters types are extract from the__init
methodparameters. The kernel function arguments list is derived from thearguments of the__init
method. The arguments of the__init
method arecopied into the kernel function argument list and the__init
and__finalize
methods are called at the beginning and the end of the kernel,respectively.The__init
and__finalize
methods must be defined inside thespecial class.Please note that this is an attribute that is used as an internalimplementation detail and not intended to be used by external users.
The syntax of the attribute is as follows:
class __attribute__((sycl_special_class)) accessor {};class [[clang::sycl_special_class]] accessor {};
This is a code example that illustrates the use of the attribute:
class__attribute__((sycl_special_class))SpecialType{intF1;intF2;void__init(intf1){F1=f1;F2=f1;}void__finalize(){}public:SpecialType()=default;intgetF2()const{returnF2;}};intmain(){SpecialTypeT;cgh.single_task([=]{T.getF2();});}
This would trigger the following kernel entry point in the AST:
void__sycl_kernel(intf1){SpecialTypeT;T.__init(f1);...T.__finalize()}
Type Attributes¶
__ptr32¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__ptr32
qualifier represents a native pointer on a 32-bit system. On a64-bit system, a pointer with__ptr32
is extended to a 64-bit pointer. The__sptr
and__uptr
qualifiers can be used to specify whether the pointeris sign extended or zero extended. This qualifier is enabled under-fms-extensions
.
__ptr64¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__ptr64
qualifier represents a native pointer on a 64-bit system. On a32-bit system, a__ptr64
pointer is truncated to a 32-bit pointer. Thisqualifier is enabled under-fms-extensions
.
__sptr¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__sptr
qualifier specifies that a 32-bit pointer should be signextended when converted to a 64-bit pointer.
__uptr¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__uptr
qualifier specifies that a 32-bit pointer should be zeroextended when converted to a 64-bit pointer.
align_value¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
The align_value attribute can be added to the typedef of a pointer type or thedeclaration of a variable of pointer or reference type. It specifies that thepointer will point to, or the reference will bind to, only objects with atleast the provided alignment. This alignment value must be some positive powerof 2.
typedefdouble*aligned_double_ptr__attribute__((align_value(64)));voidfoo(double&x__attribute__((align_value(128)),aligned_double_ptry){...}
If the pointer value does not have the specified alignment at runtime, thebehavior of the program is undefined.
annotate_type¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
This attribute is used to add annotations to types, typically for use by staticanalysis tools that are not integrated into the core Clang compiler (e.g.,Clang-Tidy checks or out-of-tree Clang-based tools). It is a counterpart to theannotate attribute, which serves the same purpose, but for declarations.
The attribute takes a mandatory string literal argument specifying theannotation category and an arbitrary number of optional arguments that provideadditional information specific to the annotation category. The optionalarguments must be constant expressions of arbitrary type.
For example:
int*[[clang::annotate_type("category1","foo",1)]]f(int[[clang::annotate_type("category2")]]*);
The attribute does not have any effect on the semantics of the type system,neither type checking rules, nor runtime semantics. In particular:
std::is_same<T,T[[clang::annotate_type("foo")]]>
is true for all typesT
.It is not permissible for overloaded functions or template specializationsto differ merely by an
annotate_type
attribute.The presence of an
annotate_type
attribute will not affect namemangling.
arm_sve_vector_bits¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
Thearm_sve_vector_bits(N)
attribute is defined by the Arm C LanguageExtensions (ACLE) for SVE. It is used to define fixed-length (VLST) variants ofsizeless types (VLAT).
For example:
#include<arm_sve.h>#if __ARM_FEATURE_SVE_BITS==512typedefsvint32_tfixed_svint32_t__attribute__((arm_sve_vector_bits(512)));#endif
Creates a typefixed_svint32_t
that is a fixed-length variant ofsvint32_t
that contains exactly 512-bits. Unlikesvint32_t
, this typecan be used in globals, structs, unions, and arrays, all of which areunsupported for sizeless types.
The attribute can be attached to a single SVE vector (such assvint32_t
) orto the SVE predicate typesvbool_t
, this excludes tuple types such assvint32x4_t
. The behavior of the attribute is undefined unlessN==__ARM_FEATURE_SVE_BITS
, the implementation defined feature macro that isenabled under the-msve-vector-bits
flag.
For more information SeeArm C Language Extensions for SVE for more information.
bpf_fastcall¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Functions annotated with this attribute are likely to be inlined by BPF JIT.It is assumed that inlined implementation uses less caller saved registers,than a regular function.Specifically, the following registers are likely to be preserved:-R0
if function return value isvoid
;-R2-R5`iffunctiontakes1argument;-``R3-R5`iffunctiontakes2arguments;-``R4-R5`iffunctiontakes3arguments;-``R5
if function takes 4 arguments;
For such functions Clang generates code pattern that allows BPF JITto recognize and remove unnecessary spills and fills of the preservedregisters.
btf_type_tag¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Clang supports the__attribute__((btf_type_tag("ARGUMENT")))
attribute forall targets. It only has effect when-g
is specified on the command line andis currently silently ignored when not applied to a pointer type (note: thisscenario may be diagnosed in the future).
TheARGUMENT
string will be preserved in IR and emitted to DWARF for thetypes used in variable declarations, function declarations, or typedefdeclarations.
For BPF targets, theARGUMENT
string will also be emitted to .BTF ELFsection.
cfi_unchecked_callee¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
cfi_unchecked_callee
is a function type attribute which prevents the compiler from instrumentingControl Flow Integrity checks on indirectfunction calls. Specifically, the attribute has the following semantics:
Indirect calls to a function type with this attribute will not be instrumented with CFI. That is,the indirect call will not be checked. Note that this only changes the behavior for indirect callson pointers to function types having this attribute. It does not prevent all indirect function callsfor a given type from being checked.
All direct references to a function whose type has this attribute will always reference thefunction definition rather than an entry in the CFI jump table.
When a pointer to a function with this attribute is implicitly cast to a pointer to a functionwithout this attribute, the compiler will give a warning saying this attribute is discarded. Thiswarning can be silenced with an explicit cast. Note an explicit cast just disables the warning, sodirect references to a function with a
cfi_unchecked_callee
attribute will still reference thefunction definition rather than the CFI jump table.
#define CFI_UNCHECKED_CALLEE __attribute__((cfi_unchecked_callee))voidno_cfi()CFI_UNCHECKED_CALLEE{}void(*with_cfi)()=no_cfi;// warning: implicit conversion discards `cfi_unchecked_callee` attribute.// `with_cfi` also points to the actual definition of `no_cfi` rather than// its jump table entry.voidinvoke(void(CFI_UNCHECKED_CALLEE*func)()){func();// CFI will not instrument this indirect call.void(*func2)()=func;// warning: implicit conversion discards `cfi_unchecked_callee` attribute.func2();// CFI will instrument this indirect call. Users should be careful however because if this// references a function with type `cfi_unchecked_callee`, then the CFI check may incorrectly// fail because the reference will be to the function definition rather than the CFI jump// table entry.}
This attribute can only be applied on functions or member functions. This attribute can be a goodalternative tono_sanitize("cfi")
if you only want to disable innstrumentation for specific indirectcalls rather than applyingno_sanitize("cfi")
on the whole function containing indirect call. Notethatcfi_unchecked_attribute
is a type attribute doesn’t disable CFI instrumentation on a functionbody.
clang_arm_mve_strict_polymorphism¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
This attribute is used in the implementation of the ACLE intrinsics for the ArmMVE instruction set. It is used to define the vector types used by the MVEintrinsics.
Its effect is to modify the behavior of a vector type with respect to functionoverloading. If a candidate function for overload resolution has a parametertype with this attribute, then the selection of that candidate function will bedisallowed if the actual argument can only be converted via a lax vectorconversion. The aim is to prevent spurious ambiguity in ARM MVE polymorphicintrinsics.
voidoverloaded(uint16x8_tvector,uint16_tscalar);voidoverloaded(int32x4_tvector,int32_tscalar);uint16x8_tmyVector;uint16_tmyScalar;// myScalar is promoted to int32_t as a side effect of the addition,// so if lax vector conversions are considered for myVector, then// the two overloads are equally good (one argument conversion// each). But if the vector has the __clang_arm_mve_strict_polymorphism// attribute, only the uint16x8_t,uint16_t overload will match.overloaded(myVector,myScalar+1);
However, this attribute does not prohibit lax vector conversions in contextsother than overloading.
uint16x8_tfunction();// This is still permitted with lax vector conversion enabled, even// if the vector types have __clang_arm_mve_strict_polymorphismint32x4_tresult=function();
cmse_nonsecure_call¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
This attribute declares a non-secure function type. When compiling for securestate, a call to such a function would switch from secure to non-secure state.All non-secure function calls must happen only through a function pointer, anda non-secure function type should only be used as a base type of a pointer.SeeARMv8-M Security Extensions: Requirements on DevelopmentTools - Engineering Specification Documentation for more information.
device_builtin_surface_type¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
Thedevice_builtin_surface_type
attribute can be applied to a classtemplate when declaring the surface reference. A surface reference variablecould be accessed on the host side and, on the device side, might be translatedinto an internal surface object, which is established through surface bind andunbind runtime APIs.
device_builtin_texture_type¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
Thedevice_builtin_texture_type
attribute can be applied to a classtemplate when declaring the texture reference. A texture reference variablecould be accessed on the host side and, on the device side, might be translatedinto an internal texture object, which is established through texture bind andunbind runtime APIs.
enforce_read_only_placement¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
- This attribute is attached to a structure, class or union declaration.
When attached to a record declaration/definition, it checks if all instancesof this type can be placed in the read-only data segment of the program. If itfinds an instance that can not be placed in a read-only segment, the compileremits a warning at the source location where the type was used.
Examples:*
struct__attribute__((enforce_read_only_placement))Foo;
*struct__attribute__((enforce_read_only_placement))Bar{...};
Both
Foo
andBar
types have theenforce_read_only_placement
attribute.The goal of introducing this attribute is to assist developers with writing securecode. A
const
-qualified global is generally placed in the read-only sectionof the memory that has additional run time protection from malicious writes. Byattaching this attribute to a declaration, the developer can express the intentto place all instances of the annotated type in the read-only program memory.Note 1: The attribute doesn’t guarantee that the object will be placed in theread-only data segment as it does not instruct the compiler to ensure sucha placement. It emits a warning if something in the code can be proven to preventan instance from being placed in the read-only data segment.
Note 2: Currently, clang only checks if all global declarations of a given type ‘T’are
const
-qualified. The following conditions would also prevent the data to beput into read only segment, but the corresponding warnings are not yet implemented.An instance of type
T
is allocated on the heap/stack.Type
T
defines/inherits a mutable field.Type
T
defines/inherits non-constexpr constructor(s) for initialization.A field of type
T
is defined by typeQ
, which does not bear theenforce_read_only_placement
attribute.A type
Q
inherits from typeT
and it does not have theenforce_read_only_placement
attribute.
noderef¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Thenoderef
attribute causes clang to diagnose dereferences of annotated pointer types.This is ideally used with pointers that point to special memory which cannot be readfrom or written to, but allowing for the pointer to be used in pointer arithmetic.The following are examples of valid expressions where dereferences are diagnosed:
int__attribute__((noderef))*p;intx=*p;// warningint__attribute__((noderef))**p2;x=**p2;// warningint*__attribute__((noderef))*p3;p=*p3;// warningstructS{inta;};structS__attribute__((noderef))*s;x=s->a;// warningx=(*s).a;// warning
Not all dereferences may diagnose a warning if the value directed by the pointer may not beaccessed. The following are examples of valid expressions where may not be diagnosed:
int*q;int__attribute__((noderef))*p;q=&*p;q=*&p;structS{inta;};structS__attribute__((noderef))*s;p=&s->a;p=&(*s).a;
noderef
is currently only supported for pointers and arrays and not usablefor references or Objective-C object pointers.
intx=2;int__attribute__((noderef))&y=x;// warning: 'noderef' can only be used on an array or pointer type
id__attribute__((noderef))obj=[NSObjectnew];// warning: 'noderef' can only be used on an array or pointer type
objc_class_stub¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
This attribute specifies that the Objective-C class to which it applies isinstantiated at runtime.
Unlike__attribute__((objc_runtime_visible))
, a class having this attributestill has a “class stub” that is visible to the linker. This allows categoriesto be defined. Static message sends with the class as a receiver use a specialaccess pattern to ensure the class is lazily instantiated from the class stub.
Classes annotated with this attribute cannot be subclassed and cannot haveimplementations defined for them. This attribute is intended for use inSwift-generated headers for classes defined in Swift.
Adding or removing this attribute to a class is an ABI-breaking change.
riscv_rvv_vector_bits¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
On RISC-V targets, theriscv_rvv_vector_bits(N)
attribute is used to definefixed-length variants of sizeless types.
For example:
#include<riscv_vector.h>#if defined(__riscv_v_fixed_vlen)typedefvint8m1_tfixed_vint8m1_t__attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen)));#endif
Creates a typefixed_vint8m1_t
that is a fixed-length variant ofvint8m1_t
that contains exactly 512 bits. Unlikevint8m1_t
, this typecan be used in globals, structs, unions, and arrays, all of which areunsupported for sizeless types.
The attribute can be attached to a single RVV vector (such asvint8m1_t
).The attribute will be rejected unlessN==(__riscv_v_fixed_vlen*LMUL)
, the implementation defined feature macro thatis enabled under the-mrvv-vector-bits
flag.__riscv_v_fixed_vlen
canonly be a power of 2 between 64 and 65536.
For types where LMUL!=1,__riscv_v_fixed_vlen
needs to be scaled by the LMULof the type before passing to the attribute.
Forvbool*_t
types,__riscv_v_fixed_vlen
needs to be divided by thenumber from the type name. For example,vbool8_t
needs to use__riscv_v_fixed_vlen
/ 8. If the resulting value is not a multiple of 8,the type is not supported for that value of__riscv_v_fixed_vlen
.
type_visibility¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Thetype_visibility
attribute allows the visibility of a type and its vaguelinkage objects (vtable, typeinfo, typeinfo name) to be controlled separately fromthe visibility of functions and data members of the type.
For example, this can be used to give default visibility to the typeinfo and the vtableof a type while still keeping hidden visibility on its member functions and static datamembers.
This attribute can only be applied to types and namespaces.
If bothvisibility
andtype_visibility
are applied to a type or a namespace, thevisibility specified with thetype_visibility
attribute overrides the visibilityprovided with the regularvisibility
attribute.
Type Safety Checking¶
Clang supports additional attributes to enable checking type safety propertiesthat can’t be enforced by the C type system. To see warnings produced by thesechecks, ensure that -Wtype-safety is enabled. Use cases include:
MPI library implementations, where these attributes enable checking thatthe buffer type matches the passed
MPI_Datatype
;for HDF5 library there is a similar use case to MPI;
checking types of variadic functions’ arguments for functions like
fcntl()
andioctl()
.
You can detect support for these attributes with__has_attribute()
. Forexample:
#if defined(__has_attribute)# if __has_attribute(argument_with_type_tag) && \ __has_attribute(pointer_with_type_tag) && \ __has_attribute(type_tag_for_datatype)# define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx)))/* ... other macros ... */# endif#endif#if !defined(ATTR_MPI_PWT)# define ATTR_MPI_PWT(buffer_idx, type_idx)#endifintMPI_Send(void*buf,intcount,MPI_Datatypedatatype/*, other args omitted */)ATTR_MPI_PWT(1,3);
argument_with_type_tag¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Use__attribute__((argument_with_type_tag(arg_kind,arg_idx,type_tag_idx)))
on a function declaration to specify that the functionaccepts a type tag that determines the type of some other argument.
This attribute is primarily useful for checking arguments of variadic functions(pointer_with_type_tag
can be used in most non-variadic cases).
- In the attribute prototype above:
arg_kind
is an identifier that should be used when annotating allapplicable type tags.arg_idx
provides the position of a function argument. The expected type ofthis function argument will be determined by the function argument specifiedbytype_tag_idx
. In the code example below, “3” means that the type of thefunction’s third argument will be determined bytype_tag_idx
.type_tag_idx
provides the position of a function argument. This functionargument will be a type tag. The type tag will determine the expected type ofthe argument specified byarg_idx
. In the code example below, “2” meansthat the type tag associated with the function’s second argument should agreewith the type of the argument specified byarg_idx
.
For example:
intfcntl(intfd,intcmd,...)__attribute__((argument_with_type_tag(fcntl,3,2)));// The function's second argument will be a type tag; this type tag will// determine the expected type of the function's third argument.
pointer_with_type_tag¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Use__attribute__((pointer_with_type_tag(ptr_kind,ptr_idx,type_tag_idx)))
on a function declaration to specify that the function accepts a type tag thatdetermines the pointee type of some other pointer argument.
- In the attribute prototype above:
ptr_kind
is an identifier that should be used when annotating allapplicable type tags.ptr_idx
provides the position of a function argument; this functionargument will have a pointer type. The expected pointee type of this pointertype will be determined by the function argument specified bytype_tag_idx
. In the code example below, “1” means that the pointee typeof the function’s first argument will be determined bytype_tag_idx
.type_tag_idx
provides the position of a function argument; this functionargument will be a type tag. The type tag will determine the expected pointeetype of the pointer argument specified byptr_idx
. In the code examplebelow, “3” means that the type tag associated with the function’s thirdargument should agree with the pointee type of the pointer argument specifiedbyptr_idx
.
For example:
typedefintMPI_Datatype;intMPI_Send(void*buf,intcount,MPI_Datatypedatatype/*, other args omitted */)__attribute__((pointer_with_type_tag(mpi,1,3)));// The function's 3rd argument will be a type tag; this type tag will// determine the expected pointee type of the function's 1st argument.
type_tag_for_datatype¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
When declaring a variable, use__attribute__((type_tag_for_datatype(kind,type)))
to create a type tag thatis tied to thetype
argument given to the attribute.
- In the attribute prototype above:
kind
is an identifier that should be used when annotating all applicabletype tags.type
indicates the name of the type.
Clang supports annotating type tags of two forms.
Type tag that is a reference to a declared identifier.Use
__attribute__((type_tag_for_datatype(kind,type)))
when declaring thatidentifier:typedefintMPI_Datatype;externstructmpi_datatypempi_datatype_int__attribute__((type_tag_for_datatype(mpi,int)));#define MPI_INT ((MPI_Datatype) &mpi_datatype_int)// &mpi_datatype_int is a type tag. It is tied to type "int".Type tag that is an integral literal.Declare a
staticconst
variable with an initializer value and attach__attribute__((type_tag_for_datatype(kind,type)))
on that declaration:typedefintMPI_Datatype;staticconstMPI_Datatypempi_datatype_int__attribute__((type_tag_for_datatype(mpi,int)))=42;#define MPI_INT ((MPI_Datatype) 42)// The number 42 is a type tag. It is tied to type "int".
Thetype_tag_for_datatype
attribute also accepts an optional third argumentthat determines how the type of the function argument specified by eitherarg_idx
orptr_idx
is compared against the type associated with the typetag. (Recall that for theargument_with_type_tag
attribute, the type of thefunction argument specified byarg_idx
is compared against the typeassociated with the type tag. Also recall that for thepointer_with_type_tag
attribute, the pointee type of the function argument specified byptr_idx
iscompared against the type associated with the type tag.) There are two supportedvalues for this optional third argument:
layout_compatible
will cause types to be compared according tolayout-compatibility rules (In C++11 [class.mem] p 17, 18, see thelayout-compatibility rules for two standard-layout struct types and for twostandard-layout union types). This is useful when creating a type tagassociated with a struct or union type. For example:/* In mpi.h */typedefintMPI_Datatype;structinternal_mpi_double_int{doubled;inti;};externstructmpi_datatypempi_datatype_double_int__attribute__((type_tag_for_datatype(mpi,structinternal_mpi_double_int,layout_compatible)));#define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)intMPI_Send(void*buf,intcount,MPI_Datatypedatatype,...)__attribute__((pointer_with_type_tag(mpi,1,3)));/* In user code */structmy_pair{doublea;intb;};structmy_pair*buffer;MPI_Send(buffer,1,MPI_DOUBLE_INT/*, ... */);// no warning because the// layout of my_pair is// compatible with that of// internal_mpi_double_intstructmy_int_pair{inta;intb;}structmy_int_pair*buffer2;MPI_Send(buffer2,1,MPI_DOUBLE_INT/*, ... */);// warning because the// layout of my_int_pair// does not match that of// internal_mpi_double_int
must_be_null
specifies that the function argument specified by eitherarg_idx
(for theargument_with_type_tag
attribute) orptr_idx
(forthepointer_with_type_tag
attribute) should be a null pointer constant.The second argument to thetype_tag_for_datatype
attribute is ignored. Forexample:/* In mpi.h */typedefintMPI_Datatype;externstructmpi_datatypempi_datatype_null__attribute__((type_tag_for_datatype(mpi,void,must_be_null)));#define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)intMPI_Send(void*buf,intcount,MPI_Datatypedatatype,...)__attribute__((pointer_with_type_tag(mpi,1,3)));/* In user code */structmy_pair{doublea;intb;};structmy_pair*buffer;MPI_Send(buffer,1,MPI_DATATYPE_NULL/*, ... */);// warning: MPI_DATATYPE_NULL// was specified but buffer// is not a null pointer
Undocumented¶
This section lists attributes which are recognized by Clang, but which arecurrently missing documentation.
Alignas, align, alignas, aligned¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
|
No documentation.
NSObject¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
__kindof¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
No documentation.
acquired_after¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
No documentation.
acquired_before¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
No documentation.
address_space¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
alias¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
analyzer_noreturn¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
No documentation.
annotate¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
available_only_in_default_eval_method¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
blocks¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
capability, shared_capability¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
No documentation.
cdecl¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
No documentation.
cf_audited_transfer¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
cf_unknown_transfer¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
common¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
const¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
constant¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
No documentation.
consumable_auto_cast_state¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
No documentation.
consumable_set_state_on_read¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
No documentation.
device¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
No documentation.
exclusive_locks_required, requires_capability, requires_shared_capability, shared_locks_required¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
No documentation.
format_arg¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
global¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
No documentation.
guarded_by¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
No documentation.
guarded_var¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
No documentation.
host¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
No documentation.
ibaction¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
iboutlet¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
iboutletcollection¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
intel_ocl_bicc¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
No documentation.
interrupt¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
interrupt¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
No documentation.
launch_bounds¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
No documentation.
lock_returned¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
No documentation.
lockable¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
No documentation.
locks_excluded¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
No documentation.
matrix_type¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
may_alias¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
mips16¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
mode¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
ms_struct¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
naked¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
| Yes |
No documentation.
neon_polyvector_type¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
neon_vector_type¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
no_instrument_function¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
no_thread_safety_analysis¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
nocommon¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
nomips16¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
noreturn¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
No documentation.
objc_arc_weak_reference_unavailable¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
objc_bridge¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
objc_bridge_mutable¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
objc_bridge_related¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
objc_designated_initializer¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
objc_exception¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
objc_gc¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
objc_independent_class¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
objc_ownership¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
objc_precise_lifetime¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
objc_protocol_requires_explicit_implementation¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
objc_requires_property_definitions¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
objc_returns_inner_pointer¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
objc_root_class¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
packed¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
pascal¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
|
No documentation.
pt_guarded_by¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
No documentation.
pt_guarded_var¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
No documentation.
ptrauth_vtable_pointer¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
pure¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
reentrant_capability¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
reqd_work_group_size¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
No documentation.
returns_twice¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
scoped_lockable¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
No documentation.
sentinel¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
shared¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
No documentation.
unavailable¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
uuid¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
No documentation.
vec_type_hint¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
No documentation.
vecreturn¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
No documentation.
vector_size¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
visibility¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
warn_unused¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
weak_import¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
No documentation.
weakref¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
No documentation.
work_group_size_hint¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
No documentation.
Variable Attributes¶
HLSL Parameter Modifiers¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
HLSL function parameters are passed by value. Parameter declarations supportthree qualifiers to denote parameter passing behavior. The three qualifiers arein,out andinout.
Parameters annotated within or with no annotation are passed by value fromthe caller to the callee.
Parameters annotated without are written to the argument after the calleereturns (Note: arguments values passed intoout parametersare not copiedinto the callee).
Parameters annotated withinout are copied into the callee via a temporary,and copied back to the argument after the callee returns.
__ptrauth¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__ptrauth
qualifier allows the programmer to directly controlhow pointers are signed when they are stored in a particular variable.This can be used to strengthen the default protections of pointerauthentication and make it more difficult for an attacker to escalatean ability to alter memory into full control of a process.
#include<ptrauth.h>typedefvoid(*my_callback)(constvoid*);my_callback__ptrauth(ptrauth_key_process_dependent_code,1,0xe27a)callback;
The first argument to__ptrauth
is the name of the signing key.Valid key names for the target are defined in<ptrauth.h>
.
The second argument to__ptrauth
is a flag (0 or 1) specifying whetherthe object should use address discrimination.
The third argument to__ptrauth
is a 16-bit non-negative integer whichallows additional discrimination between objects.
always_destroy¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
Thealways_destroy
attribute specifies that a variable with static or threadstorage duration should have its exit-time destructor run. This attribute is thedefault unless clang was invoked with -fno-c++-static-destructors.
If a variable is explicitly declared with this attribute, Clang will silenceotherwise applicable-Wexit-time-destructors
warnings.
called_once¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Thecalled_once
attribute specifies that the annotated function or methodparameter is invoked exactly once on all execution paths. It only appliesto parameters with function-like types, i.e. function pointers or blocks. Thisconcept is particularly useful for asynchronous programs.
Clang implements a check forcalled_once
parameters,-Wcalled-once-parameter
. It is on by default and finds the followingviolations:
Parameter is not called at all.
Parameter is called more than once.
Parameter is not called on one of the execution paths.
In the latter case, Clang pinpoints the path where parameter is not invokedby showing the control-flow statement where the path diverges.
voidfooWithCallback(void(^callback)(void)__attribute__((called_once))){if(somePredicate()){...callback();}else{callback();// OK: callback is called on every path}}voidbarWithCallback(void(^callback)(void)__attribute__((called_once))){if(somePredicate()){...callback();// note: previous call is here}callback();// warning: callback is called twice}voidfoobarWithCallback(void(^callback)(void)__attribute__((called_once))){if(somePredicate()){// warning: callback is not called when condition is false...callback();}}
This attribute is useful for API developers who want to double-check if theyimplemented their method correctly.
clang::code_align¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Theclang::code_align(N)
attribute applies to a loop and specifies the bytealignment for a loop. The attribute accepts a positive integer constantinitialization expression indicating the number of bytes for the minimumalignment boundary. Its value must be a power of 2, between 1 and 4096(inclusive).
voidfoo(){intvar=0;[[clang::code_align(16)]]for(inti=0;i<10;++i)var++;}voidArray(int*array,size_tn){[[clang::code_align(64)]]for(inti=0;i<n;++i)array[i]=0;}voidcount(){inta1[10],inti=0;[[clang::code_align(32)]]while(i<10){a1[i]+=3;}}voidcheck(){inta=10;[[clang::code_align(8)]]do{a=a+1;}while(a<20);}template<intA>voidfunc(){[[clang::code_align(A)]]for(;;){}}
cleanup¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
This attribute allows a function to be run when a local variable goes out ofscope. The attribute takes the identifier of a function with a parameter typethat is a pointer to the type with the attribute.
staticvoidfoo(int*){...}staticvoidbar(int*){...}voidbaz(void){intx__attribute__((cleanup(foo)));{inty__attribute__((cleanup(bar)));}}
The above example will result in a call tobar
being passed the address ofy
wheny
goes out of scope, then a call tofoo
being passed theaddress ofx
whenx
goes out of scope. If two or more variables sharethe same scope, theircleanup
callbacks are invoked in the reverse orderthe variables were declared in. It is not possible to check the return value(if any) of thesecleanup
callback functions.
dllexport¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
| Yes |
The__declspec(dllexport)
attribute declares a variable, function, orObjective-C interface to be exported from the module. It is available under the-fdeclspec
flag for compatibility with various compilers. The primary useis for COFF object files which explicitly specify what interfaces are availablefor external use. See thedllexport documentation on MSDN for moreinformation.
dllimport¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
| Yes |
The__declspec(dllimport)
attribute declares a variable, function, orObjective-C interface to be imported from an external module. It is availableunder the-fdeclspec
flag for compatibility with various compilers. Theprimary use is for COFF object files which explicitly specify what interfacesare imported from external modules. See thedllimport documentation on MSDNfor more information.
Note that a dllimport function may still be inlined, if its definition isavailable and it doesn’t reference any non-dllimport functions or globalvariables.
ext_builtin_input¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
Vulkan shaders haveInput builtins. Those variables are externallyinitialized by the driver/pipeline, but each copy is private to the currentlane.
Those builtins can be declared using the[[vk::ext_builtin_input]] attributelike follows:
[[vk::ext_builtin_input(/* WorkgroupId */26)]]staticconstuint3groupid;
This variable will be lowered into a module-level variable, with theInputstorage class, and theBuiltIn 26 decoration.
The full documentation for this inline SPIR-V attribute can be found here:https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md
groupshared¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
HLSL enables threads of a compute shader to exchange values via shared memory.HLSL provides barrier primitives such as GroupMemoryBarrierWithGroupSync,and so on to ensure the correct ordering of reads and writes to shared memoryin the shader and to avoid data races.Here’s an example to declare a groupshared variable... code-block:: c++
groupshared GSData data[5*5*1];
The full documentation is available here:https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-syntax#group-shared
init_priority¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
In C++, the order in which global variables are initialized across translationunits is unspecified, unlike the ordering within a single translation unit. Theinit_priority
attribute allows you to specify a relative ordering for theinitialization of objects declared at namespace scope in C++ within a singlelinked image on supported platforms. The priority is given as an integer constantexpression between 101 and 65535 (inclusive). Priorities outside of that range arereserved for use by the implementation. A lower value indicates a higher priorityof initialization. Note that only the relative ordering of values is important.For example:
structSomeType{SomeType();};__attribute__((init_priority(200)))SomeTypeObj1;__attribute__((init_priority(101)))SomeTypeObj2;
Obj2
will be initializedbeforeObj1
despite the usual order ofinitialization being the opposite.
Note that this attribute does not control the initialization order of objectsacross final linked image boundaries like shared objects and executables.
On Windows,init_seg(compiler)
is represented with a priority of 200 andinit_seg(library)
is represented with a priority of 400.init_seg(user)
uses the default 65535 priority.
On MachO platforms, this attribute also does not control the order of initializationacross translation units, where it only affects the order within a single TU.
This attribute is only supported for C++ and Objective-C++ and is ignored inother language modes. Currently, this attribute is not implemented on z/OS.
init_seg¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The attribute applied bypragmainit_seg()
controls the section intowhich global initialization function pointers are emitted. It is onlyavailable with-fms-extensions
. Typically, this function pointer isemitted into.CRT$XCU
on Windows. The user can change the order ofinitialization by using a different section name with the same.CRT$XC
prefix and a suffix that sorts lexicographically before orafter the standard.CRT$XCU
sections. See theinit_segdocumentation on MSDN for more information.
leaf¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theleaf
attribute is used as a compiler hint to improve dataflow analysisin library functions. Functions marked with theleaf
attribute are not allowedto jump back into the caller’s translation unit, whether through invoking acallback function, an external function call, use oflongjmp
, or other means.Therefore, they cannot use or modify any data that does not escape the caller function’scompilation unit.
For more information seegcc documentation <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html>
loader_uninitialized¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theloader_uninitialized
attribute can be placed on global variables toindicate that the variable does not need to be zero initialized by the loader.On most targets, zero-initialization does not incur any additional cost.For example, most general purpose operating systems deliberately ensurethat all memory is properly initialized in order to avoid leaking privilegedinformation from the kernel or other programs. However, some targetsdo not make this guarantee, and on these targets, avoiding an unnecessaryzero-initialization can have a significant impact on load times and/or codesize.
A declaration with this attribute is a non-tentative definition just as if itprovided an initializer. Variables with this attribute are considered to beuninitialized in the same sense as a local variable, and the programs mustwrite to them before reading from them. If the variable’s type is a C++ classtype with a non-trivial default constructor, or an array thereof, this attributeonly suppresses the static zero-initialization of the variable, not the dynamicinitialization provided by executing the default constructor.
maybe_undef¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Themaybe_undef
attribute can be placed on a function parameter. It indicatesthat the parameter is allowed to use undef values. It informs the compilerto insert a freeze LLVM IR instruction on the function parameter.Please note that this is an attribute that is used as an internalimplementation detail and not intended to be used by external users.
In languages HIP, CUDA etc., some functions have multi-threaded semantics andit is enough for only one or some threads to provide defined arguments.Depending on semantics, undef arguments in some threads don’t produceundefined results in the function call. Since, these functions accept undefinedarguments,maybe_undef
attribute can be placed.
Sample usage:.. code-block:: c
void maybeundeffunc(int __attribute__((maybe_undef))param);
maybe_unused, unused¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
When passing the-Wunused
flag to Clang, entities that are unused by theprogram may be diagnosed. The[[maybe_unused]]
(or__attribute__((unused))
) attribute can be used to silence such diagnosticswhen the entity cannot be removed. For instance, a local variable may existsolely for use in anassert()
statement, which makes the local variableunused whenNDEBUG
is defined.
The attribute may be applied to the declaration of a class, a typedef, avariable, a function or method, a function parameter, an enumeration, anenumerator, a non-static data member, or a label.
#include<cassert>[[maybe_unused]]voidf([[maybe_unused]]boolthing1,[[maybe_unused]]boolthing2){[[maybe_unused]]boolb=thing1&&thing2;assert(b);}
model¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Themodel
attribute allows overriding the translation unit’scode model (specified by-mcmodel
) for a specific global variable.
On LoongArch, allowed values are “normal”, “medium”, “extreme”.
On x86-64, allowed values are"small"
and"large"
."small"
isroughly equivalent to-mcmodel=small
, meaning the global is considered“small” placed closer to the.text
section relative to “large” globals, andto prefer using 32-bit relocations to access the global."large"
is roughlyequivalent to-mcmodel=large
, meaning the global is considered “large” andplaced further from the.text
section relative to “small” globals, and64-bit relocations must be used to access the global.
no_destroy¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
Theno_destroy
attribute specifies that a variable with static or threadstorage duration shouldn’t have its exit-time destructor run. Annotating everystatic and thread duration variable with this attribute is equivalent toinvoking clang with -fno-c++-static-destructors.
If a variable is declared with this attribute, clang doesn’t access check orgenerate the type’s destructor. If you have a type that you only want to beannotated withno_destroy
, you can therefore declare the destructor private:
structonly_no_destroy{only_no_destroy();private:~only_no_destroy();};[[clang::no_destroy]]only_no_destroyglobal;// fine!
Note that destructors are still required for subobjects of aggregates annotatedwith this attribute. This is because previously constructed subobjects need tobe destroyed if an exception gets thrown before the initialization of thecomplete object is complete. For instance:
voidf(){try{[[clang::no_destroy]]staticonly_no_destroyarray[10];// error, only_no_destroy has a private destructor.}catch(...){// Handle the error}}
Here, if the construction ofarray[9]
fails with an exception,array[0..8]
will be destroyed, so the element’s destructor needs to be accessible.
nodebug¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Thenodebug
attribute allows you to suppress debugging information for afunction or method, for a variable that is not a parameter or a non-staticdata member, or for a typedef or using declaration.
noescape¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
noescape
placed on a function parameter of a pointer type is used to informthe compiler that the pointer cannot escape: that is, no reference to the objectthe pointer points to that is derived from the parameter value will surviveafter the function returns. Users are responsible for making sure parametersannotated withnoescape
do not actually escape. Callingfree()
on sucha parameter does not constitute an escape.
For example:
int*gp;voidnonescapingFunc(__attribute__((noescape))int*p){*p+=100;// OK.}voidescapingFunc(__attribute__((noescape))int*p){gp=p;// Not OK.}
Additionally, when the parameter is ablock pointer<https://clang.llvm.org/docs/BlockLanguageSpec.html>, the same restrictionapplies to copies of the block. For example:
typedefvoid(^BlockTy)();BlockTyg0,g1;voidnonescapingFunc(__attribute__((noescape))BlockTyblock){block();// OK.}voidescapingFunc(__attribute__((noescape))BlockTyblock){g0=block;// Not OK.g1=Block_copy(block);// Not OK either.}
nosvm¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
| Yes |
OpenCL 2.0 supports the optional__attribute__((nosvm))
qualifier forpointer variable. It informs the compiler that the pointer does not referto a shared virtual memory region. See OpenCL v2.0 s6.7.2 for details.
Since it is not widely used and has been removed from OpenCL 2.1, it is ignoredby Clang.
objc_externally_retained¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theobjc_externally_retained
attribute can be applied to strong localvariables, functions, methods, or blocks to opt intoexternally-retained semantics.
When applied to the definition of a function, method, or block, every parameterof the function with implicit strong retainable object pointer type isconsidered externally-retained, and becomesconst
. By explicitly annotatinga parameter with__strong
, you can opt back into the defaultnon-externally-retained behavior for that parameter. For instance,first_param
is externally-retained below, but notsecond_param
:
__attribute__((objc_externally_retained))voidf(NSArray*first_param,__strongNSArray*second_param){// ...}
Likewise, when applied to a strong local variable, that variable becomesconst
and is considered externally-retained.
When compiled without-fobjc-arc
, this attribute is ignored.
pass_object_size, pass_dynamic_object_size¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Note
The mangling of functions with parameters that are annotated withpass_object_size
is subject to change. You can get around this byusing__asm__("foo")
to explicitly name your functions, thus preservingyour ABI; also, non-overloadable C functions withpass_object_size
arenot mangled.
Thepass_object_size(Type)
attribute can be placed on function parameters toinstruct clang to call__builtin_object_size(param,Type)
at each callsiteof said function, and implicitly pass the result of this call in as an invisibleargument of typesize_t
directly after the parameter annotated withpass_object_size
. Clang will also replace any calls to__builtin_object_size(param,Type)
in the function by said implicitparameter.
Example usage:
intbzero1(char*constp__attribute__((pass_object_size(0))))__attribute__((noinline)){inti=0;for(/**/;i<(int)__builtin_object_size(p,0);++i){p[i]=0;}returni;}intmain(){charchars[100];intn=bzero1(&chars[0]);assert(n==sizeof(chars));return0;}
If successfully evaluating__builtin_object_size(param,Type)
at thecallsite is not possible, then the “failed” value is passed in. So, using thedefinition ofbzero1
from above, the following code would exit cleanly:
intmain2(intargc,char*argv[]){intn=bzero1(argv);assert(n==-1);return0;}
pass_object_size
plays a part in overload resolution. If two overloadcandidates are otherwise equally good, then the overload with one or moreparameters withpass_object_size
is preferred. This implies that the choicebetween two identical overloads both withpass_object_size
on one or moreparameters will always be ambiguous; for this reason, having two such overloadsis illegal. For example:
#define PS(N) __attribute__((pass_object_size(N)))// OKvoidFoo(char*a,char*b);// Overload A// OK -- overload A has no parameters with pass_object_size.voidFoo(char*aPS(0),char*bPS(0));// Overload B// Error -- Same signature (sans pass_object_size) as overload B, and both// overloads have one or more parameters with the pass_object_size attribute.voidFoo(void*aPS(0),void*b);// OKvoidBar(void*aPS(0));// Overload C// OKvoidBar(char*cPS(1));// Overload Dvoidmain(){charknown[10],*unknown;Foo(unknown,unknown);// Calls overload BFoo(known,unknown);// Calls overload BFoo(unknown,known);// Calls overload BFoo(known,known);// Calls overload BBar(known);// Calls overload DBar(unknown);// Calls overload D}
Currently,pass_object_size
is a bit restricted in terms of its usage:
Only one use of
pass_object_size
is allowed per parameter.It is an error to take the address of a function with
pass_object_size
onany of its parameters. If you wish to do this, you can create an overloadwithoutpass_object_size
on any parameters.It is an error to apply the
pass_object_size
attribute to parameters thatare not pointers. Additionally, any parameter thatpass_object_size
isapplied to must be markedconst
at its function’s definition.
Clang also supports thepass_dynamic_object_size
attribute, which behavesidentically topass_object_size
, but evaluates a call to__builtin_dynamic_object_size
at the callee instead of__builtin_object_size
.__builtin_dynamic_object_size
provides some extraruntime checks when the object size can’t be determined at compile-time. You canread more about__builtin_dynamic_object_size
here.
require_constant_initialization, constinit (C++20)¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
This attribute specifies that the variable to which it is attached is intendedto have aconstant initializeraccording to the rules of [basic.start.static]. The variable is required tohave static or thread storage duration. If the initialization of the variableis not a constant initializer an error will be produced. This attribute mayonly be used in C++; theconstinit
spelling is only accepted in C++20onwards.
Note that in C++03 strict constant expression checking is not done. Insteadthe attribute reports if Clang can emit the variable as a constant, even if it’snot technically a ‘constant initializer’. This behavior is non-portable.
Static storage duration variables with constant initializers avoid hard-to-findbugs caused by the indeterminate order of dynamic initialization. They can alsobe safely used during dynamic initialization across translation units.
This attribute acts as a compile time assertion that the requirementsfor constant initialization have been met. Since these requirements changebetween dialects and have subtle pitfalls it’s important to fail fast insteadof silently falling back on dynamic initialization.
The first use of the attribute on a variable must be part of, or precede, theinitializing declaration of the variable. C++20 requires theconstinit
spelling of the attribute to be present on the initializing declaration if itis used anywhere. The other spellings can be specified on a forward declarationand omitted on a later initializing declaration.
// -std=c++14#define SAFE_STATIC [[clang::require_constant_initialization]]structT{constexprT(int){}~T();// non-trivial};SAFE_STATICTx={42};// Initialization OK. Doesn't check destructor.SAFE_STATICTy=42;// error: variable does not have a constant initializer// copy initialization is not a constant expression on a non-literal type.
section, __declspec(allocate)¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
| Yes |
Thesection
attribute allows you to specify a specific section aglobal variable or function should be in after translation.
standalone_debug¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
Thestandalone_debug
attribute causes debug info to be emitted for a recordtype regardless of the debug info optimizations that are enabled with-fno-standalone-debug. This attribute only has an effect when debug infooptimizations are enabled (e.g. with -fno-standalone-debug), and is C++-only.
swift_async_context¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theswift_async_context
attribute marks a parameter of aswiftasynccall
function as having the special asynchronous context-parameter ABI treatment.
If the function is notswiftasynccall
, this attribute only generatesextended frame information.
A context parameter must have pointer or reference type.
swift_context¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theswift_context
attribute marks a parameter of aswiftcall
orswiftasynccall
function as having the special context-parameterABI treatment.
This treatment generally passes the context value in a special registerwhich is normally callee-preserved.
Aswift_context
parameter must either be the last parameter or must befollowed by aswift_error_result
parameter (which itself must always bethe last parameter).
A context parameter must have pointer or reference type.
swift_error_result¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theswift_error_result
attribute marks a parameter of aswiftcall
function as having the special error-result ABI treatment.
This treatment generally passes the underlying error value in and out ofthe function through a special register which is normally callee-preserved.This is modeled in C by pretending that the register is addressable memory:
The caller appears to pass the address of a variable of pointer type.The current value of this variable is copied into the register beforethe call; if the call returns normally, the value is copied back into thevariable.
The callee appears to receive the address of a variable. This addressis actually a hidden location in its own stack, initialized with thevalue of the register upon entry. When the function returns normally,the value in that hidden location is written back to the register.
Aswift_error_result
parameter must be the last parameter, and it must bepreceded by aswift_context
parameter.
Aswift_error_result
parameter must have typeT**
orT*&
for sometype T. Note that no qualifiers are permitted on the intermediate level.
It is undefined behavior if the caller does not pass a pointer orreference to a valid object.
The standard convention is that the error value itself (that is, thevalue stored in the apparent argument) will be null upon function entry,but this is not enforced by the ABI.
swift_indirect_result¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Theswift_indirect_result
attribute marks a parameter of aswiftcall
orswiftasynccall
function as having the special indirect-result ABItreatment.
This treatment gives the parameter the target’s normal indirect-resultABI treatment, which may involve passing it differently from an ordinaryparameter. However, only the first indirect result will receive thistreatment. Furthermore, low-level lowering may decide that a direct resultmust be returned indirectly; if so, this will take priority over theswift_indirect_result
parameters.
Aswift_indirect_result
parameter must either be the first parameter orfollow anotherswift_indirect_result
parameter.
Aswift_indirect_result
parameter must have typeT*
orT&
forsome object typeT
. IfT
is a complete type at the point ofdefinition of a function, it is undefined behavior if the argumentvalue does not point to storage of adequate size and alignment for avalue of typeT
.
Making indirect results explicit in the signature allows C functions todirectly construct objects into them without relying on languageoptimizations like C++’s named return value optimization (NRVO).
swiftasynccall¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Theswiftasynccall
attribute indicates that a function iscompatible with the low-level conventions of Swift async functions,provided it declares the right formal arguments.
In most respects, this is similar to theswiftcall
attribute, except forthe following:
A parameter may be marked
swift_async_context
,swift_context
orswift_indirect_result
(with the same restrictions on parameterordering asswiftcall
) but the parameter attributeswift_error_result
is not permitted.A
swiftasynccall
function must have return typevoid
.Within a
swiftasynccall
function, a call to aswiftasynccall
function that is the immediate operand of areturn
statement isguaranteed to be performed as a tail call. This syntax is allowed evenin C as an extension (a call to a void-returning function cannot be areturn operand in standard C). If something in the calling function wouldsemantically be performed after a guaranteed tail call, such as thenon-trivial destruction of a local variable or temporary,then the program is ill-formed.
Query for this attribute with__has_attribute(swiftasynccall)
. Query ifthe target supports the calling convention with__has_extension(swiftasynccc)
.
swiftcall¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
|
Theswiftcall
attribute indicates that a function should be calledusing the Swift calling convention for a function or function pointer.
The lowering for the Swift calling convention, as described by the SwiftABI documentation, occurs in multiple phases. The first, “high-level”phase breaks down the formal parameters and results into innately directand indirect components, adds implicit parameters for the genericsignature, and assigns the context and error ABI treatments to parameterswhere applicable. The second phase breaks down the direct parametersand results from the first phase and assigns them to registers or thestack. Theswiftcall
convention only handles this second phase oflowering; the C function type must accurately reflect the resultsof the first phase, as follows:
Results classified as indirect by high-level lowering should berepresented as parameters with the
swift_indirect_result
attribute.Results classified as direct by high-level lowering should be representedas follows:
First, remove any empty direct results.
If there are no direct results, the C result type should be
void
.If there is one direct result, the C result type should be a type withthe exact layout of that result type.
If there are a multiple direct results, the C result type should bea struct type with the exact layout of a tuple of those results.
Parameters classified as indirect by high-level lowering should berepresented as parameters of pointer type.
Parameters classified as direct by high-level lowering should beomitted if they are empty types; otherwise, they should be representedas a parameter type with a layout exactly matching the layout of theSwift parameter type.
The context parameter, if present, should be represented as a trailingparameter with the
swift_context
attribute.The error result parameter, if present, should be represented as atrailing parameter (always following a context parameter) with the
swift_error_result
attribute.
swiftcall
does not support variadic arguments or unprototyped functions.
The parameter ABI treatment attributes are aspects of the function type.A function type which applies an ABI treatment attribute to aparameter is a different type from an otherwise-identical function typethat does not. A single parameter may not have multiple ABI treatmentattributes.
Support for this feature is target-dependent, although it should besupported on every target that Swift supports. Query for this attributewith__has_attribute(swiftcall)
. Query if the target supports thecalling convention with__has_extension(swiftcc)
. This impliessupport for theswift_context
,swift_error_result
, andswift_indirect_result
attributes.
thread¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
The__declspec(thread)
attribute declares a variable with thread localstorage. It is available under the-fms-extensions
flag for MSVCcompatibility. See the documentation for__declspec(thread) on MSDN.
In Clang,__declspec(thread)
is generally equivalent in functionality to theGNU__thread
keyword. The variable must not have a destructor and must havea constant initializer, if any. The attribute only applies to variablesdeclared with static storage duration, such as globals, class static datamembers, and static locals.
tls_model¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
|
| Yes |
Thetls_model
attribute allows you to specify which thread-local storagemodel to use. It accepts the following strings:
global-dynamic
local-dynamic
initial-exec
local-exec
TLS models are mutually exclusive.
uninitialized¶
GNU | C++11 | C23 |
| Keyword |
| HLSL Annotation |
|
---|---|---|---|---|---|---|---|
|
| Yes |
The command-line parameter-ftrivial-auto-var-init=*
can be used toinitialize trivial automatic stack variables. By default, trivial automaticstack variables are uninitialized. This attribute is used to override thecommand-line parameter, forcing variables to remain uninitialized. It has nosemantic meaning in that using uninitialized values is undefined behavior,it rather documents the programmer’s intent.