- Introduction
- AMD GPU Register Attributes
- Function Attributes
- interrupt
- acquire_capability (acquire_shared_capability, clang::acquire_capability, clang::acquire_shared_capability)
- assert_capability (assert_shared_capability, clang::assert_capability, clang::assert_shared_capability)
- assume_aligned (gnu::assume_aligned)
- availability
- _Noreturn
- noreturn
- carries_dependency
- enable_if
- flatten (gnu::flatten)
- format (gnu::format)
- noduplicate (clang::noduplicate)
- no_sanitize (clang::no_sanitize)
- no_sanitize_address (no_address_safety_analysis, gnu::no_address_safety_analysis, gnu::no_sanitize_address)
- no_sanitize_thread
- no_sanitize_memory
- no_split_stack (gnu::no_split_stack)
- objc_boxable
- objc_method_family
- objc_requires_super
- objc_runtime_name
- optnone (clang::optnone)
- overloadable
- release_capability (release_shared_capability, clang::release_capability, clang::release_shared_capability)
- target (gnu::target)
- try_acquire_capability (try_acquire_shared_capability, clang::try_acquire_capability, clang::try_acquire_shared_capability)
- Variable Attributes
- Type Attributes
- Statement Attributes
- Calling Conventions
- Consumed Annotation Checking
- Type Safety Checking
- OpenCL Address Spaces
- Nullability Attributes
This page lists the attributes currently supported by Clang.
Clang supports attributes for controlling register usage on AMD GPU targets. These attributes may be attached to a kernel function definition and is an optimization hint to the backend for the maximum number of registers to use. This is useful in cases where register limited occupancy is known to be an important factor for the performance for the kernel.
The semantics are as follows:
- The backend will attempt to limit the number of used registers to the specified value, but the exact number used is not guaranteed. The number used may be rounded up to satisfy the allocation requirements or ABI constraints of the subtarget. For example, on Southern Islands VGPRs may only be allocated in increments of 4, so requesting a limit of 39 VGPRs will really attempt to use up to 40. Requesting more registers than the subtarget supports will truncate to the maximum allowed. The backend may also use fewer registers than requested whenever possible.
- 0 implies the default no limit on register usage.
- Ignored on older VLIW subtargets which did not have separate scalar and vector registers, R600 through Northern Islands.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
Clang supports the
__attribute__((amdgpu_num_sgpr(<num_registers>)))
attribute on AMD
Southern Islands GPUs and later for controlling the number of scalar
registers. A typical value would be between 8 and 104 in increments of
8.
Due to common instruction constraints, an additional 2-4 SGPRs are typically required for internal use depending on features used. This value is a hint for the total number of SGPRs to use, and not the number of user SGPRs, so no special consideration needs to be given for these.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
Clang supports the
__attribute__((amdgpu_num_vgpr(<num_registers>)))
attribute on AMD
Southern Islands GPUs and later for controlling the number of vector
registers. A typical value would be between 4 and 256 in increments
of 4.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
Clang supports the GNU style __attribute__((interrupt("TYPE")))
attribute on
ARM targets. This attribute may be attached to a function definition and
instructs the backend to generate appropriate function entry/exit code so that
it can be used directly as an interrupt service routine.
The parameter passed to the interrupt attribute is optional, but if provided 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 to 8 bytes on entry. This is a general requirement of the AAPCS at public interfaces, but may not hold when an exception is taken. Doing this allows other AAPCS functions to be called.
If the CPU is M-class this is all that needs to be done since the architecture itself is designed in such a way that functions obeying the normal AAPCS ABI constraints are valid exception handlers.
If the CPU is not M-class, the prologue and epilogue are modified to save all non-banked registers that are used, so that upon return the user-mode state will not be corrupted. Note that to avoid unnecessary overhead, only general-purpose (integer) registers are saved in this way. If VFP operations are needed, that state must be saved manually.
Specifically, interrupt kinds other than "FIQ" will save all core registers except "lr" and "sp". "FIQ" interrupts will save r0-r7.
If the CPU is not M-class, the return instruction is changed to one of the canonical sequences permitted by the architecture for exception return. Where possible the function itself will make the necessary "lr" adjustments so that the "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 on the execution state of the code which generated the exception. In this case a sequence equivalent to "movs pc, lr" will be used.
acquire_capability (acquire_shared_capability, clang::acquire_capability, clang::acquire_shared_capability)
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
Marks a function as acquiring a capability.
assert_capability (assert_shared_capability, clang::assert_capability, clang::assert_shared_capability)
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
Marks a function that dynamically tests whether a capability is held, and halts the program if it is not held.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
Use __attribute__((assume_aligned(<alignment>[,<offset>]))
on a function
declaration to specify that the return value of the function (which must be a
pointer type) has the specified offset, in bytes, from an address with the
specified 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 a condition that the code already ensures is true. It does not cause the compiler to enforce the provided alignment assumption.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
The availability
attribute can be placed on declarations to describe the
lifecycle of that declaration relative to operating system versions. Consider
the function declaration for a hypothetical function f
:
void f(void) __attribute__((availability(macosx,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
The availability attribute states that f
was introduced in Mac OS X 10.4,
deprecated in Mac OS X 10.6, and obsoleted in Mac OS X 10.7. This information
is used by Clang to determine when it is safe to use f
: for example, if
Clang is instructed to compile code for Mac OS X 10.5, a call to f()
succeeds. If Clang is instructed to compile code for Mac OS X 10.6, the call
succeeds but Clang emits a warning specifying that the function is deprecated.
Finally, if Clang is instructed to compile code for Mac OS X 10.7, the call
fails because f()
is no longer available.
The availability attribute is a comma-separated list starting with the platform name and then including clauses specifying important milestones in the declaration's lifetime (in any order) along with additional information. Those clauses 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 that users should migrate away from this API.
- obsoleted=version
- The first version in which this declaration was obsoleted, meaning that it was 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 or error about use of a deprecated or obsoleted declaration. Useful to direct users to replacement APIs.
Multiple availability attributes can be placed on a declaration, which may correspond to different platforms. Only the availability attribute with the platform corresponding to the target platform will be used; any others will be ignored. If no availability attribute specifies availability for the current target platform, the availability attributes are ignored. Supported platforms are:
ios
- Apple's iOS operating system. The minimum deployment target is specified by
the
-mios-version-min=*version*
or-miphoneos-version-min=*version*
command-line arguments. macosx
- Apple's Mac OS X operating system. The minimum deployment target is
specified by the
-mmacosx-version-min=*version*
command-line argument.
A declaration can be used even when deploying back to a platform version prior
to when the declaration was introduced. When this happens, the declaration is
weakly linked,
as if the weak_import
attribute were added to the declaration. A
weakly-linked declaration may or may not be present a run-time, and a program
can determine whether the declaration is present by checking whether the
address of that declaration is non-NULL.
If there are multiple declarations of the same entity, the availability attributes must either match on a per-platform basis or later declarations must not have availability attributes for that platform. For example:
void g(void) __attribute__((availability(macosx,introduced=10.4)));
void g(void) __attribute__((availability(macosx,introduced=10.4))); // okay, matches
void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
void g(void); // okay, inherits both macosx and ios availability from above.
void g(void) __attribute__((availability(macosx,introduced=10.5))); // error: mismatch
When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
@interface A
- (id)method __attribute__((availability(macosx,introduced=10.4)));
- (id)method2 __attribute__((availability(macosx,introduced=10.4)));
@end
@interface B : A
- (id)method __attribute__((availability(macosx,introduced=10.3))); // okay: method moved into base class later
- (id)method __attribute__((availability(macosx,introduced=10.5))); // error: this method was available via the base class in 10.4
@end
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
A function declared as _Noreturn
shall not return to its caller. The
compiler will generate a diagnostic for a function declared as _Noreturn
that appears to be capable of returning to its caller.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
A function declared as [[noreturn]]
shall not return to its caller. The
compiler will generate a diagnostic for a function declared as [[noreturn]]
that appears to be capable of returning to its caller.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
The carries_dependency
attribute specifies dependency propagation into and
out of functions.
When specified on a function or Objective-C method, the carries_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 that
function. Implementations of the function and its caller may choose to preserve
dependencies instead of emitting memory ordering instructions such as fences.
Note, this attribute does not change the meaning of the program, but may result in generation of more efficient code.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
Note
Some features of this attribute are experimental. The meaning of multiple enable_if attributes on a single declaration is subject to change in a future version of clang. Also, the ABI is not standardized and the name mangling may change in future versions. To avoid that, use asm labels.
The enable_if
attribute can be placed on function declarations to control
which overload is selected based on the values of the function's arguments.
When combined with the overloadable
attribute, this feature is also
available in C.
int isdigit(int c);
int isdigit(int c) __attribute__((enable_if(c <= -1 || c > 255, "chosen when 'c' is out of range"))) __attribute__((unavailable("'c' must have the value of an unsigned char or EOF")));
void foo(char c) {
isdigit(c);
isdigit(10);
isdigit(-10); // results in a compile-time error.
}
The enable_if attribute takes two arguments, the first is an expression written in terms of the function parameters, the second is a string explaining why this overload candidate could not be selected to be displayed in diagnostics. The expression is part of the function signature for the purposes of determining whether it is a redeclaration (following the rules used when determining whether a C++ template specialization is ODR-equivalent), but is not part of the type.
The enable_if expression is evaluated as if it were the body of a bool-returning constexpr function declared with the arguments of the function it is being applied to, then called with the parameters at the call site. If the result is false or could not be determined through constant expression evaluation, then this overload will not be chosen and the provided string may be used in a diagnostic if the compile fails as a result.
Because the enable_if expression is an unevaluated context, there are no global state changes, nor the ability to pass information from the enable_if expression to the function body. For example, suppose we want calls to strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of strbuf) only if the size of strbuf can be determined:
__attribute__((always_inline))
static inline size_t strnlen(const char *s, size_t maxlen)
__attribute__((overloadable))
__attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
"chosen when the buffer size is known but 'maxlen' is not")))
{
return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
}
Multiple enable_if attributes may be applied to a single declaration. In this case, the enable_if expressions are evaluated from left to right in the following manner. First, the candidates whose enable_if expressions evaluate to false or cannot be evaluated are discarded. If the remaining candidates do not share ODR-equivalent enable_if expressions, the overload resolution is ambiguous. Otherwise, enable_if overload resolution continues with the next enable_if attribute on the candidates that have not been discarded and have remaining enable_if attributes. In this way, we pick the most specific overload out of a number of viable overloads using enable_if.
void f() __attribute__((enable_if(true, ""))); // #1
void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2
void g(int i, int j) __attribute__((enable_if(i, ""))); // #1
void g(int i, int j) __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_if expression is ODR-equivalent for both declarations, but #1 does not have another enable_if expression to continue evaluating, so the next round of evaluation has only 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 are not ODR-equivalent.
Query for this feature with __has_attribute(enable_if)
.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
The flatten
attribute causes calls within the attributed function to
be inlined unless it is impossible to do so, for example if the body of the
callee is unavailable or if the callee has the noinline
attribute.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
Clang supports the format
attribute, which indicates that the function
accepts a printf
or scanf
-like format string and corresponding
arguments or a va_list
that contains these arguments.
Please see GCC documentation about format attribute to find details about attribute syntax.
Clang implements two kinds of checks with this attribute.
Clang checks that the function with the
format
attribute is called with a format string that uses format specifiers that are allowed, and that arguments match the format string. This is the-Wformat
warning, it is on by default.Clang checks that the format string argument is a literal string. This is the
-Wformat-nonliteral
warning, it is off by default.Clang implements this mostly the same way as GCC, but there is a difference for functions that accept a
va_list
argument (for example,vprintf
). GCC does not emit-Wformat-nonliteral
warning for calls to such functions. Clang does not warn if the format string comes from a function parameter, where the function is annotated with a compatible attribute, otherwise it warns. For example:__attribute__((__format__ (__scanf__, 1, 3))) void foo(const char* s, char *buf, ...) { va_list ap; 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 is not a string literal.
Another example:
__attribute__((__format__ (__printf__, 1, 3))) void foo(const char* s, char *buf, ...) { va_list ap; va_start(ap, buf); vprintf(s, ap); // warning }
In this case Clang does not warn because the format string
s
and the corresponding arguments are annotated. If the arguments are incorrect, the caller offoo
will receive a warning.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
The noduplicate
attribute can be placed on function declarations to control
whether function calls to this function can be duplicated or not as a result of
optimizations. This is required for the implementation of functions with
certain special requirements, like the OpenCL "barrier" function, that might
need to be run concurrently by all the threads that are executing in lockstep
on the hardware. For example this attribute applied on the function
"nodupfunc" in the code below avoids that:
void nodupfunc() __attribute__((noduplicate));
// Setting it as a C++11 attribute is also valid
// void nodupfunc() [[clang::noduplicate]];
void foo();
void bar();
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 branches of the condition.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
Use the no_sanitize
attribute on a function declaration to specify
that a particular instrumentation or set of instrumentations should not be
applied to that function. The attribute takes a list of string literals,
which have the same meaning as values accepted by the -fno-sanitize=
flag. For example, __attribute__((no_sanitize("address", "thread")))
specifies that AddressSanitizer and ThreadSanitizer should not be applied
to the function.
See :ref:`Controlling Code Generation <controlling-code-generation>` for a full list of supported sanitizer flags.
no_sanitize_address (no_address_safety_analysis, gnu::no_address_safety_analysis, gnu::no_sanitize_address)
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
Use __attribute__((no_sanitize_address))
on a function declaration to
specify that address safety instrumentation (e.g. AddressSanitizer) should
not be applied to that function.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
Use __attribute__((no_sanitize_thread))
on a function declaration to
specify that checks for data races on plain (non-atomic) memory accesses should
not be inserted by ThreadSanitizer. The function is still instrumented by the
tool to avoid false positives and provide meaningful stack traces.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
Use __attribute__((no_sanitize_memory))
on a function declaration to
specify that checks for uninitialized memory should not be inserted
(e.g. by MemorySanitizer). The function may still be instrumented by the tool
to avoid false positives in other places.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
The no_split_stack
attribute disables the emission of the split stack
preamble for a particular function. It has no effect if -fsplit-stack
is not specified.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
Structs and unions marked with the objc_boxable
attribute can be used
with the Objective-C boxed expression syntax, @(...)
.
Usage: __attribute__((objc_boxable))
. This attribute
can only be placed on a declaration of a trivially-copyable struct or union:
struct __attribute__((objc_boxable)) some_struct {
int i;
};
union __attribute__((objc_boxable)) some_union {
int i;
float f;
};
typedef struct __attribute__((objc_boxable)) _some_struct some_struct;
// ...
some_struct ss;
NSValue *boxed = @(ss);
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
Many methods in Objective-C have conventional meanings determined by their selectors. It is sometimes useful to be able to mark a method as having a particular conventional meaning despite not having the right selector, or as not having the conventional meaning that its selector would suggest. For these use cases, we provide an attribute to specifically describe the "method family" that a method belongs to.
Usage: __attribute__((objc_method_family(X)))
, where X
is one of
none
, alloc
, copy
, init
, mutableCopy
, or new
. This
attribute 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 who
merely want to document its non-standard retain and release semantics, should
use the retaining behavior attributes (ns_returns_retained
,
ns_returns_not_retained
, etc).
Query for this feature with __has_attribute(objc_method_family)
.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
Some Objective-C classes allow a subclass to override a particular method in a
parent class but expect that the overriding method also calls the overridden
method in the parent class. For these cases, we provide an attribute to
designate that a method requires a "call to super
" in the overriding
method in the subclass.
Usage: __attribute__((objc_requires_super))
. This attribute can only
be 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, and
not a protocol. Currently this attribute does not enforce any placement of
where 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 it
exists.
Note that on both OS X and iOS that the Foundation framework provides a
convenience macro NS_REQUIRES_SUPER
that provides syntactic sugar for this
attribute:
- (void)foo NS_REQUIRES_SUPER;
This macro is conditionally defined depending on the compiler's support for this attribute. If the compiler does not support the attribute the macro expands to nothing.
Operationally, when a method has this annotation the compiler will warn if the implementation of an override in a subclass does not call super. For example:
warning: method possibly missing a [super AnnotMeth] call
- (void) AnnotMeth{};
^
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
By default, the Objective-C interface or protocol identifier is used in the metadata name for that object. The objc_runtime_name attribute allows annotated interfaces or protocols to use the specified string argument in the object's metadata name instead of the default name.
Usage: __attribute__((objc_runtime_name("MyLocalName")))
. This attribute
can only be placed before an @protocol or @interface declaration:
__attribute__((objc_runtime_name("MyLocalName")))
@interface Message
@end
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
The optnone
attribute suppresses essentially all optimizations
on a function or method, regardless of the optimization level applied to
the compilation unit as a whole. This is particularly useful when you
need to debug a particular function, but it is infeasible to build the
entire application without optimization. Avoiding optimization on the
specified function can improve the quality of the debugging information
for that function.
This attribute is incompatible with the always_inline
and minsize
attributes.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
Clang provides support for C++ function overloading in C. Function overloading
in C is introduced using the overloadable
attribute. For example, one
might provide several overloaded versions of a tgsin
function that invokes
the appropriate standard function computing the sine of a value with float
,
double
, or long double
precision:
#include <math.h>
float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
Given these declarations, one can call tgsin
with a float
value to
receive a float
result, with a double
to receive a double
result,
etc. Function overloading in C follows the rules of C++ function overloading
to pick the best overload given the call arguments, with a few C-specific
semantics:
- Conversion from
float
ordouble
tolong double
is ranked as a floating-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*
is considered a pointer conversion (with conversion rank) ifT
andU
are compatible types. - A conversion from type
T
to a value of typeU
is permitted ifT
andU
are compatible types. This conversion is given "conversion" rank.
The declaration of overloadable
functions is restricted to function
declarations and definitions. Most importantly, if any function with a given
name is given the overloadable
attribute, then all function declarations
and definitions with that name (and in that scope) must have the
overloadable
attribute. This rule even applies to redeclarations of
functions whose original declaration had the overloadable
attribute, e.g.,
int f(int) __attribute__((overloadable));
float f(float); // error: declaration of "f" must have the "overloadable" attribute
int g(int) __attribute__((overloadable));
int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
Functions marked overloadable
must have prototypes. Therefore, the
following code is ill-formed:
int h() __attribute__((overloadable)); // error: h does not have a prototype
However, overloadable
functions are allowed to use a ellipsis even if there
are no named parameters (as is permitted in C++). This feature is particularly
useful when combined with the unavailable
attribute:
void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
Functions declared with the overloadable
attribute have their names mangled
according to the same rules as C++ function names. For example, the three
tgsin
functions in our motivating example get the mangled names
_Z5tgsinf
, _Z5tgsind
, and _Z5tgsine
, respectively. There are two
caveats to this use of name mangling:
- Future versions of Clang may change the name mangling of functions overloaded
in C, so you should not depend on an specific mangling. To be completely
safe, we strongly urge the use of
static inline
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, it's name will be mangled in the same way as it would in C.
Query for this feature with __has_extension(attribute_overloadable)
.
release_capability (release_shared_capability, clang::release_capability, clang::release_shared_capability)
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
Marks a function as releasing a capability.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
Clang supports the GNU style __attribute__((target("OPTIONS")))
attribute.
This attribute may be attached to a function definition and instructs
the backend to use different code generation options than were passed on the
command line.
The current set of options correspond to the existing "subtarget features" for
the target with or without a "-mno-" in front corresponding to the absence
of the feature, as well as arch="CPU"
which will change the default "CPU"
for the function.
Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2", "avx", "xop" and largely correspond to the machine specific options handled by the front end.
try_acquire_capability (try_acquire_shared_capability, clang::try_acquire_capability, clang::try_acquire_shared_capability)
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
Marks a function that attempts to acquire a capability. This function may fail to actually acquire the capability; they accept a Boolean value determining whether acquiring the capability means success (true), or failing to acquire the capability means success (false).
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
The attribute applied by pragma init_seg()
controls the section into
which global initialization function pointers are emitted. It is only
available with -fms-extensions
. Typically, this function pointer is
emitted into .CRT$XCU
on Windows. The user can change the order of
initialization by using a different section name with the same
.CRT$XC
prefix and a suffix that sorts lexicographically before or
after the standard .CRT$XCU
sections. See the init_seg
documentation on MSDN for more information.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X | X |
The section
attribute allows you to specify a specific section a
global variable or function should be in after translation.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
The tls_model
attribute allows you to specify which thread-local storage
model to use. It accepts the following strings:
- global-dynamic
- local-dynamic
- initial-exec
- local-exec
TLS models are mutually exclusive.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
The __declspec(thread)
attribute declares a variable with thread local
storage. It is available under the -fms-extensions
flag for MSVC
compatibility. See the documentation for __declspec(thread) on MSDN.
In Clang, __declspec(thread)
is generally equivalent in functionality to the
GNU __thread
keyword. The variable must not have a destructor and must have
a constant initializer, if any. The attribute only applies to variables
declared with static storage duration, such as globals, class static data
members, and static locals.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
The align_value attribute can be added to the typedef of a pointer type or the declaration of a variable of pointer or reference type. It specifies that the pointer will point to, or the reference will bind to, only objects with at least the provided alignment. This alignment value must be some positive power of 2.
typedef double * aligned_double_ptr __attribute__((align_value(64))); void foo(double & x __attribute__((align_value(128)), aligned_double_ptr y) { ... }
If the pointer value does not have the specified alignment at runtime, the behavior of the program is undefined.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
This attribute can be added to an enumerator to signal to the compiler that it is intended to be used as a flag type. This will cause the compiler to assume that the range of the type includes all of the values that you can get by manipulating bits of the enumerator when issuing warnings.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
This collection of keywords is enabled under -fms-extensions
and controls
the pointer-to-member representation used on *-*-win32
targets.
The *-*-win32
targets utilize a pointer-to-member representation which
varies in size and alignment depending on the definition of the underlying
class.
However, this is problematic when a forward declaration is only available and no definition has been made yet. In such cases, Clang is forced to utilize the most general representation that is available to it.
These keywords make it possible to use a pointer-to-member representation other than the most general one regardless of whether or not the definition will ever be present in the current translation unit.
This family of keywords belong between the class-key
and class-name
:
struct __single_inheritance S;
int S::*i;
struct S {};
This keyword can be applied to class templates but only has an effect when used on full specializations:
template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
template <> struct __single_inheritance A<int, float>;
Note that choosing an inheritance model less general than strictly necessary is an error:
struct __multiple_inheritance S; // error: inheritance model does not match definition
int S::*i;
struct S {};
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
This attribute can be added to a class declaration or definition to signal to the compiler that constructors and destructors will not reference the virtual function table.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
The clang::fallthrough
attribute is used along with the
-Wimplicit-fallthrough
argument to annotate intentional fall-through
between switch labels. It can only be applied to a null statement placed at a
point of execution between any statement and the next switch label. It is
common to mark these places with a specific comment, but this attribute is
meant to replace comments with a more strict annotation, which can be checked
by the compiler. This attribute doesn't change semantics of the code and can
be used wherever an intended fall-through occurs. It is designed to mimic
control-flow statements like break;
, so it can be placed in most places
where break;
can, but only if there are no statements on the execution path
between it and the next switch label.
Here is an example:
// compile with -Wimplicit-fallthrough
switch (n) {
case 22:
case 33: // no warning: no statements between case labels
f();
case 44: // warning: unannotated fall-through
g();
[[clang::fallthrough]];
case 55: // no warning
if (x) {
h();
break;
}
else {
i();
[[clang::fallthrough]];
}
case 66: // no warning
p();
[[clang::fallthrough]]; // warning: fallthrough annotation does not
// directly precede case label
q();
case 77: // warning: unannotated fall-through
r();
}
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
The #pragma clang loop
directive allows loop optimization hints to be
specified for the subsequent loop. The directive allows vectorization,
interleaving, and unrolling to be enabled or disabled. Vector width as well
as interleave and unrolling count can be manually specified. See
language extensions
for details.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
Loop unrolling optimization hints can be specified with #pragma unroll
and
#pragma nounroll
. The pragma is placed immediately before a for, while,
do-while, or c++11 range-based for loop.
Specifying #pragma unroll
without a parameter directs the loop unroller to
attempt to fully unroll the loop if the trip count is known at compile time:
#pragma unroll
for (...) {
...
}
Specifying the optional parameter, #pragma unroll _value_
, directs the
unroller to unroll the loop _value_
times. The parameter may optionally be
enclosed in parentheses:
#pragma unroll 16
for (...) {
...
}
#pragma unroll(16)
for (...) {
...
}
Specifying #pragma nounroll
indicates that the loop should not be unrolled:
#pragma nounroll
for (...) {
...
}
#pragma unroll
and #pragma unroll _value_
have identical semantics to
#pragma clang loop unroll(full)
and
#pragma clang loop unroll_count(_value_)
respectively. #pragma nounroll
is equivalent to #pragma clang loop unroll(disable)
. See
language extensions
for further details including limitations of the unroll hints.
Clang supports several different calling conventions, depending on the target platform and architecture. The calling convention used for a function determines how parameters are passed, how results are returned to the caller, and other low-level details of calling a function.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X | X |
On 32-bit x86 targets, this attribute changes the calling convention of a
function to use ECX and EDX as register parameters and clear parameters off of
the stack on return. This convention does not support variadic calls or
unprototyped functions in C, and has no effect on x86_64 targets. This calling
convention is supported primarily for compatibility with existing code. Users
seeking register parameters should use the regparm
attribute, which does
not require callee-cleanup. See the documentation for __fastcall on MSDN.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
On non-Windows x86_64 targets, this attribute changes the calling convention of a function to match the default convention used on Windows x86_64. This attribute has no effect on Windows targets or non-x86_64 targets.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
On ARM targets, this attribute can be used to select calling conventions
similar to stdcall
on x86. Valid parameter values are "aapcs" and
"aapcs-vfp".
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
On 32-bit x86 targets, the regparm attribute causes the compiler to pass the first three integer parameters in EAX, EDX, and ECX instead of on the stack. This attribute has no effect on variadic functions, and all parameters are passed via the stack as normal.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X | X |
On 32-bit x86 targets, this attribute changes the calling convention of a function to clear parameters off of the stack on return. This convention does not support variadic calls or unprototyped functions in C, and has no effect on x86_64 targets. This calling convention is used widely by the Windows API and COM applications. See the documentation for __stdcall on MSDN.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X | X |
On 32-bit x86 targets, this attribute changes the calling convention of a
function to use ECX for the first parameter (typically the implicit this
parameter of C++ methods) and clear parameters off of the stack on return. This
convention does not support variadic calls or unprototyped functions in C, and
has no effect on x86_64 targets. See the documentation for __thiscall on
MSDN.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
On 32-bit x86 and x86_64 targets, this attribute changes the calling convention 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 integer
parameters are passed in memory, and callee clears the stack. On x86_64
targets, the callee does not clear the stack, and integer parameters are
passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling
convention.
On both 32-bit x86 and x86_64 targets, vector and floating point arguments are passed in XMM0-XMM5. Homogenous vector aggregates of up to four elements are passed 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 that cannot be passed in registers for any reason is passed by reference, which allows the caller to align the parameter memory.
See the documentation for __vectorcall on MSDN for more details.
Clang supports additional attributes for checking basic resource management properties, specifically for unique objects that have a single owning reference. The following attributes are currently supported, although the implementation for these annotations is currently in development and are subject to change.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
Use __attribute__((callable_when(...)))
to indicate what states a method
may be called in. Valid states are unconsumed, consumed, or unknown. Each
argument to this attribute must be a quoted string. E.g.:
__attribute__((callable_when("unconsumed", "unknown")))
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
Each class
that uses any of the typestate annotations must first be marked
using the consumable
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
, or unconsumed
.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
This attribute specifies expectations about function parameters. Calls to an function with annotated parameters will issue a warning if the corresponding argument isn't in the expected state. The attribute is also used to set the initial state of the parameter when analyzing the function's body.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
The return_typestate
attribute can be applied to functions or parameters.
When applied to a function the attribute specifies the state of the returned
value. The function's body is checked to ensure that it always returns a value
in the specified state. On the caller side, values returned by the annotated
function are initialized to the given state.
When applied to a function parameter it modifies the state of an argument after a call to the function returns. The function's body is checked to ensure that the parameter is in the expected state before returning.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
Annotate methods that transition an object into a new state with
__attribute__((set_typestate(new_state)))
. The new state must be
unconsumed, consumed, or unknown.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
Use __attribute__((test_typestate(tested_state)))
to indicate that a method
returns true if the object is in the specified state..
Clang supports additional attributes to enable checking type safety properties that can't be enforced by the C type system. Use cases include:
- MPI library implementations, where these attributes enable checking that
the 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()
. For
example:
#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)
#endif
int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
ATTR_MPI_PWT(1,3);
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
Use __attribute__((argument_with_type_tag(arg_kind, arg_idx,
type_tag_idx)))
on a function declaration to specify that the function
accepts a type tag that determines the type of some other argument.
arg_kind
is an identifier that should be used when annotating all
applicable type tags.
This attribute is primarily useful for checking arguments of variadic functions
(pointer_with_type_tag
can be used in most non-variadic cases).
For example:
int fcntl(int fd, int cmd, ...)
__attribute__(( argument_with_type_tag(fcntl,3,2) ));
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
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 that
determines the pointee type of some other pointer argument.
For example:
int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
__attribute__(( pointer_with_type_tag(mpi,1,3) ));
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
Clang supports annotating type tags of two forms.
Type tag that is an expression containing a reference to some declared identifier. Use
__attribute__((type_tag_for_datatype(kind, type)))
on a declaration with that identifier:extern struct mpi_datatype mpi_datatype_int __attribute__(( type_tag_for_datatype(mpi,int) )); #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
Type tag that is an integral literal. Introduce a
static const
variable with a corresponding initializer value and attach__attribute__((type_tag_for_datatype(kind, type)))
on that declaration, for example:#define MPI_INT ((MPI_Datatype) 42) static const MPI_Datatype mpi_datatype_int __attribute__(( type_tag_for_datatype(mpi,int) )) = 42
The attribute also accepts an optional third argument that determines how the expression is compared to the type tag. There are two supported flags:
layout_compatible
will cause types to be compared according to layout-compatibility rules (C++11 [class.mem] p 17, 18). This is implemented to support annotating types likeMPI_DOUBLE_INT
.For example:
/* In mpi.h */ struct internal_mpi_double_int { double d; int i; }; extern struct mpi_datatype mpi_datatype_double_int __attribute__(( type_tag_for_datatype(mpi, struct internal_mpi_double_int, layout_compatible) )); #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int) /* In user code */ struct my_pair { double a; int b; }; struct my_pair *buffer; MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning struct my_int_pair { int a; int b; } struct my_int_pair *buffer2; MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning: actual buffer element // type 'struct my_int_pair' // doesn't match specified MPI_Datatype
must_be_null
specifies that the expression should be a null pointer constant, for example:/* In mpi.h */ extern struct mpi_datatype mpi_datatype_null __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) )); #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null) /* In user code */ MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL // was specified but buffer // is not a null pointer
The address space qualifier may be used to specify the region of memory that is used to allocate the object. OpenCL supports the following address spaces: __generic(generic), __global(global), __local(local), __private(private), __constant(constant).
__constant int c = ...; __generic int* foo(global int* g) { __local int* l; private int p; ... return l; }
More details can be found in the OpenCL C language Spec v2.0, Section 6.5.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
The constant address space attribute signals that an object is located in a constant (non-modifiable) memory region. It is available to all work items. Any type can be annotated with the constant address space attribute. Objects with the constant address space qualifier can be declared in any scope and must have an initializer.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
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 and function parameters in non-kernel functions can have the generic address space type attribute. It is intended to be a placeholder for any other address space except for '__constant' in OpenCL code which can be used with multiple address spaces.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
The global address space attribute specifies that an object is allocated in global memory, which is accessible by all work items. The content stored in this memory area persists between kernel executions. Pointer types to the global address space are allowed as function parameters or local variables. Starting with OpenCL v2.0, the global address space can be used with global (program scope) variables and static local variable as well.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
The local address space specifies that an object is allocated in the local (work group) memory area, which is accessible to all work items in the same work group. The content stored in this memory region is not accessible after the kernel execution ends. In a kernel function scope, any variable can be in the local address space. In other scopes, only pointer types to the local address space are allowed. Local address space variables cannot have an initializer.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
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 its content is destroyed after work item execution ends. Local variables can be declared in the private address space. Function arguments are always in the private address space. Kernel function arguments of a pointer or an array type cannot point to the private address space.
Whether a particular pointer may be "null" is an important concern when working with pointers in the C family of languages. The various nullability attributes indicate whether a particular pointer can be null or not, which makes APIs more expressive and can help static analysis tools identify bugs involving null pointers. Clang supports several kinds of nullability attributes: the nonnull
and returns_nonnull
attributes indicate which function or method parameters and result types can never be null, while nullability type qualifiers indicate which pointer types can be null (_Nullable
) or cannot be null (_Nonnull
).
The nullability (type) qualifiers express whether a value of a given pointer type can be null (the _Nullable
qualifier), doesn't have a defined meaning for null (the _Nonnull
qualifier), or for which the purpose of null is unclear (the _Null_unspecified
qualifier). Because nullability qualifiers are expressed within the type system, they are more general than the nonnull
and returns_nonnull
attributes, allowing one to express (for example) a nullable pointer to an array of nonnull pointers. Nullability qualifiers are written to the right of the pointer to which they apply. For example:
// No meaningful result when 'ptr' is null (here, it happens to be undefined behavior). int fetch(int * _Nonnull ptr) { return *ptr; } // 'ptr' may be null. int fetch_or_zero(int * _Nullable ptr) { return ptr ? *ptr : 0; } // A nullable pointer to non-null pointers to const characters. const char *join_strings(const char * _Nonnull * _Nullable strings, unsigned n);
In Objective-C, there is an alternate spelling for the nullability qualifiers that can be used in Objective-C methods and properties using context-sensitive, non-underscored keywords. For example:
@interface NSView : NSResponder - (nullable NSView *)ancestorSharedWithView:(nonnull NSView *)aView; @property (assign, nullable) NSView *superview; @property (readonly, nonnull) NSArray *subviews; @end
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
The nonnull
attribute indicates that some function parameters must not be null, and can be used in several different ways. It's original usage (from GCC) is as a function (or Objective-C method) attribute that specifies which parameters of the function are nonnull in a comma-separated list. For example:
extern void * my_memcpy (void *dest, const void *src, size_t len) __attribute__((nonnull (1, 2)));
Here, the nonnull
attribute indicates that parameters 1 and 2
cannot have a null value. Omitting the parenthesized list of parameter indices means that all parameters of pointer type cannot be null:
extern void * my_memcpy (void *dest, const void *src, size_t len) __attribute__((nonnull));
Clang also allows the nonnull
attribute to be placed directly on a function (or Objective-C method) parameter, eliminating the need to specify the parameter index ahead of type. For example:
extern void * my_memcpy (void *dest __attribute__((nonnull)), const void *src __attribute__((nonnull)), size_t len);
Note that the nonnull
attribute indicates that passing null to a non-null parameter is undefined behavior, which the optimizer may take advantage of to, e.g., remove null checks. The _Nonnull
type qualifier indicates that a pointer cannot be null in a more general manner (because it is part of the type system) and does not imply undefined behavior, making it more widely applicable.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X | X |
The returns_nonnull
attribute indicates that a particular function (or Objective-C method) always returns a non-null pointer. For example, a particular system malloc
might be defined to terminate a process when memory is not available rather than returning a null pointer:
extern void * malloc (size_t size) __attribute__((returns_nonnull));
The returns_nonnull
attribute implies that returning a null pointer is undefined behavior, which the optimizer may take advantage of. The _Nonnull
type qualifier indicates that a pointer cannot be null in a more general manner (because it is part of the type system) and does not imply undefined behavior, making it more widely applicable
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
The _Nonnull
nullability qualifier indicates that null is not a meaningful value for a value of the _Nonnull
pointer type. For example, given a declaration such as:
int fetch(int * _Nonnull ptr);
a caller of fetch
should not provide a null value, and the compiler will produce a warning if it sees a literal null value passed to fetch
. Note that, unlike the declaration attribute nonnull
, the presence of _Nonnull
does not imply that passing null is undefined behavior: fetch
is free to consider null undefined behavior or (perhaps for backward-compatibility reasons) defensively handle null.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
The _Null_unspecified
nullability qualifier indicates that neither the _Nonnull
nor _Nullable
qualifiers make sense for a particular pointer type. It is used primarily to indicate that the role of null with specific pointers in a nullability-annotated header is unclear, e.g., due to overly-complex implementations or historical factors with a long-lived API.
GNU | C++11 | __declspec | Keyword | Pragma |
---|---|---|---|---|
X |
The _Nullable
nullability qualifier indicates that a value of the _Nullable
pointer type can be null. For example, given:
int fetch_or_zero(int * _Nullable ptr);
a caller of fetch_or_zero
can provide null.