Sub topic 2
Calling Sequence and Frame Layout
Assume you know C-style functions, recursion, and the stack as a last-in, first-out data structure. This chapter focuses on how a function call creates, uses, and removes a stack frame.
What happens during a call
A calling sequence is the agreed procedure used by a caller and a callee. The caller is the function making the call. The callee is the function being called. The agreement is called a calling convention.
A typical call follows these steps:
- The caller evaluates arguments and places them in registers or memory.
- The caller saves any values that must survive the call.
- The call instruction records the return address, which identifies the next instruction in the caller.
- The callee creates its frame in a prologue.
- The callee executes its body.
- The callee places the result in an agreed register or memory location.
- The callee restores saved registers and removes its frame in an epilogue.
- Control returns to the recorded return address.
The exact order depends on the machine and application binary interface, or ABI. The logical responsibilities remain similar.
#include <stdio.h>
int add_one(int x) {
int result = x + 1;
return result;
}
int main(void) {
int answer = add_one(7);
printf("%d\n", answer);
return 0;
}When main calls add_one, the caller supplies 7. The callee receives it as x, creates space for result, returns 8, and gives control back to main.
A stack frame layout
A stack frame is the memory area belonging to one active function call. It commonly contains the following items:
| Area | Purpose |
|---|---|
| Arguments | Values passed to the callee, when not kept in registers |
| Return address | Location where execution resumes |
| Saved frame pointer | Previous frame's reference point |
| Saved registers | Caller or callee register values that must be preserved |
| Local variables | Storage for variables declared inside the function |
| Temporary values | Intermediate results needed during evaluation |
Many systems use a stack pointer, SP, to identify the current stack top and a frame pointer, FP, to provide stable offsets within the frame. The stack may grow toward lower addresses, so diagrams must state the convention.
Prologue and epilogue
The prologue saves the old frame pointer, establishes a new one, and reserves space for locals. The epilogue reverses these actions. A compiler may omit FP and address locals relative to SP when debugging and variable-sized allocations do not require a stable frame reference.
In recursive calls, each call gets a separate frame. Therefore, each call has its own parameters, return address, and local variables. Returning from one call removes only that call's frame.
Exercise
If function f calls g and g calls h, how many return addresses are active before h returns?
Show answer
Three: one for returning from h to g, one for returning from g to f, and one for returning from f to its caller.