Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 329
eonil Avatar asked Jan 24 '11 17:01

eonil


People also ask

Does GCC do tail call optimization?

Some C compilers, such as gcc and clang, can perform tail call optimization (TCO).

Does C++ support tail call optimization?

Tail call optimisation isn't in the C++ standard. Apparently, some compilers, including MS Visual Studio and GCC, do provide tail call optimisation under certain circumstances (when optimisations are enabled, obviously).

What languages support tail call optimization?

This kind of function call is called a tail call, and languages like Haskell, Scala, and Scheme can avoid keeping around unnecessary stack frames in such calls. This is called tail call optimization (TCO) or tail call elimitation.

What is tail optimization?

Tail call optimization is the specific use of tail calls in a function or subroutine that eliminate the need for additional stack frames. Tail call optimization can be part of efficient programming and the use of the values that subroutines return to a program to achieve more agile results or use fewer resources.


1 Answers

Clang 13 "musttail" attribute to force tail call optimization in tail recursive functions even if optimizations are disabled.

https://clang.llvm.org/docs/AttributeReference.html#musttail

usage:

int f(int x) {
  ...
  __attribute__((musttail)) return f(x-1);
}
like image 159
Bobisnotyouruncle Avatar answered Dec 02 '22 05:12

Bobisnotyouruncle