The Stack Frame: Saving What a Call Would Destroy

A function that calls another has a problem: the call overwrites ra, and the registers run out. The cure is a small piece of memory that each function borrows and gives back. This page watches it grow and shrink.

You Will Be Able To

  • Say what the stack pointer holds, and in which direction the stack grows.
  • Lay out the frame of a function: what it must save, and at which offset from sp.
  • Follow a nested call, and say what each word of the stack holds at each moment.
Lesson
S2.19
Time
30 min
Runs on
Your browser
Check
6 questions

In S2.3, main called add3 and all went well. Now let add3 call a third function. Its jal writes a new return address into ra, over the old one. Unless the way back to main was put somewhere safe first, the program can never get home.

Before You Start

You need calls and returns from S2.3: jal writes ra, jalr returns through it, and saved registers must come back unchanged.

You need loads and stores with an offset, such as sw ra, 12(sp), from S2.1.

Five questions this page answers
Question
1What does sp hold, and which way does the stack grow?
2What must a function save before it calls another function?
3What must a function do before it uses a saved register?
4Why does the frame of a function vanish when the function returns?
5What happens when a function calls another and does not save ra?

The Idea: Borrow a Piece of Memory, and Give It Back

A function needs a safe place for a few values. They are its return address, and the old values of the saved registers it wants to use. Registers cannot be that place. The next call may take them.

Memory can. One region of memory is set aside for this, and it is called the stack. One register always says where its used part ends. That register is x2, and its name is sp, for stack pointer.

The stack grows toward lower addresses. A function takes room by subtracting from sp, and gives it back by adding the same number. The room it takes is its stack frame, or frame for short.

Frames pile up like plates. When main calls a function, a frame goes on top. When that function calls another, a second frame goes on top of the first. Each return takes the top frame away. The last one put on is the first one taken off.

Not every function needs a frame. A function that calls nothing, and uses no saved register, has nothing to protect. It is called a leaf function.

New Words

New words on this page
WordMeaning
StackA region of memory in which functions keep values while they run. It grows toward lower addresses.
Stack pointerThe register x2, named sp. It holds the lowest address of the stack that is in use.
Stack frameThe part of the stack that one function has taken. Frame for short.
Stack pushPutting a value on the stack: make room below sp, and store the value there.
Stack popTaking a value off the stack: load it, and give the room back.
Function entry codeThe first instructions of a function: they make the frame and save registers into it.
Function exit codeThe last instructions of a function: they restore the registers and give the frame back.
Leaf functionA function that calls no other function. It often needs no frame.
Nested callA call made by a function that was itself called.
Stack overflowThe stack growing past the memory set aside for it, into other data.

One Picture: A Frame Comes and Goes

The Frame of twice_inc, and the Stack Pointer Around ItStep through the picture. The middle column is memory, with higher addresses at the top. Follow sp down and up again.
  • Processor
  • Memory
  • Control / FSM
