Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of using clang builtins vs standard functions

Clang and GCC define a bunch of builtin functions I'll use the example of remainder here:

__builtin_sqrt(x)

However, standard C99 defines the following in math.h

sqrt(x)

What's the point of clang defining a builtin for a method that already exists? I'd have thought common math functions such as sqrt would be optimised by the backend so doesn't really need a builtin. This builtins are less portable than standard c, for obvious reasons.

like image 298
H Bellamy Avatar asked Mar 08 '17 09:03

H Bellamy


1 Answers

From gcc manual:

GCC normally generates special code to handle certain built-in functions more efficiently; for instance, calls to alloca may become single instructions which adjust the stack directly, and calls to memcpy may become inline copy loops. The resulting code is often both smaller and faster, but since the function calls no longer appear as such, you cannot set a breakpoint on those calls, nor can you change the behavior of the functions by linking with a different library. In addition, when a function is recognized as a built-in function, GCC may use information about that function to warn about problems with calls to that function, or to generate more efficient code, even if the resulting code still contains calls to that function. For example, warnings are given with -Wformat for bad calls to printf when printf is built in and strlen is known not to modify global memory.

Library functions are external to the compiler, so it cannot reason about them to the same extent as builtins. For example, compiler might use builtins in constant folding, eg. replace __builtin_sqrt(1) with 1 whereas it generally cannot do the same with call to library sqrt(1).

Using builtins does not affect portability, because they implement the Standard C, so they have the same semantics.

like image 51
el.pescado - нет войне Avatar answered Oct 02 '22 12:10

el.pescado - нет войне