Tell HN: We are trying to get tail calls into the WebAssembly standard
625 pointsTo effectively support some forms of Functional Programming support for tail-calls has been proposed as an extension to the WebAssembly standard.
This proposal has reached Phase3 of the standardization process years ago, but has since stalled.
Phase3 is known as "the implementation phase" and the prerequisite for advancing the proposal to Phase4 is to have support in two different browser engines. V8/Chrome support has been available for a long time, so another engine is required.
To unblock this situation we have contributed full support for WebAssembly Tail Calls to JavaScript/WebKit/Safari. The PR is available here:
https://github.com/WebKit/WebKit/pull/2065
An in-depth article about the challenges of implementing this feature is also available. This is intended both as documentation for our contribution, but also as a general explainer about how tails calls actually work, with a particular focus on stack space management.
https://leaningtech.com/fantastic-tail-calls-and-how-to-impl...
Comments (290) 26 threads
Show all comments
Showing thread 1 of 26
I'm a huge functional programming evangelist, but high-level stuff like this does not belong in a low level language bytecode like WASM.
Wasm should only care about two things: Security and Performance.
With the standard blowing up like crazy we'll get neither. Worse, we'll cemenent the current duopoly of browser engines, because we'll make it (again) so complex that no-one can create an alternative.
We shouldn't have GC, Exceptions or Tail calls in WASM, as long as the compiler can provide them.
What we should have is multi memory support and memory read permissions, because without them WASM lacks basic security primitives.[1]
Reference types maybe. But I've yet to see a convincing argument as to why they are absolutely necessary.
Everything else (as long as it can be done by the compiler) is just bloat.
1. https://www.usenix.org/conference/usenixsecurity20/presentat...
For posterity my original comment was:
“From what I understand, tail calls can always (?) be lowered to while loops[1], which are expressible in WASM.
1. https://en.wikipedia.org/wiki/Tail_call#Relation_to_the_whil...
If you have an A -> B, or A -> [indirect] call, that is not the case.
g(): a = 1+1; b = 2+a; print(b); return f()
into code that does not allocate stack space and just reuses the frame allocated for g()?
Continue this thread — 2 replies
It's an ugly piece of code, but because of parsers, there is a huge amount of know how on it.
Continue this thread — 2 replies
The best they can do are trampolines, which come with a high performance cost.
The issue is that to avoid stack blow-up you need the engine to recycle stack frames. You might argue that this could happen implicitly in the VM, with all the calls in tail position being automatically converted to tail-calls. The problem with this is that in WebAssembly (and JavaScript) the call stack is observable via the .stack property of thrown exceptions.
Since an implicit conversion would be observable engines cannot simply optimize the problem away, and that is the reason why new opcodes (return_call/return_call_indirect) are actually required at the WASM level.
For the specific case of direct calls (return_call opcode) the compiler could solve the problem by inlining, with some luck. But for the case of return_call_indirect there is no other possible solution.
I've long suspected exceptions making it into WASM being it's million dollar mistake, and this further confirms it.
Even if it wasn't observable though, I think guaranteed tail-call elimination via either a new opcode or having it be a required property of regular calls in the spec (we already missed that ship, of course) is important. Without it, proper compilation and execution of some languages on wasm would depend on an otherwise invisible property of the engine - that is, tail call elimination isn't just an optimization, it's a critical aspect of language semantics that needs to be guaranteed to be relied on.
Continue this thread — 14 replies
EDIT: Also as another commenter mentioned, this is a property exposed by the VM engine to the host environment, not something directly observable from within WebAssembly itself.
Possibly a stupid question as I haven't given this much thought, but I thought tail call elimination could be used to convert recursive calls in tail position into loops. Could a compiler not do this (like Scala does, for example)?
Turning this into a loop is only possible when the function calls itself, not when it calls another function, and not (naively) when two functions call each other in the tail position.
Continue this thread — 39 replies
(1) Thank you for implementing this in JSC!! I hope they take it, it makes it into Safari, and the tail-call proposal advances.
(2) I don't think you are exactly right about the call stack being observable via thrown exceptions. There's no formal spec for the v3 exceptions proposal yet, but in the documents and tests, there's nothing that would change in WebAssembly core to make the call stack observable. (There's no ".stack property" that would be added to Wasm itself.) It's true that the proposal amends the JS API (but only the JS API) to describe a traceStack=true option; from Wasm's perspective I understand that's just an ordinary exception that happens to include an externref value (just like any other value) to which Wasm attaches no special significance. The Web-based engines can attach an informative stack trace if they want, but there's no requirement preventing frames from having been optimized out. The non-Web engines won't have to think about this.
(3) I think the real reason that a Wasm engine can't implicitly make tail calls proper is that the spec tests forbid it, basically because they didn't want the implementation base to fragment by having some engines perform an optimization that changes the space complexity of a program, which some programs would have started to depend on. (The spec tests say: "Implementations are required to have every call consume some abstract resource towards exhausting some abstract finite limit, such that infinitely recursive test cases reliably trap in finite time. This is because otherwise applications could come to depend on it on those implementations and be incompatible with implementations that don't do it (or don't do it under the same circumstances.)")
But the issue is much weaker than "call stack is observable" -- it's more like "infinite recursion must trap eventually, but it can be nondeterministic when."
More discussion here: https://github.com/WebAssembly/spec/issues/150
If an implementation really wanted to, they could get around this by incrementing a "function call counter" that traps at, say, 2^64, rendering it effectively moot.
I feel like these kinds of situations are where being practical might make more sense than being mathematically precise. Something like "each function call must consume at least N bits of memory" or something concrete like that. Or heck, "implementations may not perform tail-call optimization" or even "implementations must be able to reconstruct the full logical call stack at any point".
This is going to be a problem for any long-running recursive program. Why would we mandate this?
(Specifically, to prevent one implementation getting an optimization for them that leads people to rely on it, making code that blows up in practical use on other implementations, despite both being nominally correct implementations of the same spec.)
The nightmare scenario is that you spend months writing a program that works great in browsers A and B, but when you roll it out to prod it immediately fails in browser C, which doesn't perform TCO.
You only want to write code that depends on TCO if you can get a guarantee that TCO will be performed. This is the motivation for the clang:musttail attribute in C/C++ (I implemented musttail in Clang): https://clang.llvm.org/docs/AttributeReference.html#musttail
To me, I'd see a distinction between code that requires a specific optimization and code that could benefit from that optimization. If the standard forbids an optimization to avoid the former, it also removes the latter.
Continue this thread — 3 replies
No.
For other optimization, the difference is the speed of execution. For tail call optimization, the difference can be normal execution and stack overflow.
Continue this thread — 2 replies
Continue this thread — 1 more reply
It's a nice detail for you to highlight, but surely that exists in the test spec specifically because the opcode spec doesn't mandate tail-call handling. If the latter did (a la Scheme), then the test spec would be updated to no longer have this note...?
Continue this thread — 1 reply
Same thing applies, I think, to any other language compiled to WASM. C/C++ compilers regularly inline huge amounts of the code when optimizations are turned on, as well as do tail-call optimization. I haven't tried, but I would assume that they do that for WASM just as they do for x86 or ARM or whatever other build target I choose. As long as my users are ok with this (and they presumably are, otherwise they wouldn't turn optimizations), what's the problem, exactly?
You might enjoy participating in an interoperable standardization process sometime.
Continue this thread — 2 replies
Stack overflows are stopping you, if you implement Scheme calls as Wasm calls.
In Scheme, tail call elimination is not merely an optional "optimization", so the compiler can't opt to not do it when it's inconvenient.
Its just a jmp? Does the wasm VM not have a jmp instruction?!?
Those are the list of control instructions. WASM seems to be a bit of a misnomer as it is not an assembly language in the more conventional sense. It is a structured language and provides a limited goto in the form of branches (in the section I linked to) which are constrained to a particular scope.
If you compile your whole program so it fits within a single function, then yes you can use this to do universal tail call elimination. Otherwise you are restricted to doing TCE only on auto-recursive functions and maybe mutually recursive functions if you have a single entry point (of the set of functions) and decide to optimize by moving all of them into one function.
Otherwise, function calls are performed using one of the two call instructions which (presently) implement a behavior more like conventional call stack/stack frames. This proposal would add a second pair of call instructions that a compiler can emit which the WASM runtime would then optimize (by not generating new stack frames).
Continue this thread — 2 replies
Continue this thread — 6 more replies
Continue this thread — 15 more replies