---
title: The stack and function calls
heading: Calling a function and finding the way back
eyebrow: C8 · Lesson 14 · The stack and function calls
xp: 50
---

::: hook
A function can be called from many places, so when it finishes it has to know where to go back to. RISC-V's answer is one instruction that jumps and remembers: `jal` puts the address of the next instruction in the register ra and then jumps. The function returns with `ret`, a jump to whatever ra holds. That works for one level. When a function calls another, the second call overwrites ra, so the first function has to save ra somewhere first, and the place is the stack: a region of memory that grows downward as calls nest and shrinks as they return. This program adds 3 + 2 + 1 with a function that calls itself.

::: play
- Step through and watch sp and ra. Each call to `sum` pushes a 16-byte frame holding ra and n.
- The memory window shows the stack. Find each frame's saved n and saved return address.
- After the calls return, sp is back to 0x10000. Is the old data in memory gone?
:::
:::

```sim cpu
    li a0, 3
    call sum            # a0 = sum(3)
    ebreak
# sum(n) = n + (n - 1) + ... + 1, found by calling itself
sum:
    beqz a0, base       # sum(0) is 0
    addi sp, sp, -16    # make a frame
    sw ra, 12(sp)       # save the return address
    sw a0, 8(sp)        # save n
    addi a0, a0, -1
    call sum            # a0 = sum(n - 1)
    lw t0, 8(sp)        # get n back
    add a0, a0, t0      # n + sum(n - 1)
    lw ra, 12(sp)       # get the return address back
    addi sp, sp, 16     # remove the frame
base:
    ret
show: a0, ra, t0
hex: ra
memory: 0xFFD0..0x10000
speed: 4
```

::: predict
## While `sum(0)` runs, at the deepest point of the calls, how many 16-byte frames are on the stack?

- [ ] 1
- [x] 3
- [ ] 4
- [ ] 6

::: reveal
Three: one each for sum(3), sum(2) and sum(1), each holding its n and its return address. sum(0) returns straight away without making a frame, because it calls nothing. At that point sp is 0x10000 − 3 × 16 = 0xFFD0. When the calls return, sp climbs back to 0x10000, but the old values stay in memory: popping a frame only moves sp.
:::
:::

::: nameit
## Calls, returns and the calling convention

**Call and return.** `jal ra, f` (written `call f`) saves PC + 4, the address of the instruction after the call, in ra and jumps to f. `ret` is `jalr x0, 0(ra)`: jump to the address in ra. (`call` is written as two instructions here, `auipc` and `jalr`, so that it can reach a function anywhere.)

**The stack.** sp holds the address of the top of the stack, which grows toward lower addresses. A function that needs to save registers makes a frame on entry and removes it before returning:

```
f:  addi sp, sp, -16    # make room
    sw ra, 12(sp)       # save what must survive
    ...
    lw ra, 12(sp)       # restore it
    addi sp, sp, 16     # give the room back
    ret
```

The standard RISC-V convention keeps sp a multiple of 16, so frames come in steps of 16 bytes.

**The calling convention** is the agreement that lets separately written functions work together:

| Registers | Role | Who saves them |
|---|---|---|
| a0 to a7 | arguments; a0 (and a1) carry the result back | the caller, if it needs them after the call |
| t0 to t6 | temporaries | the caller, if it needs them after the call |
| ra | return address | a function that makes calls of its own |
| s0 to s11 | values kept across calls | the callee, before it uses them |
| sp | stack pointer | the callee leaves it as it found it |

A **leaf function**, one that calls nothing, often needs no frame at all.

**Recursion** works because every call gets its own frame, so each level keeps its own n and its own way back.
:::


::: example
## sp is 0xFFF0 when f is called. f makes a 16-byte frame and saves ra at 12(sp) and s0 at 8(sp). At what addresses are they saved?

::: solution
1. **Make the frame.** f moves sp down 16 bytes:
   $$\text{0xFFF0} - 16 = \text{0xFFE0}$$