The Frame of twice_inc, and the Stack Pointer Around ItStep through the picture. The middle column is memory, with higher addresses at the top. Follow sp down and up again. component main calls twice_inc; its spis 8001_0000 component twice_inc calls inc twice, so itneeds a frame component inc calls nothing, andneeds no frame component Word at8000_fffc the saved ra: 8, theway back to main component Word at8000_fff8 the saved s0 of main component Word at8000_fff4 the saved s1 of main component Word at8000_fff0 not used: it keeps theframe at 16 bytes component sp 8001_0000, then8000_fff0, then8001_0000 again jal: ra = 8sp points heresaves rasaves s0saves s1jal: ra is overwritten
  1. component maincalls twice_inc; its sp is 8001_0000
    • jal: ra = 8 → twice_inc
  2. component sp8001_0000, then 8000_fff0, then 8001_0000 again
    • sp points here → Word at 8000_fff0
  3. component twice_inccalls inc twice, so it needs a frame
    • saves ra → Word at 8000_fffc
    • saves s0 → Word at 8000_fff8
    • saves s1 → Word at 8000_fff4
    • jal: ra is overwritten → inc
  4. component Word at 8000_fff0not used: it keeps the frame at 16 bytes
  5. component Word at 8000_fff4the saved s1 of main
  6. component Word at 8000_fff8the saved s0 of main
  7. component Word at 8000_fffcthe saved ra: 8, the way back to main
  8. component inccalls nothing, and needs no frame
  1. Before the call

    The stack is empty. The stack pointer holds 8001_0000, one past the last byte of the SRAM.

  2. The call from main

    The jal in main writes 8 into ra. That is the only copy of the way back to main.

  3. A frame is made

    The function subtracts 16 from sp. The 16 bytes from 8000_fff0 up now belong to it.

  4. Three words are saved

    It stores ra, s0 and s1 into its frame. Now it may call, and may use s0 and s1.

  5. The nested calls

    Each call of inc overwrites ra. That does no harm: the old value is in memory. The function inc makes no frame.

  6. The frame is given back

    The function loads ra, s0 and s1 from the frame and adds 16 to sp. Then it returns to address 8.

Read the diagram as text
  • main: calls twice_inc; its sp is 8001_0000
  • twice_inc: calls inc twice, so it needs a frame
  • inc: calls nothing, and needs no frame
  • Word at 8000_fffc: the saved ra: 8, the way back to main
  • Word at 8000_fff8: the saved s0 of main
  • Word at 8000_fff4: the saved s1 of main
  • Word at 8000_fff0: not used: it keeps the frame at 16 bytes
  • sp: 8001_0000, then 8000_fff0, then 8001_0000 again
  • main → twice_inc: jal: ra = 8
  • sp → Word at 8000_fff0: sp points here
  • twice_inc → Word at 8000_fffc: saves ra
  • twice_inc → Word at 8000_fff8: saves s0
  • twice_inc → Word at 8000_fff4: saves s1
  • twice_inc → inc: jal: ra is overwritten

A frame lives exactly as long as its function runs. After the return, sp is where it was.

The Smallest Example, Worked by Hand

Three functions in C. The function main calls twice_inc, and twice_inc calls inc two times.

The C program. No C compiler is used on this page: the assembly below is compiled by hand.
int inc(int num) {
  return num + 1;
}

int twice_inc(int num) {
  int first = inc(num);
  return first + inc(num);
}

int main(void) {
  return twice_inc(5);
}

Look at twice_inc as a compiler would. It makes calls, so ra will be overwritten. It needs num again after the first call, and first after the second. Those two values must survive a call, so they go into s0 and s1. But s0 and s1 belong to main until they are saved.

So the frame needs three words: for ra, s0 and s1. Three words are 12 bytes. The convention keeps sp at a multiple of 16, so the frame is 16 bytes.

The frame of twice_inc
Offset from spAddressHolds
128000_fffcthe ra of twice_inc: the way back to main
88000_fff8the s0 of main
48000_fff4the s1 of main
08000_fff0nothing: it fills the frame up to 16 bytes

Before the call, sp is 8001_0000. Inside twice_inc it is 8000_fff0, which is 16 less.

twice_inc, compiled by hand
AddressAssemblyWhat it does
0caddi sp, sp, -16makes the frame
10 to 18sw ra, 12(sp); sw s0, 8(sp); sw s1, 4(sp)saves three registers
1caddi s0, a0, 0keeps num in s0
20jal ra, 0x48calls inc; a0 already holds num
24addi s1, a0, 0keeps first in s1
28addi a0, s0, 0the argument num again
2cjal ra, 0x48calls inc
30add a0, s1, a0first plus the second result
34 to 3clw ra, 12(sp); lw s0, 8(sp); lw s1, 4(sp)restores the three registers
40addi sp, sp, 16gives the frame back
44jalr zero, 0(ra)returns to main

Addresses are in hex. The function inc is two instructions at 48: addi a0, a0, 1 and a return.

