Next:Built-in Functions Specific to Particular Target Machines, Previous:Built-in functions for C++ allocations and deallocations, Up:Built-in Functions Provided by GCC [Contents][Index]
This section documents miscellaneous built-in functions available in GCC.
bool__builtin_has_attribute(type-or-expression,attribute) ¶The__builtin_has_attribute function evaluates to an integer constantexpression equal totrue if the symbol or type referenced bythetype-or-expression argument has been declared withtheattribute referenced by the second argument. Forantype-or-expression argument that does not reference a symbol,since attributes do not apply to expressions the built-in considerthe type of the argument. Neither argument is evaluated.Thetype-or-expression argument is subject to the samerestrictions as the argument totypeof (seeReferring to a Type withtypeof). Theattribute argument is an attribute name optionally followed bya comma-separated list of arguments enclosed in parentheses. Both formsof attribute names—with and without double leading and trailingunderscores—are recognized. SeeAttribute Syntax, for details.When no attribute arguments are specified for an attribute that expectsone or more arguments the function returnstrue iftype-or-expression has been declared with the attribute regardlessof the attribute argument values. Arguments provided for an attributethat expects some are validated and matched up to the provided number.The function returnstrue if all provided arguments match. Forexample, the first call to the function below evaluates totruebecausex is declared with thealigned attribute butthe second call evaluates tofalse becausex is declaredaligned (8) and notaligned (4).
__attribute__ ((aligned (8))) int x;_Static_assert (__builtin_has_attribute (x, aligned), "aligned");_Static_assert (!__builtin_has_attribute (x, aligned (4)), "aligned (4)");
Due to a limitation the__builtin_has_attribute function returnsfalse for themode attribute even if the type or variablereferenced by thetype-or-expression argument was declared with one.The function is also not supported with labels, and in C with enumerators.
Note that unlike the__has_attribute preprocessor operator whichis suitable for use in#if preprocessing directives__builtin_has_attribute is an intrinsic function that is notrecognized in such contexts.
type__builtin_speculation_safe_value(typeval,typefailval) ¶This built-in function can be used to help mitigate against unsafespeculative execution.type may be any integral type or anypointer type.
The second argument,failval, is optional and defaults to zeroif omitted.
GCC defines the preprocessor macro__HAVE_BUILTIN_SPECULATION_SAFE_VALUE for targets that have beenupdated to support this builtin.
The built-in function can be used where a variable appears to be used in asafe way, but the CPU, due to speculative execution may temporarily ignorethe bounds checks. Consider, for example, the following function:
int array[500];int f (unsigned untrusted_index){ if (untrusted_index < 500) return array[untrusted_index]; return 0;}If the function is called repeatedly withuntrusted_index lessthan the limit of 500, then a branch predictor will learn that theblock of code that returns a value stored inarray will beexecuted. If the function is subsequently called with anout-of-range value it will still try to execute that block of codefirst until the CPU determines that the prediction was incorrect(the CPU will unwind any incorrect operations at that point).However, depending on how the result of the function is used, it might bepossible to leave traces in the cache that can reveal what was storedat the out-of-bounds location. The built-in function can be used toprovide some protection against leaking data in this way by changingthe code to:
int array[500];int f (unsigned untrusted_index){ if (untrusted_index < 500) return array[__builtin_speculation_safe_value (untrusted_index)]; return 0;}The built-in function will either cause execution to stall until theconditional branch has been fully resolved, or it may permitspeculative execution to continue, but using 0 instead ofuntrusted_value if that exceeds the limit.
If accessing any memory location is potentially unsafe when speculativeexecution is incorrect, then the code can be rewritten as
int array[500];int f (unsigned untrusted_index){ if (untrusted_index < 500) return *__builtin_speculation_safe_value (&array[untrusted_index], NULL); return 0;}which will cause aNULL pointer to be used for the unsafe case.
int__builtin_types_compatible_p(type1,type2) ¶You can use the built-in function__builtin_types_compatible_p todetermine whether two types are the same.
This built-in function returns 1 if the unqualified versions of thetypestype1 andtype2 (which are types, not expressions) arecompatible, 0 otherwise. The result of this built-in function can beused in integer constant expressions.
This built-in function ignores top level qualifiers (e.g.,const,volatile). For example,int is equivalent toconstint.
The typeint[] andint[5] are compatible. On the otherhand,int andchar * are not compatible, even if the sizeof their types, on the particular architecture are the same. Also, theamount of pointer indirection is taken into account when determiningsimilarity. Consequently,short * is not similar toshort **. Furthermore, two types that are typedefed areconsidered compatible if their underlying types are compatible.
Anenum type is not considered to be compatible with anotherenum type even if both are compatible with the same integertype; this is what the C standard specifies.For example,enum {foo, bar} is not similar toenum {hot, dog}.
You typically use this function in code whose execution variesdepending on the arguments’ types. For example:
#define foo(x) \ ({ \ typeof (x) tmp = (x); \ if (__builtin_types_compatible_p (typeof (x), long double)) \ tmp = foo_long_double (tmp); \ else if (__builtin_types_compatible_p (typeof (x), double)) \ tmp = foo_double (tmp); \ else if (__builtin_types_compatible_p (typeof (x), float)) \ tmp = foo_float (tmp); \ else \ abort (); \ tmp; \ })Note: This construct is only available for C.
type__builtin_choose_expr(const_exp,exp1,exp2) ¶You can use the built-in function__builtin_choose_expr toevaluate code depending on the value of a constant expression. Thisbuilt-in function returnsexp1 ifconst_exp, which is aninteger constant expression, is nonzero. Otherwise it returnsexp2.
Like the ‘? :’ operator, this built-in function does not evaluate theexpression that is not chosen. For example, ifconst_exp evaluates totrue,exp2 is not evaluated even if it has side effects. On theother hand,__builtin_choose_expr differs from ‘? :’ in that thefirst operand must be a compile-time constant, and the other operands are notsubject to the ‘? :’ type constraints and promotions.
This built-in function can return an lvalue if the chosen argument is anlvalue.
Ifexp1 is returned, the return type is the same asexp1’stype. Similarly, ifexp2 is returned, its return type is the sameasexp2.
Example:
#define foo(x) \ __builtin_choose_expr ( \ __builtin_types_compatible_p (typeof (x), double), \ foo_double (x), \ __builtin_choose_expr ( \ __builtin_types_compatible_p (typeof (x), float), \ foo_float (x), \ /*The void expression results in a compile-time error \when assigning the result to something. */ \ (void)0))
Note: This construct is only available for C. Furthermore, theunused expression (exp1 orexp2 depending on the value ofconst_exp) may still generate syntax errors. This may change infuture revisions.
type__builtin_tgmath(functions,arguments) ¶The built-in function__builtin_tgmath, available only for Cand Objective-C, calls a function determined according to the rules of<tgmath.h> macros. It is intended to be used inimplementations of that header, so that expansions of macros from thatheader only expand each of their arguments once, to avoid problemswhen calls to such macros are nested inside the arguments of othercalls to such macros; in addition, it results in better diagnosticsfor invalid calls to<tgmath.h> macros than implementationsusing other GNU C language features. For example, thepowtype-generic macro might be defined as:
#define pow(a, b) __builtin_tgmath (powf, pow, powl, \ cpowf, cpow, cpowl, a, b)
The arguments to__builtin_tgmath are at least two pointers tofunctions, followed by the arguments to the type-generic macro (whichwill be passed as arguments to the selected function). All thepointers to functions must be pointers to prototyped functions, noneof which may have variable arguments, and all of which must have thesame number of parameters; the number of parameters of the firstfunction determines how many arguments to__builtin_tgmath areinterpreted as function pointers, and how many as the arguments to thecalled function.
The types of the specified functions must all be different, butrelated to each other in the same way as a set of functions that maybe selected between by a macro in<tgmath.h>. This means thatthe functions are parameterized by a floating-point typet,different for each such function. The function return types may allbe the same type, or they may bet for each function, or theymay be the real type corresponding tot for each function (ifsome of the typest are complex). Likewise, for each parameterposition, the type of the parameter in that position may always be thesame type, or may bet for each function (this case must applyfor at least one parameter position), or may be the real typecorresponding tot for each function.
The standard rules for<tgmath.h> macros are used to find acommon typeu from the types of the arguments for parameterswhose types vary between the functions; complex integer types (a GNUextension) are treated like the complex type corresponding to the realfloating type that would be chosen for the corresponding real integer type.If the function return types vary, or are all the same integer type,the function called is the one for whicht isu, and it isan error if there is no such function. If the function return typesare all the same floating-point type, the type-generic macro is takento be one of those from TS 18661 that rounds the result to a narrowertype; if there is a function for whicht isu, it iscalled, and otherwise the first function, if any, for whichthas at least the range and precision ofu is called, and it isan error if there is no such function.
int__builtin_constant_p(exp) ¶You can use the built-in function__builtin_constant_p todetermine if the expressionexp is known to be constant atcompile time and hence that GCC can perform constant-folding on expressionsinvolving that value. The argument of the function is the expression to test.The expression is not evaluated, side-effects are discarded. The functionreturns the integer 1 if the argument is known to be a compile-timeconstant and 0 if it is not known to be a compile-time constant.Any expression that has side-effects makes the function return 0.A return of 0 does not indicate that the expression isnot a constant,but merely that GCC cannot prove it is a constant within the constraintsof the active set of optimization options.
You typically use this function in an embedded application wherememory is a critical resource. If you have some complex calculation,you may want it to be folded if it involves constants, but need to calla function if it does not. For example:
#define Scale_Value(X) \ (__builtin_constant_p (X) \ ? ((X) * SCALE + OFFSET) : Scale (X))
You may use this built-in function in either a macro or an inlinefunction. However, if you use it in an inlined function and pass anargument of the function as the argument to the built-in, GCCnever returns 1 when you call the inline function with a string constantor compound literal (seeCompound Literals) and does not return 1when you pass a constant numeric value to the inline function unless youspecify the-O option.
You may also use__builtin_constant_p in initializers for staticdata. For instance, you can write
static const int table[] = { __builtin_constant_p (EXPRESSION) ? (EXPRESSION) : -1, /*… */};This is an acceptable initializer even ifEXPRESSION is not aconstant expression, including the case where__builtin_constant_p returns 1 becauseEXPRESSION can befolded to a constant butEXPRESSION contains operands that arenot otherwise permitted in a static initializer (for example,0 && foo ()). GCC must be more conservative about evaluating thebuilt-in in this case, because it has no opportunity to performoptimization.
bool__builtin_is_constant_evaluated(void) ¶The__builtin_is_constant_evaluated function is available onlyin C++. The built-in is intended to be used by implementations ofthestd::is_constant_evaluated C++ function. Programs should makeuse of the latter function rather than invoking the built-in directly.
The main use case of the built-in is to determine whether aconstexprfunction is being called in aconstexpr context. A call tothe function evaluates to a core constant expression with the valuetrue if and only if it occurs within the evaluation of an expressionor conversion that is manifestly constant-evaluated as defined in the C++standard. Manifestly constant-evaluated contexts include constant-expressions,the conditions ofconstexpr if statements, constraint-expressions, andinitializers of variables usable in constant expressions. For more detailsrefer to the latest revision of the C++ standard.
type__builtin_counted_by_ref(ptr) ¶The built-in function__builtin_counted_by_ref checks whether the arrayobject pointed by the pointerptr has another object associated with itthat represents the number of elements in the array object through thecounted_by attribute (i.e. the counted-by object). If so, returns apointer to the corresponding counted-by object.If such counted-by object does not exist, returns a null pointer.
This built-in function is only available in C for now.
The argumentptr must be a pointer to an array.Thetype of the returned value is a pointer type pointing to thecorresponding type of the counted-by object or a void pointer type in caseof a null pointer being returned.
For example:
struct foo1 { int counter; struct bar1 array[] __attribute__((counted_by (counter)));} *p;struct foo2 { int other; struct bar2 array[];} *q;the following call to the built-in
__builtin_counted_by_ref (p->array)
returns:
&p->counter with typeint *.However, the following call to the built-in
__builtin_counted_by_ref (q->array)
returns a null pointer tovoid.
void__builtin_clear_padding(ptr) ¶The built-in function__builtin_clear_padding function clearspadding bits inside of the object representation of object pointed byptr, which has to be a pointer. The value representation of theobject is not affected. The type of the object is assumed to be the typethe pointer points to. Inside of a union, the only cleared bits arebits that are padding bits for all the union members.
This built-in-function is useful if the padding bits of an object mighthave indeterminate values and the object representation needs to bebitwise compared to some other object, for example for atomic operations.
For C++,ptr argument type should be pointer to trivially-copyabletype, unless the argument is address of a variable or parameter, becauseotherwise it isn’t known if the type isn’t just a base class whose paddingbits are reused or laid out differently in a derived class.
type__builtin_bit_cast(type,arg) ¶The__builtin_bit_cast function is available onlyin C++. The built-in is intended to be used by implementations ofthestd::bit_cast C++ template function. Programs should makeuse of the latter function rather than invoking the built-in directly.
This built-in function allows reinterpreting the bits of theargargument as if it had typetype.type and the type of thearg argument need to be trivially copyable types with the same size.When manifestly constant-evaluated, it performs extra diagnostics requiredforstd::bit_cast and returns a constant expression ifargis a constant expression. For more detailsrefer to the latest revision of the C++ standard.
long__builtin_expect(longexp, longc) ¶You may use__builtin_expect to provide the compiler withbranch prediction information. In general, you should prefer touse actual profile feedback for this (-fprofile-arcs), asprogrammers are notoriously bad at predicting how their programsactually perform. However, there are applications in which thisdata is hard to collect.
The return value is the value ofexp, which should be an integralexpression. The semantics of the built-in are that it is expected thatexp ==c. For example:
if (__builtin_expect (x, 0)) foo ();
indicates that we do not expect to callfoo, sincewe expectx to be zero. Since you are limited to integralexpressions forexp, you should use constructions such as
if (__builtin_expect (ptr != NULL, 1)) foo (*ptr);
when testing pointer or floating-point values.
For the purposes of branch prediction optimizations, the probability thata__builtin_expect expression istrue is controlled by GCC’sbuiltin-expect-probability parameter, which defaults to 90%.
You can also use__builtin_expect_with_probability to explicitlyassign a probability value to individual expressions. If the built-inis used in a loop construct, the provided probability will influencethe expected number of iterations made by loop optimizations.
long__builtin_expect_with_probability ¶(longexp, longc, doubleprobability)
This function has the same semantics as__builtin_expect,but the caller provides the expected probability thatexp ==c.The last argument,probability, is a floating-point value in therange 0.0 to 1.0, inclusive. Theprobability argument must be aconstant floating-point expression.
void__builtin_trap(void) ¶This function causes the program to exit abnormally. GCC implementsthis function by using a target-dependent mechanism (such asintentionally executing an illegal instruction) or by callingabort. The mechanism used may vary from release to release soyou should not rely on any particular implementation.
void__builtin_unreachable(void) ¶If control flow reaches the point of the__builtin_unreachable,the program is undefined. It is useful in situations where thecompiler cannot deduce the unreachability of the code.
One such case is immediately following anasm statement thateither never terminates, or one that transfers control elsewhereand never returns. In this example, without the__builtin_unreachable, GCC issues a warning that controlreaches the end of a non-void function. It also generates codeto return after theasm.
int f (int c, int v){ if (c) { return v; } else { asm("jmp error_handler"); __builtin_unreachable (); }}Because theasm statement unconditionally transfers control outof the function, control never reaches the end of the functionbody. The__builtin_unreachable is in fact unreachable andcommunicates this fact to the compiler.
Another use for__builtin_unreachable is following a call afunction that never returns but that is not declared__attribute__((noreturn)), as in this example:
void function_that_never_returns (void);int g (int c){ if (c) { return 1; } else { function_that_never_returns (); __builtin_unreachable (); }}type__builtin_assoc_barrier(typeexpr) ¶This built-in inhibits re-association of the floating-point expressionexpr with expressions consuming the return value of the built-in. Theexpressionexpr itself can be reordered, and the whole expressionexpr can be reordered with operands after the barrier. The barrier isrelevant when-fassociative-math is active.
float x0 = a + b - b;float x1 = __builtin_assoc_barrier(a + b) - b;
means that, with-fassociative-math,x0 can be optimized tox0 = a butx1 cannot.
It is also relevant when-ffp-contract=fast is active;it will prevent contraction between expressions.
float x0 = a * b + c;float x1 = __builtin_assoc_barrier (a * b) + c;
means that, with-ffp-contract=fast,x0 may be optimized touse a fused multiply-add instruction butx1 cannot.
void *__builtin_assume_aligned(const void *exp, size_talign, ...) ¶This function returns its first argument, and allows the compilerto assume that the returned pointer is at leastalign bytesaligned. This built-in can have either two or three arguments,if it has three, the third argument should have integer type, andif it is nonzero means misalignment offset. For example:
void *x = __builtin_assume_aligned (arg, 16);
means that the compiler can assumex, set toarg, is at least16-byte aligned, while:
void *x = __builtin_assume_aligned (arg, 32, 8);
means that the compiler can assume forx, set toarg, that(char *) x - 8 is 32-byte aligned.
int__builtin_LINE() ¶This function is the equivalent of the preprocessor__LINE__macro and returns a constant integer expression that evaluates tothe line number of the invocation of the built-in. When used as a C++default argument for a functionF, it returns the line numberof the call toF.
const char *__builtin_FUNCTION() ¶This function is the equivalent of the__FUNCTION__ symboland returns an address constant pointing to the name of the functionfrom which the built-in was invoked, or the empty string ifthe invocation is not at function scope. When used as a C++ defaultargument for a functionF, it returns the name ofF’scaller or the empty string if the call was not made at functionscope.
const char *__builtin_FILE() ¶This function is the equivalent of the preprocessor__FILE__macro and returns an address constant pointing to the file namecontaining the invocation of the built-in, or the empty string ifthe invocation is not at function scope. When used as a C++ defaultargument for a functionF, it returns the file name of the calltoF or the empty string if the call was not made at functionscope.
For example, in the following, each call to functionfoo willprint a line similar to"file.c:123: foo: message" with the nameof the file and the line number of theprintf call, the name ofthe functionfoo, followed by the wordmessage.
const char*function (const char *func = __builtin_FUNCTION ()){ return func;}void foo (void){ printf ("%s:%i: %s: message\n", file (), line (), function ());}void__builtin___clear_cache(void *begin, void *end) ¶This function is used to flush the processor’s instruction cache forthe region of memory betweenbegin inclusive andendexclusive. Some targets require that the instruction cache beflushed, after modifying memory containing code, in order to obtaindeterministic behavior.
If the target does not require instruction cache flushes,__builtin___clear_cache has no effect. Otherwise eitherinstructions are emitted in-line to clear the instruction cache or acall to the__clear_cache function in libgcc is made.
void__builtin_prefetch(const void *addr, ...) ¶This function is used to minimize cache-miss latency by moving data intoa cache before it is accessed.You can insert calls to__builtin_prefetch into code for whichyou know addresses of data in memory that is likely to be accessed soon.If the target supports them, data prefetch instructions are generated.If the prefetch is done early enough before the access then the data willbe in the cache by the time it is accessed.
The value ofaddr is the address of the memory to prefetch.There are two optional arguments,rw andlocality.The value ofrw is a compile-time constant zero, one or two; onemeans that the prefetch is preparing for a write to the memory address,two means that the prefetch is preparing for a shared read (expected to beread by at least one other processor before it is written if written atall) and zero, the default, means that the prefetch is preparing for a read.The valuelocality must be a compile-time constant integer betweenzero and three. A value of zero means that the data has no temporallocality, so it need not be left in the cache after the access. A valueof three means that the data has a high degree of temporal locality andshould be left in all levels of cache possible. Values of one and twomean, respectively, a low or moderate degree of temporal locality. Thedefault is three.
for (i = 0; i < n; i++) { a[i] = a[i] + b[i]; __builtin_prefetch (&a[i+j], 1, 1); __builtin_prefetch (&b[i+j], 0, 1); /*… */ }Data prefetch does not generate faults ifaddr is invalid, butthe address expression itself must be valid. For example, a prefetchofp->next does not fault ifp->next is not a validaddress, but evaluation faults ifp is not a valid address.
If the target does not support data prefetch, the address expressionis evaluated if it includes side effects but no other code is generatedand GCC does not issue a warning.
int__builtin_classify_type(arg) ¶int__builtin_classify_type(type) ¶The__builtin_classify_type returns a small integer with a categoryofarg argument’s type, like void type, integer type, enumeral type,boolean type, pointer type, reference type, offset type, real type, complextype, function type, method type, record type, union type, array type,string type, bit-precise integer type, vector type, etc. When the argumentis an expression, for backwards compatibility reason the argument is promotedlike arguments passed to... in varargs function, so some classes arenever returned in certain languages. Alternatively, the argument of thebuilt-in function can be a typename, such as thetypeof specifier.
int a[2];__builtin_classify_type (a) == __builtin_classify_type (int[5]);__builtin_classify_type (a) == __builtin_classify_type (void*);__builtin_classify_type (typeof (a)) == __builtin_classify_type (int[5]);
The first comparison will never be true, asa is implicitly convertedto pointer. The last two comparisons will be true as they classifypointers in the second case and arrays in the last case.
Pmode__builtin_extend_pointer(void *x) ¶On targets where the user visible pointer size is smaller than the sizeof an actual hardware address this function returns the extended userpointer. Targets where this is true included ILP32 mode on x86_64 orAarch64. This function is mainly useful when writing inline assemblycode.
int__builtin_goacc_parlevel_id(intx) ¶Returns the openacc gang, worker or vector id depending on whetherx is0, 1 or 2.
int__builtin_goacc_parlevel_size(intx) ¶Returns the openacc gang, worker or vector size depending on whetherx is0, 1 or 2.
Next:Built-in Functions Specific to Particular Target Machines, Previous:Built-in functions for C++ allocations and deallocations, Up:Built-in Functions Provided by GCC [Contents][Index]