2. **Save ra.** It goes 12 bytes up:
   $$\text{0xFFE0} + 12 = \text{0xFFEC}$$
3. **Save s0.** It goes 8 bytes up:
   $$\text{0xFFE0} + 8 = \text{0xFFE8}$$

**Answer:** ra is saved at 0xFFEC and s0 at 0xFFE8.
:::
:::

::: example
## f calls g, and g calls h, which calls nothing. f and g each make a 16-byte frame and h makes none. How far below f's starting sp is sp while h runs?

::: solution
1. **Add up the frames.** f's frame and g's are 16 bytes each, 32 bytes together.
2. **h's frame.** h is a leaf, so it needs no frame of its own.

**Answer:** 32 bytes below f's starting sp.
:::
:::

::: example
## A function uses s0 and s1 and calls another function. Which registers must it save, and how big a stack frame does it need?

::: solution
1. **Save ra.** Its own call overwrites it.
2. **Save s0 and s1.** The calling convention promises its caller those are preserved.
3. **Size the frame.** That's 12 bytes, but the stack pointer must stay a multiple of 16, so the frame is 16 bytes.

```asm
    addi sp, sp, -16
    sw   ra, 12(sp)
    sw   s0, 8(sp)
    sw   s1, 4(sp)
```

4. **Restore before returning.** The mirror image comes before `ret`.
5. **Leave the temporaries.** t0 to t6 need no saving: the caller has already assumed they'll be lost.

**Answer:** it saves ra, s0 and s1, 12 bytes, in a 16-byte frame.
:::
:::

::: check
given: p = 2048..4095 int; k = 1..6 int; let s = 16*p
answer: s - 16*k
base: 16
width: 4

## sp holds 0x{s:hex4}. A chain of {k} nested calls each makes a 16-byte frame. What does sp hold at the deepest point?

::: right
Right: 0x{answer}. The stack grows toward lower addresses.
:::

::: misses
- [s + 16*k] The stack grows down: making a frame subtracts from sp.
- [s - k] Each frame is 16 bytes.
- [any] Not yet. Subtract 16 for each frame, in hex.
:::
:::

::: check
kind: choice

## A function is about to call another function. Which register must it have saved on the stack first, if it wants to return to its own caller afterwards?

- [x] ra
- [ ] a0
- [ ] zero
- [ ] t0

::: right
Right. The call puts a new return address in ra, so the old one is lost unless it was saved.
:::

::: misses
- [2] a0 only needs saving if the function needs its old value after the call.
- [3] zero is always 0; there's nothing to save.
- [4] t0 is a temporary. Save it only if you need it afterwards, but you will always need ra to get back.
:::
:::

::: check
kind: asm
given: n = 1..400 int
expect: a1 = 3*n

## Finish `triple`, a function that returns 3 × its argument. The main program passes n in a0 and calls it.

```asm starter
    li a0, n
    call triple
    mv a1, a0
    ebreak
triple:
    # return 3 * a0 in a0
    ret
```

```asm solution
    li a0, n
    call triple
    mv a1, a0
    ebreak
triple:
    slli t0, a0, 1      # 2n
    add a0, a0, t0      # 3n
    ret
```

::: right
Right. A leaf function: it calls nothing, so it can leave ra alone and needs no frame.
:::
:::

::: check
kind: asm
given: n = 1..200 int
expect: a1 = 9*n; sp = 65536

## Finish `nine`, which returns 9 × its argument by calling `triple` twice. The stack must be back where it started when the program stops.

```asm starter
    li a0, n
    call nine
    mv a1, a0
    ebreak
nine:
    # call triple twice; save ra first
    ret
triple:
    slli t0, a0, 1
    add a0, a0, t0
    ret
```

```asm solution
    li a0, n
    call nine
    mv a1, a0
    ebreak
nine:
    addi sp, sp, -16
    sw ra, 12(sp)
    call triple
    call triple
    lw ra, 12(sp)
    addi sp, sp, 16
    ret
triple:
    slli t0, a0, 1
    add a0, a0, t0
    ret
```

