The stack of Guile’s virtual machine is composed of frames. Each frame corresponds to the application of one compiled procedure, and contains storage space for arguments, local variables, and some bookkeeping information (such as what to do after the frame is finished).
While the compiler is free to do whatever it wants to, as long as the semantics of a computation are preserved, in practice every time you call a function, a new frame is created. (The notable exception of course is the tail call case, see Tail Calls.)
The structure of the top stack frame is as follows:
| ... | +==================+ <- fp + 2 = SCM_FRAME_PREVIOUS_SP (fp) | Dynamic link | +------------------+ | Return address | +==================+ <- fp | Local 0 | +------------------+ | Local 1 | +------------------+ | ... | +------------------+ | Local N-1 | \------------------/ <- sp
In the above drawing, the stack grows downward. Usually the procedure being applied is in local 0, followed by the arguments from local 1. After that are enough slots to store the various lexically-bound and temporary values that are needed in the function’s application.
The return address is the
ip that was in effect before this
program was applied. When we return from this activation frame, we will
jump back to this
ip. Likewise, the dynamic link is the
offset of the
fp that was in effect before this program was
applied, relative to the current
To prepare for a non-tail application, Guile’s VM will emit code that
shuffles the function to apply and its arguments into appropriate stack
slots, with two free slots below them. The call then initializes those
free slots with the current
fp, and updates
ip to point to the function entry, and
fp to point to the
new call frame.
In this way, the dynamic link links the current frame to the previous frame. Computing a stack trace involves traversing these frames.
As an implementation detail, we actually store the dynamic link as an offset and not an absolute value because the stack can move at runtime as it expands or during partial continuation calls. If it were an absolute value, we would have to walk the frames, relocating frame pointers.