[英]Why noreturn/__builtin_unreachable prevents tail call optimization
I have come to fact that all major compilers will not do tail call optimization if a called function does not return (ie marked as _Noreturn
/ [[noreturn]]
or there is a __builtin_unreachable()
after the call). 我已经发现,如果被调用的函数没有返回(即标记为_Noreturn
/ [[noreturn]]
或者调用后有__builtin_unreachable()
,所有主要编译器都不会进行尾调用优化。 Is this an intended behavior and not a missed optimization, and if so why? 这是一个预期的行为,而不是错过优化,如果是这样,为什么?
Example 1: 例1:
#ifndef __cplusplus
#define NORETURN _Noreturn
#else
#define NORETURN [[noreturn]]
#endif
void canret(void);
NORETURN void noret(void);
void foo(void) { canret(); }
void bar(void) { noret(); }
C: https://godbolt.org/z/pJfEe- C++: https://godbolt.org/z/-4c78K C: https : //godbolt.org/z/pJfEe- C ++: https : //godbolt.org/z/-4c78K
Example 2: 例2:
#ifdef _MSC_VER
#define UNREACHABLE __assume(0)
#else
#define UNREACHABLE __builtin_unreachable()
#endif
void f(void);
void foo(void) { f(); }
void bar(void) { f(); UNREACHABLE; }
It's intentional, though perhaps controversial since it can seriously harm stack usage properties; 这是有意的,虽然可能引起争议,因为它会严重损害堆栈使用属性; for this reason I've even resorted to tricking the compiler to think a function that can't return can. 出于这个原因,我甚至采用欺骗编译器来思考一个无法返回的函数。 The reasoning is that many noreturn functions are abort
-like (or even call abort
), and that it's likely someone running a debugger wants to be able to see where the call happened from -- information which would be lost by a tail call. 其理由是,许多不返回的功能是abort
样(或者甚至称之为abort
),并且很可能有人运行调试希望能够看到通话的事情发生了-这将通过尾调用信息丢失。
Citations: 引文:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.