13 ms·
Rust will likely not support tail call optimization
- pcwalton 14y agoNote that we do sibling call optimization per LLVM, and you can use trampolines like Clojure does. Sibling call optimization, most notably, includes all self-calls. This means that calls to the currently executing function in tail position will be tail call optimized, if there are no destructors in scope. The biggest problem here is ABIs: you have to use Pascal calling conventions instead of C calling conventions. It's also difficult when you have destructors: there are not many tail call positions when destructors are in scope.
- tsewlliw 14y agoI'd vote getting to use RAII is a better win than TCO. And really its by definition not a tail call when you have to run destructors after a "tail" call, and tricky/annoying to express that destructors should be run prior to a tail call.
- edwintorok 14y agoHow about the other two calling conventions that support tail call optimization? (cc 10 and cc11) Do those have the same performance penalty as fastcall + tailcallopt?
- masklinn 14y agoWouldn't it be possible to have some sort of macro able to "manually" convert calls in a recursive style into loops? Something along the lines of Clojure's `loop/recur` but less tricky (and maybe with a single "word")?
- pcwalton 14y agoYes, I think so.
- ufo 14y agoSelf recursion is only a particular case and you can often represent it with loops or folding patterns as you are imagining. However, the really cool use for tail call elimination is when you are calling other functions since you can't rewrite the code without breaking encapsulation. Out of the top of my head, one important example of this would be continuation passing style (you need TCO to turn the continuations into real "gotos")
- gngeal 14y agoThat would be useless. I believe the point of proper tail calls is that the set of functions that may be called from a particular call site is not closed. The callee may be a parameter of the caller, for example in combinator-style libraries. You can't convert that in advance.
- protomyth 14y agoIt seems like part of decision was reached because of limitations in LLVM[1]. This makes me a bit uneasy, but I guess it has to follow C to meet its goals. 1) "LLVM does support tail call optimization, but it requires using a different calling convention than C and slowing down all function calls" from https://mail.mozilla.org/pipermail/rust-dev/2013-April/003556.html https://mail.mozilla.org/pipermail/rust-dev/2013-April/00355... and http://llvm.org/docs/CodeGenerator.html#tail-call-optimization http://llvm.org/docs/CodeGenerator.html#tail-call-optimizati...
- deleted 14y ago[deleted]
- cwzwarich 14y agoThey could also add their own calling convention to LLVM to support what they want like GHC and HiPE have done.
- saidajigumi 14y agoNo they can't, at least not without compromising on several points laid out in TFA. Mainly these two: - Tail calls also "play badly" with assumptions in C tools, including platform ABIs and dynamic linking. - Tail calls require a calling convention that is a performance hit relative to the C convention. See other posts in this discussion for examples of the impacts of some alternate calling convention choices.
- anonymous 14y agoThen how can GCC and clang do TCE in C programs?
- aidenn0 14y ago1) They can't do it all the time 2) Some of the times they can do it, they do it when they control both the caller and the callee. In that case you can violate the ABI to your heart's content. 3) I don't really see TCE as an issue in Rust, since they seem to be going the RAII route and, as others have commented, RAII and TCE don't play well together (for the same reason a call at the end of a dynamic binding can't be TCE'd in common-lisp).
- dewitt 14y agoClojure also doesn't support TCO, and from what I can tell the explicit loop/recur is sufficient, which also has the advantage that it is very clear (i.e., the compiler will tell you) when TCO is not being invoked. With implicit TCO you might think you're getting the benefit, only to have a stack blow up unexpectedly at runtime with an edge-case input.
- pcwalton 14y agoEspecially with destructors. Whenever you have a destructor in the frame, you're not in tail-call position. This means that tail-call positions in Rust are going to be few anyway.
- cpeterso 14y agoDoes this mean Rust's `be` keyword can be retired? :)
- pcwalton 14y agoYes.
- qznc 14y agoThat calls for an interesting optimization: Using escape+liveness analysis you could probably call some of those destructors earlier.
- kragen 14y agoThe problem is that TCO in the sense we're talking about isn't really an "optimization". It's a language feature that removes the need for explicit looping constructs by allowing you to write them as higher-order functions instead. This only works if the guy writing the higher-order function can prove that the compiler will successfully "optimize away" the tail call, or if he doesn't care whether the program dies with a stack overflow. If the success of TCO is dependent on which conservative approximation the compiler is using for escape and liveness analysis, then people who care about their programs continuing to run will demand explicit looping constructs anyway. There are three separate inventions in Scheme that work this way. Closures give you objects without an object construct, tail-call optimization gives you loops without looping constructs, and call/cc gives you threads, exceptions, and backtracking without thread, exception, or backtracking constructs. (I mention Scheme because all three of these were, as far as I can tell, introduced in Scheme, and only later adopted by other functional languages like ML, although to be fair, TCO at least falls out naturally from combinator-graph reduction.) In a sense, Scheme is sort of like a functional assembly language: there are lots of object systems, looping constructs, threads, and exception systems in Scheme, and they aren't compatible with each other. It's sort of like the situation with linked lists in C, where every library has its own linked-list type. It's exactly the opposite of assembly language in another way, though. By making object instantiation and population implicit, both the compiler and the maintenance programmer have to do extra work to figure out what's an object and what's not, and what the object's fields are. The same is true of loops, threads, and exceptions. In assembly, instead, you have the problem of things being too explicit, thus losing the signal in the noise. That's my take, anyway. I haven't spent that much time programming in either Scheme or assembly, although I did write an almost-Scheme compiler targeting assembly called Ur-Scheme.
- pekk 14y agoI'm puzzled: if Rust and Clojure won't support TCO and they are both cool, why is there such bitter complaining every time it comes up that Python won't support TCO?
- kyllo 14y agoBecause Rust and Clojure have have better excuses, maybe? Rust is supposed to be as fast as C/C++ and TCO will slow it down. Clojure can't have TCO because the Java Virtual Machine doesn't support it. So they have a workaround (trampolines). Python doesn't support TCO because... it screws up stack traces?
- Rickasaurus 14y agoWe'll just have to put Rust up against MLton and see if tail calls really are so expensive.
- larsberg 14y agoIf I understand it correctly, the Rust issue is that tail calls are expensive in the context of LLVM and the calling convention that they are using. MLton (like Manticore, which I work on) uses a different code generation backend and calling convention entirely. And neither of us worry about "destructors" or, in general, things that happen at every return point. Though, interestingly, in the context of a CPS-converted program, destructors would just be the next continuation called on the way to calling the procedure previously "returned to." Under our (Manticore) calling convention, we would just jump to each of those continuations and wouldn't have to grow stack (though in our case, it's keeping around heap frames, as we're not stack-based), and would have the same next allocation and instruction-level behavior as a tail call. That said, if you think tail calls are hard to debug, CPS-converted programs would destroy most people's will to live. No stack backtraces, except in debug modes, with 5-10x performance penalties.
- Rickasaurus 14y agoI never thought tail calls were hard to debug, but can you can keep text offsets to the original tokens through the CPS transform? Usually with typed languages that's enough information to figure out what went wrong or at least what to log. Also, I'm not sure why the entire library needs the same calling convention when it's such bad form to expose all of your functions anyway.
- btipling 14y agoWhat is tail call optimization? How does it usually work? There's an implementation example on the Wikipedia page to answer this question a little bit: http://en.wikipedia.org/wiki/Tail_call http://en.wikipedia.org/wiki/Tail_call
- arb99 14y agoalso http://stackoverflow.com/questions/310974/what-is-tail-call-optimization http://stackoverflow.com/questions/310974/what-is-tail-call-... gives a decent overview
- ericbb 14y agoAnd, of course, "Debunking the 'Expensive Procedure Call' Myth, or, Procedure Call Implementations Considered Harmful, or, Lambda: The Ultimate GOTO" by Guy Steele. Available here: http://library.readscheme.org/page1.html http://library.readscheme.org/page1.html
- Rickasaurus 14y agoScrew it, we might as well use Go Seriously though, why not just use a rec keyword and then disallow any of the things that don't play nicely when you're in the recursive function? If you really wanted to be cool you could put those things right into the type system.
- coldtea 14y agoThey don't want to be cool. They want to create a usable, pragmatic and fast language.
- Rickasaurus 14y agoSounds mostly like a pile of empty words to me. Usable and pragmatic are purely contextual. Is rust faster than Haskell?
- coldtea 14y ago>Sounds mostly like a pile of empty words to me. All words are empty until we put meaning on them. Go and read what they are trying to achieve and how, and then they won't be empty anymore. >Usable and pragmatic are purely contextual. Is rust faster than Haskell? It's not highly optimized yet, as it's in pre-alpha stage. But it's goal is to be faster than Haskell, and close to C/C++/ADA speed. Usable and pragmatic means that it should work for their goals, which are very real and tangible themselves: to use it as a compiled language to create a fast, parallel and secure web browser engine. They don't want to pile on academic concept and programming features or compiler tricks just to be "cool", "interesting", or "cutting edge". They don't even care if they would be "nice to have". They care about: what helps their goals, and what can be implemented without overcomplicating things. If Rust cannot become a language in which it's able to write a fast (faster than the currently available), parallel (more parallel than the currently available) and safe (safer than the currently available) browser engine, then it would have failed on its targets.
- Rickasaurus 14y ago
- mike_ivanov 14y agoA TCO-support discussion on Y combinator. OH IRONY.
- zxcdw 14y agoElaborate for the ignorant.
- kd0amg 14y agoThe Y combinator is a way to express recursion in lambda calculus. Tail call optimization (turning certain function calls into GOTOs) is the traditional way to keep from overflowing the control stack in languages based on lambda calculus.
- qznc 14y agoThe Y Combinator is something important in the theory of functional programming. It takes one function as argument and applies it to itself ad infinitum. Together with lazy evaluation this is how you can implement recursion in a language which does not natively support it, namely (lazy) lambda calculus. http://en.wikipedia.org/wiki/Fixed-point_combinator#Y_combinator http://en.wikipedia.org/wiki/Fixed-point_combinator#Y_combin... Actually, TCO and Y are not really related with each other apart from the fact that you usually learn about them in the same course about functional programming.
- kragen 14y agoIf you write your loops with the Y-combinator, you need tail-call elimination to keep them from overflowing the stack when they run for enough iterations, because the way your function f goes on to the next iteration of itself is by calling the (Y f) that was passed as its first argument.
- qznc 14y agoYou can write a lambda calculus interpreter which does beta-reduction. In this case, there is no stack which could overflow. Just a lambda expression, which is reduced to another expression.
- beagle3 14y agoPlease, for the sake of $DIETY, stop calling it "Tail Call Optimization". It is not an optimization, and the wrong term causes lots of useless discussions and misunderstanding. Call it "Tail Call Elimination", because that's what it is. With finite memory (that is, in the real world), a program that relies on tail recursion will blow up if TCE is not implemented even though it can run forever with TCE. Thus, it changes actual program results (rather than just runtime speed or amount of memory required), and cannot be considered just an "optimization", since it is functionally required. And to future-language designers: Please, for the sake of $DIETY2, make the syntax for guaranteed-eliminated-tail-call different than a regular call: It's really a bad idea that a function such as: def f(x): ... return 0+f(x-1) cannot in general be TCEd (adding 0 to a floating point imporper denormal will make it proper), whereas def f(x): ... return f(x-1) can. I suggest "chain y" instead of "return y" so that the compiler can verify that a TCE can indeed happen.
- gngeal 14y ago"Please, for the sake of $DIETY" If you worship food, that is. But you're right, people calling proper tail calls "an optimization" should be shot. Those who survive the subsequent generation scavenging should be shot again. :-)
- kibwen 14y agoAs a historical note, this was also the original plan for Rust, where the presence of the `be` keyword rather than the `return` keyword would indicate tail-calling.
- millstone 14y agocannot be considered just an "optimization", since it is functionally required Here is a C program: #include <stdio.h> int main(void) { while (1) malloc(64); } With clang, when compiled with -O0, this consumes all the memory on my system. When compiled with -O2, it runs forever in constant memory, because clang has optimized out the call to malloc. If I replace the call with, say, 'malloc((size_t)(-1) >> 1)', it even changes the output of the program. Here is another example: int factorial(long long x) { return x * factorial(x-1); } With gcc, when compiled with -O2, the factorial function can correctly compute the factorial of a very large number. When compiled with -O0, it cannot. I would call both of these optimizations, even though someone may rely on either for correctness. So I don't think tail calls are unique in this respect. make the syntax for guaranteed-eliminated-tail-call different than a regular call Agreed.
- jevinskie 14y agoHere is some information about TCE in LLVM from the lead developer: http://nondot.org/sabre/LLVMNotes/GuaranteedEfficientTailCalls.txt http://nondot.org/sabre/LLVMNotes/GuaranteedEfficientTailCal...
- pratb 14y agoThe problem seems to be that you can't do tail calls with the C calling convention. For example, let's say a 0-argument function tail calls a 1-argument one: the 1-argument function expects an argument on the stack, so the 0-argument function must push one. However, when the 1-argument function returns, the argument will still be on the stack, because with the C calling convention the caller removes arguments from the stack. But the caller called a 0-argument function, so he won't remove any argument, and thus the stack is now misaligned due to the argument left over there, which will crash the program soon. However, just switching to the Pascal/stdcall convention, where the callee removes arguments from the stack should just work; it might be slightly slower, but on all modern architectures (i.e. those that aren't x86-32) parameters are going to be passed in registers anyway for must functions, so it shouldn't matter. The problem of that is that non-varags functions cannot be called with a varargs prototype; this is an issue with K&R C that allows calling undeclared functions, but isn't an issue with Rust. So, I'm not quite sure why Rust doesn't just switch calling conventions and support tail calls.
- asbut 14y agoThe problem seems to be that you can't do tail calls with the C calling convention. For example, let's say a 0-argument function tail calls a 1-argument one: the 1-argument function expects an argument on the stack, so the 0-argument function must push one. However, when the 1-argument function returns, the argument will still be on the stack, because with the C calling convention the caller removes arguments from the stack. But the caller called a 0-argument function, so he won't remove any argument, and thus the stack is now misaligned due to the argument left over there, which will crash the program soon. However, just switching to the Pascal/stdcall convention, where the callee removes arguments from the stack should just work; it might be slightly slower, but on all modern architectures (i.e. those that aren't x86-32) parameters are going to be passed in registers anyway for must functions, so it shouldn't matter. The problem of that is that non-varags functions cannot be called with a varargs prototype; this is an issue with K&R C that allows calling undeclared functions, but isn't an issue with Rust. So, I'm not quite sure why Rust doesn't just switch calling conventions and support tail calls.
- deleted 14y ago[deleted]