::: right
Right. Without saving ra, the first `call triple` would overwrite it, and `nine`'s `ret` would jump back into `nine` instead of to the main program.
:::
:::

::: check
given: F = 16 | 32 | 48; S = 1 | 2 | 4
answer: floor(1024*S/F)
tolerance: 0

## A recursive function makes a {F}-byte frame on each call, and the stack has {S} KiB (1 KiB = 1024 bytes). How many calls deep can it go before the stack runs out?

::: right
Right: {answer}. Go deeper and the stack overflows into whatever memory lies below it.
:::

::: misses
- [floor(1000*S/F)] 1 KiB is 1024 bytes.
- [any] Not yet. Divide the stack's size in bytes by the frame size.
:::
:::

::: check
kind: match

## Match each register to its role in the calling convention.

- a0 :: the first argument, and the return value
- ra :: where to go back to when the function returns
- sp :: the address of the top of the stack
- s0 :: kept across calls: a function that uses it saves it first
- t0 :: a temporary that any call may overwrite

::: right
Right. The convention lets functions written by different people, or by a compiler, call each other safely.
:::
:::

::: check
kind: parts
given: s = 1 | 2 | 5 | 6; c = 0 | 1

## A function uses {s} saved registers and makes calls if c = 1 (here c = {c}).

::: part
answer: s + c
tolerance: 0

### How many registers must it save on the stack?

::: misses
- [any] Each saved register it uses, plus ra if it calls.
:::
:::

::: part
answer: 16*ceil(4*(s + c)/16)
tolerance: 0

### How big is its frame, keeping sp a multiple of 16?

::: misses
- [4*(s + c)] Round up to a multiple of 16.
- [any] 4 bytes per register, rounded up to 16.
:::
:::
:::

::: check
kind: derivation
vars: d = 1..1000, f = 16..256, s = 4096..1048576

## Calls nest d deep, each with an f-byte frame, from a stack of s bytes.

::: step
answer: d*f

### How much stack is in use at the deepest point?
:::

::: step
answer: floor(s/f)

### How deep can calls nest before the stack overflows?
:::

::: right
Right. Recursion depth is limited by the stack, not by the algorithm.
:::
:::

::: explain
## Why must a function that calls another function save ra, while a function that calls nothing can leave it alone?

::: model
ra holds the address the function must return to. A call puts a new value in ra, the address just after that call, so a function that makes a call loses its own return address unless it copied it somewhere first, usually its stack frame, and restores it before `ret`. A leaf function never executes a call, so nothing changes ra between its entry and its `ret`, and it can return through ra directly.
:::
:::

::: practice

::: check
given: p = 2048..4095 int; k = 1..8 int; let s = 16*p
answer: s - 16*k
base: 16
width: 4

## sp = 0x{s:hex4}. After {k} 16-byte frames, sp?

::: misses
- [s + 16*k] It grows down.
- [any] Subtract 16k.
:::
:::

::: check
given: F = 16 | 32 | 64; S = 512 | 1024 | 2048
answer: floor(S/F)
tolerance: 0

## {S} bytes of stack, {F}-byte frames. Maximum depth?

::: misses
- [any] Stack size / frame size.
:::
:::

::: check
kind: asm
given: x = -300..300 int; y = 301..600 int; z = -300..-1 int
expect: a0 = x + y + z

## Finish `add3`, which returns the sum of its three arguments.

```asm starter
    li a0, x
    li a1, y
    li a2, z
    call add3
    ebreak
add3:
    ret
```

```asm solution
    li a0, x
    li a1, y
    li a2, z
    call add3
    ebreak
add3:
    add a0, a0, a1
    add a0, a0, a2
    ret
```

::: misses
- [any] The arguments arrive in a0, a1 and a2; the result goes back in a0.
:::
:::
:::
