Next: , Previous: , Up: A Virtual Machine for Guile   [Contents][Index]


9.3.3 Stack Layout

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:

   /------------------\ <- top of stack
   | Local N-1        | <- sp
   | ...              |
   | Local 1          |
   | Local 0          | <- fp = SCM_FRAME_LOCALS_ADDRESS (fp)
   +==================+
   | Return address   |
   | Dynamic link     | <- fp - 2 = SCM_FRAME_LOWER_ADDRESS (fp)
   +==================+
   |                  | <- fp - 3 = SCM_FRAME_PREVIOUS_SP (fp)

In the above drawing, the stack grows upward. 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 fp in effect before this program was applied.

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 ip and 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.


Next: , Previous: , Up: A Virtual Machine for Guile   [Contents][Index]