The Rules

  1. Rule 1: sp holds the lowest address of the stack in use.

    The stack grows toward lower addresses.

  2. Rule 2: A function makes its frame by subtracting from sp, and gives it back by adding the same number.

    The number is a multiple of 16.

  3. Rule 3: A function that makes a call saves ra in its frame first.

    It restores ra before its own return.

  4. Rule 4: A function that uses a saved register saves the old value in its frame first.

    It restores the value before it returns.

  5. Rule 5: A function writes only into its own frame: from sp up to the sp it was given.

    Memory below sp belongs to nobody. The next call will overwrite it.

  6. Rule 6: A leaf function that uses only temporary and argument registers needs no frame.

    It never touches sp.

Sources for These Rules

Every fact about the stack and the calling convention on this page is stated as commonly described. That covers the direction of growth, what sp points at, the multiple of 16, and who saves ra and the saved registers. The document that defines the convention is not in the reference library. So none of these facts is checked against it.

The plan of this track points to two textbooks for this material. They are Patterson and Hennessy, section 2.8, and Harris and Harris, section 6.3. Those places are not checked either.

The start of the stack at 8001_0000 is a choice of this page. It is one past the last byte of the 64 KiB of SRAM of ap_soc. The values 1111_1111 and 2222_2222 stand for whatever main keeps in s0 and s1.

Now Run It

The lab at the end of this page runs the three functions on the small model. Before the start, sp holds 8001_0000, and s0 and s1 hold two values of main that are easy to spot.

Printed by the lab on Icarus. The instruction-level model of this track printed the same rows.
00000000 | addi a0, zero, 5 | a0 = 00000005
00000004 | jal ra, 0xc | ra = 00000008, next is 0000000c
0000000c | addi sp, sp, -16 | sp = 8000fff0
00000010 | sw ra, 12(sp) | mem[8000fffc] = 00000008
00000014 | sw s0, 8(sp) | mem[8000fff8] = 11111111
00000018 | sw s1, 4(sp) | mem[8000fff4] = 22222222
0000001c | addi s0, a0, 0 | s0 = 00000005
00000020 | jal ra, 0x48 | ra = 00000024, next is 00000048
00000048 | addi a0, a0, 1 | a0 = 00000006
0000004c | jalr zero, 0(ra) | next is 00000024
00000024 | addi s1, a0, 0 | s1 = 00000006
00000028 | addi a0, s0, 0 | a0 = 00000005
0000002c | jal ra, 0x48 | ra = 00000030, next is 00000048
00000048 | addi a0, a0, 1 | a0 = 00000006
0000004c | jalr zero, 0(ra) | next is 00000030
00000030 | add a0, s1, a0 | a0 = 0000000c
00000034 | lw ra, 12(sp) | ra = 00000008 from mem[8000fffc]
00000038 | lw s0, 8(sp) | s0 = 11111111 from mem[8000fff8]
0000003c | lw s1, 4(sp) | s1 = 22222222 from mem[8000fff4]
00000040 | addi sp, sp, 16 | sp = 80010000
00000044 | jalr zero, 0(ra) | next is 00000008
00000008 | ebreak | stop
a0=12 s0=11111111 s1=22222222 sp=80010000

Rule 2 at work: rows 3 and 20. The stack pointer goes down by 16 to 8000_fff0, and comes back to 8001_0000.

Rules 3 and 4 at work: rows 4 to 6. The three stores land at 8000_fffc, 8000_fff8 and 8000_fff4, as in the table of the frame.

Now watch ra. Row 8 overwrites it with 24, and row 13 with 30. Neither is the way back to main.

Rule 3 again: row 17. The load brings 8 back from 8000_fffc. Row 21 then returns to address 8, in main.

Rule 6 at work: the four rows of inc, at 48 and 4c. They never mention sp.

