Held Wednesday, March 14, 2001
Today we continue our investigation of stack frames by considering some particular examples.
factorial, so we'll try that first.
function factorial(n: integer): integer; var tmp1: integer; begin if (n = 0) then factorial := 1 else begin tmp := factorial(n-1); factorial := n * tmp; end end;
+--------------+ <- FP | old FP | +--------------+ | return value | +--------------+ | ret. address | +--------------+ | n | +--------------+ | tmp | +--------------+ | extra | +--------------+ <- SP
factoriallook like? In a generic language with four bytes per word
BEGIN_FACTORIAL: # Do anything appropriate for the beginning of a procedure call ... # if (n = 0) START_FACTORIAL_CODE: COMPARE MEM[SP-12], CONSTANT JUMP IF EQUAL BASE_CASE JUMP RECURSIVE_CASE # factorial := 1 BASE_CASE: STORE INTO MEM[FP+4] FROM CONSTANT JUMP END_FACTORIAL # tmp := factorial(n-1) RECURSIVE_CASE: # Compute n-1 SUBTRACT CONSTANT FROM MEM[SP-12], STORE IN MEM[SP-8] # Call factorial ... # Copy the value back STORE INTO MEM[SP-8] FROM MEM[SP+4] # factorial := n * tmp MULTIPLY MEM[SP-12] BY MEM[SP-8], STORE IN MEM[FP+4] JUMP END_FACTORIAL # Clean up END_FACTORIAL: ...
# Do anything appropriate for the beginning of a procedure call ADD CONSTANT to SP
END_FACTORIAL: SUBTRACT CONSTANT from SP
STORE INTO MEM[SP+12] FROM MEM[SP-4]
STORE INTO MEM[SP] FROM FP
SET FP to SP
STORE INTO MEM[SP+8], RETURN_HERE
JUMP BEGIN_FACTORIAL RETURN_HERE:
STORE INTO FP FROM MEM[FP]
Monday, 22 January 2001
Disclaimer: I usually create these pages on the fly. This means that they are rarely proofread and may contain bad grammar and incorrect details. It also means that I may update them regularly (see the history for more details). Feel free to contact me with any suggestions for changes.
This page was generated by Siteweaver on Mon Apr 30 10:52:03 2001.
This page may be found at
You may validate this page's HTML.
The source was last modified Mon Jan 22 10:39:11 2001.