3.9.2.1 Stack Frame Pointer Example
Figure 3-8 through Figure 3-10 show how a stack frame is created and removed for the code snippet shown in Frame Pointer Usage. This example demonstrates how a stack frame operates and is not indicative of the code generated by the compiler. Figure 3-8 shows the stack condition at the beginning of the example, before any registers are pushed to the stack. Here, W15 points to the first free stack location (TOS) and W14 points to a portion of stack memory allocated for the routine that is currently executing.
Before calling the function, “COMPUTE”, the parameters of the function (W0, W1 and W2) are PUSHed on the stack. After the “CALL COMPUTE” instruction is executed, the PC changes to the address of “COMPUTE” and the return address of the function, “TASKA”, is placed on the stack (Figure 3-9). Function “COMPUTE” then uses the “LNK #4” instruction to PUSH the calling routine’s Frame Pointer value onto the stack and the new Frame Pointer will be set to point to the current Stack Pointer. Then, the literal 4 is added to the Stack Pointer address in W15, which reserves memory for two long-word of temporary data (Figure 3-10).
Inside the function, “COMPUTE”, the FP is used to access the function parameters and temporary (local) variables. [W14 + n] will access the temporary variables used by the routine and [W14 – n] is used to access the parameters. At the end of the function, the ULNK instruction is used to copy the Frame Pointer address to the Stack Pointer and then POP the calling subroutine’s Frame Pointer back to the W14 register. The ULNK instruction returns the stack back to the state shown in Figure 3-9.
A RETURN instruction will return to the code that called the subroutine. The calling code is responsible for removing the parameters from the stack. The RETURN and POP instructions restore the stack to the state shown in Figure 3-8.
Frame Pointer Usage
TASKA: ...
PUSH W0 ; Push parameter 1
PUSH W1 ; Push parameter 2
PUSH W2 ; Push parameter 3
CALL COMPUTE ; Call COMPUTE function
POP W2 ; Pop parameter 3
POP W1 ; Pop parameter 2
POP W0 ; Pop parameter 1
...
COMPUTE:
LNK #4 ; Stack FP, allocate 4 bytes for local variables
...
ULNK ; Free allocated memory, restore original FP
RETURN ; Return to TASKA