Read the last row. The result is 12, and s0, s1 and sp hold what they held before the call. For main, nothing has happened but the result.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
A stack: last in, first outA fixed place in memory for each functionA function can call itself, and memory is used only while a function runs. The depth must be planned.
One subtraction for the whole frameA separate push for each valueThe offsets from sp stay fixed inside the function. Some bytes of the frame may go unused.
The callee saves the saved registersThe caller saves everything it needsA register is saved once per function, not once per call. A function that needs none saves none.
The stack grows downwardUpwardProgram data can grow up from the other end of the same memory. Nothing stops the two from meeting.
sp kept at a multiple of 16Any multiple of 4Larger values can sit at addresses that are multiples of their size. Small frames waste a few bytes.

The Trap: The Function That Could Never Get Home

A programmer writes a small function by hand, called add_two. It calls inc two times in a row. It uses no saved register, so it seems to need no frame at all.

The function in C. Its hand-written assembly is two calls and a return, and nothing else.
int add_two(int num) {
  return inc(inc(num));
}
The same model, stopped after 12 instructions. The function add_two is at address c, and inc at 18.
00000000 | addi a0, zero, 5 | a0 = 00000005
00000004 | jal ra, 0xc | ra = 00000008, next is 0000000c
0000000c | jal ra, 0x18 | ra = 00000010, next is 00000018
00000018 | addi a0, a0, 1 | a0 = 00000006
0000001c | jalr zero, 0(ra) | next is 00000010
00000010 | jal ra, 0x18 | ra = 00000014, next is 00000018
00000018 | addi a0, a0, 1 | a0 = 00000007
0000001c | jalr zero, 0(ra) | next is 00000014
00000014 | jalr zero, 0(ra) | next is 00000014
00000014 | jalr zero, 0(ra) | next is 00000014
00000014 | jalr zero, 0(ra) | next is 00000014
00000014 | jalr zero, 0(ra) | next is 00000014
still running after 12 instructions
a0=7 ra=00000014

Read row 2. The call from main writes 8 into ra. That is the way back to main.

Read rows 3 and 6. Each call of inc writes ra again: first 10, then 14. The 8 is gone.

Read row 9. The return of add_two goes to the address in ra, which is 14. That is the return instruction itself. So it returns to itself, for ever. The answer 7 sits in a0, and main never sees it.

This is rule 3. A function that makes even one call must save ra. Only a leaf function may skip the frame.

At Scale

This page1 frame of 16 bytes
A real programdozens of frames; kibibytes of stack

This section looks ahead. On a real chip the stack is one of the first things set up, and one of the first things to go wrong.

  1. Who sets sp

    Nothing sets sp at reset. The start-up code of the chip must do it before the first call. Module S6 covers that code.

  2. Stack overflow

    Nothing checks the stack. Too many nested calls move sp down into other data. Memory protection can catch that: S3.25 sets a trap below a stack.

  3. Local variables

    Arrays and other variables that do not fit in registers live in the frame as well. Frames then grow well past 16 bytes.

  4. One stack for each task

    An operating system gives every task a stack of its own. A switch of task is, in essence, a switch of sp. Common practice.

Try It

Run the lab. Mark the rows where sp changes, and the rows that write or read the frame.

Remove the three rows that restore ra, s0 and s1. Predict the last row, and where the program ends up.

Change inc so that it uses s0 as scratch, without saving it. Which value in the last row is now wrong, and whose fault is it?

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: 00000000 | addi a0, zero, 5 | a0 = 00000005 00000004 | jal ra, 0xc | ra = 00000008, next is 0000000c 0000000c | addi sp, sp, -16 | sp = 8000fff0 00000010 | sw ra, 12(sp) | mem[8000fffc] = 00000008 00000014 | sw s0, 8(sp) | mem[8000fff8] = 11111111 00000018 | sw s1, 4(sp) | mem[8000fff4] = 22222222 0000001c | addi s0, a0, 0 | s0 = 00000005 00000020 | jal ra, 0x48 | ra = 00000024, next is 00000048 00000048 | addi a0, a0, 1 | a0 = 00000006 0000004c | jalr zero, 0(ra) | next is 00000024 00000024 | addi s1, a0, 0 | s1 = 00000006 00000028 | addi a0, s0, 0 | a0 = 00000005 0000002c | jal ra, 0x48 | ra = 00000030, next is 00000048 00000048 | addi a0, a0, 1 | a0 = 00000006 0000004c | jalr zero, 0(ra) | next is 00000030 00000030 | add a0, s1, a0 | a0 = 0000000c 00000034 | lw ra, 12(sp) | ra = 00000008 from mem[8000fffc] 00000038 | lw s0, 8(sp) | s0 = 11111111 from mem[8000fff8] 0000003c | lw s1, 4(sp) | s1 = 22222222 from mem[8000fff4] 00000040 | addi sp, sp, 16 | sp = 80010000 00000044 | jalr zero, 0(ra) | next is 00000008 00000008 | ebreak | stop a0=12 s0=11111111 s1=22222222 sp=80010000

