I have trouble understanding GCC built-in functions, and feel very confused.
What is the difference between a library function and an built-in function?
There are roughly two kinds of built-ins: the ones which correspond to standard library functions (malloc
, printf
and strcpy
are all treated as built-ins by default), and the ones which don't have a counterpart in the standard library - think of __builtin_expect
, __builtin_prefetch
, etc.
The first kind of built-ins are there to enable the compiler to emit optimised code in place of the corresponding calls. Knowing the internal semantics of each of the calls from the standard library, the compiler can decide to either emit a call to the function that resides in the library, or emit a custom-generated piece of code in its place, so that the original semantics are preserved and the code runs better.
The second kind of built-ins (also called "intrinsics") enable tricks and optimisations which are hardly achievable with a static piece of code that resides in a library. They may translate to giving hints to the CPU (__builtin_prefetch
, __builtin_expect
), or enhancing the C language with better compile-time introspection (__builtin_constant_p
, __builtin_types_compatible_p
), or providing a simpler, platform-independent interface to some architecture-specific instructions (__builtin_ffs
, __builtin_popcount
).