Is it possible to force tail call optimization on GCC/Clang?

大城市里の小女人 提交于 2019-12-10 12:56:56

问题


I'm trying to write a program in functional style with C as much as possible. I know fine compilers like GCC/Clang do tail call optimization silently, but it's not guaranteed. Is there any option to force tail call optimization on the compilers? (Of course when only it's called at the end of itself)


回答1:


Clang is not doing any optimisations at all. There is an LLVM pass tailcallelim which may do what you want (but it is not guaranteed). You can run it separately with opt.




回答2:


I don't think it really enforces it, but you can use -foptimize-sibling-calls when using gcc. It's automatically enabled if you use -O2, -O3 or -Os.




回答3:


In reality a lot of compilers for C already handle this for you. As eq mentioned you might as well let the compiler handle most of these things rather than trying to create optimizations that won't work elsewhere. Often times you'll find even if you set optimization flags that there is really no performance difference.




回答4:


A meta answer:

There are some lessons it's useful to take over into C from functional languages: use small functions, use functions which don't mutate either globals or input arguments, don't be frightened of function pointers. But there's a limit to what you can reasonably do here, and relying on tail-call elimination ('tail-call optimization' isn't really the right term) is probably beyond what's useful. You can't force the compiler to use this strategy, and even if you could, the resulting C would be extremely unidiomatic, and hard to read for others, including your future self.

Use languages to their strengths. C is good for some things, so use it for those, in good C style. If you want different strengths, or if you want to use a functional style (excellent decision!), use a functional language.




回答5:


If it really is a tail call then a while loop or a goto wont look that much different from a recursive call. Just update all variables instead of passing them as parameters. AFAIK this is the only cross-platform way in C to control stack usage at all optimization levels. It can actually be more readable too since you have one function with initialization followed by the loop, which is pretty idiomatic. The tail recursive version requires two functions, one for initialization and one for the recursive part.



来源:https://stackoverflow.com/questions/4785066/is-it-possible-to-force-tail-call-optimization-on-gcc-clang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!