Check Yourself

Predict the outputA function is called from address 0. It makes a frame of 16 bytes and stores ra at offset 12. Before the call, sp is 8001_0000. What does the last row say?
// Where is the return address kept?
// The program is the task at the top. Each row is one instruction: i(kind, a, b, c).
// The comment beside a row is the same instruction in assembly.
module tb;
  task automatic the_program();
    i(JAL,    ra,   zero, 'h8);   // 00: jal ra, 0x8
    i(EBREAK, zero, zero, 0);     // 04: ebreak
    i(ADDI,   sp,   sp,   -16);   // 08: addi sp, sp, -16      the function starts here
    i(SW,     ra,   sp,   12);    // 0c: sw ra, 12(sp)
    i(EBREAK, zero, zero, 0);     // 10: ebreak
  endtask

  // ---- From here down: a small model of an RV32I processor, as test code. You need not change it. ----
  localparam int LUI = 0, AUIPC = 1, JAL = 2, JALR = 3, BEQ = 4, BNE = 5, BLT = 6, BGE = 7, BLTU = 8, BGEU = 9, LW = 10, SW = 11,
                 ADDI = 12, SLTI = 13, SLTIU = 14, XORI = 15, ORI = 16, ANDI = 17, SLLI = 18, SRLI = 19, SRAI = 20,
                 ADD = 21, SUB = 22, SLL = 23, SLT = 24, SLTU = 25, XOR = 26, SRL = 27, SRA = 28, OR = 29, AND = 30, EBREAK = 31;
  localparam int zero = 0, ra = 1, sp = 2, gp = 3, tp = 4, t0 = 5, t1 = 6, t2 = 7, s0 = 8, s1 = 9, a0 = 10, a1 = 11, a2 = 12, a3 = 13, a4 = 14, a5 = 15,
                 a6 = 16, a7 = 17, s2 = 18, s3 = 19, s4 = 20, s5 = 21, s6 = 22, s7 = 23, s8 = 24, s9 = 25, s10 = 26, s11 = 27, t3 = 28, t4 = 29, t5 = 30, t6 = 31;
  int kind [0:63], fa [0:63], fb [0:63], fc [0:63];   // the program: one row for each instruction
  int rows = 0;
  task automatic i(input int k, input int a, input int b, input int c);   // add one row to the program
    if (rows < 64) begin kind[rows] = k; fa[rows] = a; fb[rows] = b; fc[rows] = c; rows++; end
  endtask
  logic [31:0] x [0:31];             // the 32 registers
  logic [31:0] pc;                   // the address of the next instruction
  logic [31:0] mem [0:16383];        // 64 KiB of data memory, from address 8000_0000 up
  int   steps;
  bit   stopped, faulted;
  function automatic string rn(input int n);                // the name of a register in the calling convention
    case (n)
      0: return "zero"; 1: return "ra"; 2: return "sp"; 3: return "gp"; 4: return "tp"; 5: return "t0"; 6: return "t1"; 7: return "t2"; 
      8: return "s0"; 9: return "s1"; 10: return "a0"; 11: return "a1"; 12: return "a2"; 13: return "a3"; 14: return "a4"; 15: return "a5"; 
      16: return "a6"; 17: return "a7"; 18: return "s2"; 19: return "s3"; 20: return "s4"; 21: return "s5"; 22: return "s6"; 23: return "s7"; 
      24: return "s8"; 25: return "s9"; 26: return "s10"; 27: return "s11"; 28: return "t3"; 29: return "t4"; 30: return "t5"; 31: return "t6"; 
      default: return "?";
    endcase
  endfunction
  function automatic string nm(input int k);                // the name of a kind of instruction
    case (k)
      0: return "lui"; 1: return "auipc"; 2: return "jal"; 3: return "jalr"; 4: return "beq"; 5: return "bne"; 
      6: return "blt"; 7: return "bge"; 8: return "bltu"; 9: return "bgeu"; 10: return "lw"; 11: return "sw"; 
      12: return "addi"; 13: return "slti"; 14: return "sltiu"; 15: return "xori"; 16: return "ori"; 17: return "andi"; 
      18: return "slli"; 19: return "srli"; 20: return "srai"; 21: return "add"; 22: return "sub"; 23: return "sll"; 
      24: return "slt"; 25: return "sltu"; 26: return "xor"; 27: return "srl"; 28: return "sra"; 29: return "or"; 
      30: return "and"; 31: return "ebreak"; 
      default: return "?";
    endcase
  endfunction
  // One instruction: read the row at the PC, do what it says, and print one line.
  task automatic step();
    int k, a, b;
    logic [31:0] c, r1, r2, res, next, ad;
    string text, effect;
    bit writes, go, take;
    go = 1;  k = EBREAK;  a = 0;  b = 0;  c = 0;
    if (pc[1:0] != 0 || pc >= 256) begin
      $display("%08h | no instruction at this address", pc);  faulted = 1;  stopped = 1;  go = 0;
    end
    else begin k = kind[pc >> 2];  a = fa[pc >> 2];  b = fb[pc >> 2];  c = fc[pc >> 2]; end
    r1 = x[b[4:0]];  r2 = x[c[4:0]];
    next = pc + 4;  writes = 1;  res = 0;  effect = "";
    if (go) case (k)
      LUI:   begin res = c << 12;       text = $sformatf("lui %s, 0x%0h", rn(a), c); end
      AUIPC: begin res = pc + (c << 12); text = $sformatf("auipc %s, 0x%0h", rn(a), c); end
      JAL:   begin res = pc + 4;  next = c;  text = $sformatf("jal %s, 0x%0h", rn(a), c); end
      JALR:  begin res = pc + 4;  next = (r1 + c) & ~32'd1;  text = $sformatf("jalr %s, %0d(%s)", rn(a), $signed(c), rn(b)); end
      BEQ, BNE, BLT, BGE, BLTU, BGEU: begin
        r1 = x[a[4:0]];  r2 = x[b[4:0]];  writes = 0;
        case (k)
          BEQ:  take = (r1 == r2);
          BNE:  take = (r1 != r2);
          BLT:  take = ($signed(r1) < $signed(r2));
          BGE:  take = ($signed(r1) >= $signed(r2));
          BLTU: take = (r1 < r2);
          default: take = (r1 >= r2);
        endcase
        if (take) next = c;
        text = $sformatf("%s %s, %s, 0x%0h", nm(k), rn(a), rn(b), c);
        if (take) effect = $sformatf("taken: next is %08h", next);
        else effect = "not taken";
      end
      LW, SW: begin
        ad = r1 + c;
        text = $sformatf("%s %s, %0d(%s)", nm(k), rn(a), $signed(c), rn(b));
        if (ad[1:0] != 0 || ad < 32'h8000_0000 || ad > 32'h8000_fffc) begin
          $display("%08h | %s | no data memory at %08h", pc, text, ad);  faulted = 1;  stopped = 1;  go = 0;
        end
        else if (k == LW) begin res = mem[ad[15:2]];  effect = $sformatf(" from mem[%08h]", ad); end
        else begin mem[ad[15:2]] = x[a[4:0]];  writes = 0;  effect = $sformatf("mem[%08h] = %08h", ad, x[a[4:0]]); end
      end
      ADDI:  res = r1 + c;
      SLTI:  res = ($signed(r1) < $signed(c)) ? 1 : 0;
      SLTIU: res = (r1 < c) ? 1 : 0;
      XORI:  res = r1 ^ c;
      ORI:   res = r1 | c;
      ANDI:  res = r1 & c;
      SLLI:  res = r1 << c[4:0];
      SRLI:  res = r1 >> c[4:0];
      SRAI:  res = $signed(r1) >>> c[4:0];
      ADD:   res = r1 + r2;
      SUB:   res = r1 - r2;
      SLL:   res = r1 << r2[4:0];
      SLT:   res = ($signed(r1) < $signed(r2)) ? 1 : 0;
      SLTU:  res = (r1 < r2) ? 1 : 0;
      XOR:   res = r1 ^ r2;
      SRL:   res = r1 >> r2[4:0];
      SRA:   res = $signed(r1) >>> r2[4:0];
      OR:    res = r1 | r2;
      AND:   res = r1 & r2;
      default: begin
        $display("%08h | ebreak | stop", pc);  stopped = 1;  go = 0;
      end
    endcase
    if (k >= ADDI && k <= SRAI) text = $sformatf("%s %s, %s, %0d", nm(k), rn(a), rn(b), $signed(c));
    if (k >= ADD && k <= AND)   text = $sformatf("%s %s, %s, %s", nm(k), rn(a), rn(b), rn(c[4:0]));
    if (go && writes) begin
      if (a[4:0] != 0) x[a[4:0]] = res;                      // register 0 is never written
      effect = {$sformatf("%s = %08h", rn(a), x[a[4:0]]), effect};
      if (k == JAL || k == JALR) begin                       // a jump with x0 as its destination keeps no return address
        if (a[4:0] == 0) effect = $sformatf("next is %08h", next);
        else effect = {effect, $sformatf(", next is %08h", next)};
      end
    end
    if (go) begin
      $display("%08h | %s | %s", pc, text, effect);
      pc = next;  steps++;
    end
  endtask
  task automatic run(input logic [31:0] start);
    pc = start;  steps = 0;  stopped = 0;  faulted = 0;
    while (!stopped && steps < 2000) step();
  endtask
  initial begin
    for (int n = 0; n < 32; n++) x[n] = 0;
    for (int n = 0; n < 16384; n++) mem[n] = 0;
    the_program();
    x[2] = 32'h8001_0000;
    run(0);
    if (!stopped) $display("still running after %0d instructions", steps);
    $display("sp=%08h, and the word at %08h holds %08h", x[2], x[2] + 12, mem[(x[2] + 12 - 32'h8000_0000) >> 2]);
  end
endmodule
ConceptWhat does sp hold, and which way does the stack grow?
ConceptWhat must a function save before it calls another function?
ConceptA function wants to use s3. What must it do?
ConceptWhy does a frame vanish when its function returns?
ConceptA function calls another and does not save ra. What happens at its return?

Common Mistakes

Wrong Call another function without saving ra.

The jal overwrites ra. The way back to your own caller is lost.

Fix Save ra in the frame before the first call, and restore it before the return.

Wrong Store below sp without moving sp.

Memory below sp belongs to nobody. The next callee puts its frame there.

Fix Subtract from sp first. Then store at sp and above.

Wrong Give back fewer bytes than were taken.

The caller then finds a wrong sp, and reads its own saved values from wrong places.

Fix Add back exactly what was subtracted, on every path to the return.

Remember

  • The stack grows toward lower addresses. sp holds the lowest address in use.
  • A frame is made by subtracting from sp and given back by adding the same number.
  • A function that calls saves ra. A function that uses a saved register saves the old value.
  • A leaf function that uses only temporary and argument registers needs no frame.

Practice

Report a problem with this page