I have been writing a compiler and have discussed this situation with a colleague.
In the most general case, suppose you have your arguments on the stack (once argument registers are exhausted).
If tail recursion:
- simply overwrite the stack arguments, set stack pointer to your frame pointer, and make the call
Otherwise:
- if the callee has less arguments than the caller, simply overwrite the first K, and do the same
Question:
- if the callee has more arguments, what do you do?
Here’s a picture representation:
<code>A's frame
....
arg2 of B
arg1 of B
_______
B's frame
</code>
<code>A's frame
....
arg2 of B
arg1 of B
_______
B's frame
</code>
A's frame
....
arg2 of B
arg1 of B
_______
B's frame
and now B
wants to call C
and do TCO, but C
has 3 arguments, what do you do?
One solution is to make a minimal frame just responsible for handling this control and placing the arguments; however, that seems like it defeats the purpose of TCO.
My colleague says that it is impossible to perform TCO in this case.