使用 clang 内置函数与标准函数的好处
Benefits of using clang builtins vs standard functions
Clang 和 GCC 定义了一堆内置函数我将在这里使用余数的例子:
__builtin_sqrt(x)
但是,标准 C99 在 math.h
中定义了以下内容
sqrt(x)
clang 为一个已经存在的方法定义一个内置函数有什么意义?我原以为常见的数学函数(例如 sqrt)会被后端优化,因此实际上不需要内置函数。由于显而易见的原因,此内置函数不如标准 c 可移植。
来自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.
库函数在编译器之外,因此它无法像内置函数那样对它们进行推理。例如,编译器可能会在 constant folding 中使用内置函数,例如。将 __builtin_sqrt(1)
替换为 1
而它通常不能对库 sqrt(1)
.
的调用做同样的事情
使用内置函数不影响可移植性,因为它们实现了标准 C,所以它们具有相同的语义。
Clang 和 GCC 定义了一堆内置函数我将在这里使用余数的例子:
__builtin_sqrt(x)
但是,标准 C99 在 math.h
sqrt(x)
clang 为一个已经存在的方法定义一个内置函数有什么意义?我原以为常见的数学函数(例如 sqrt)会被后端优化,因此实际上不需要内置函数。由于显而易见的原因,此内置函数不如标准 c 可移植。
来自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.
库函数在编译器之外,因此它无法像内置函数那样对它们进行推理。例如,编译器可能会在 constant folding 中使用内置函数,例如。将 __builtin_sqrt(1)
替换为 1
而它通常不能对库 sqrt(1)
.
使用内置函数不影响可移植性,因为它们实现了标准 C,所以它们具有相同的语义。