---
title: Assembly functions lab
heading: Writing real functions in RISC-V assembly
eyebrow: C8 · Lesson 23 · Assembly functions lab
xp: 50
---

::: hook
The assembly lab (lesson 19) had you write loops and arithmetic. Real programs are made of functions: searching, counting, copying, and functions that call other functions, including themselves. Each of the seven exercises here is a small function you'd find in any C library or firmware, written by hand. They're graded by running them, and the last two also check that you followed the calling convention, because a function that works alone but wrecks its caller's registers or stack isn't finished.
:::

::: play
- The main program adds up the squares of 1 to 10 by calling `square` ten times.
- `square` is a normal function: it may use any temporary register, and it does, overwriting t0 and t1. That's why the running sum lives in s0 and the counter in s1, which callees must preserve.
- Step through one call: `jal` saves the return address in ra, `square` runs, and `ret` jumps back. a0 ends at 385.
:::

```sim cpu
    li a0, 10
    mv s2, a0            # n, kept safe in a saved register
    li s0, 0             # the sum
    li s1, 1             # i
loop:
    bgt s1, s2, done
    mv a0, s1            # the argument
    jal ra, square
    add s0, s0, a0       # the result comes back in a0
    addi s1, s1, 1
    j loop
done:
    mv a0, s0
    ebreak

square:                  # a0 = a0 * a0; clobbers t0 and t1, as it may
    mv t0, a0
    li t1, 0x5A5A
    mul a0, t0, t0
    ret
show: a0, s0, s1, t0, ra
speed: 6
```

::: predict
## If main kept the running sum in t0 instead of s0, what would a0 hold at the end?

- [ ] 385, as before
- [x] 110
- [ ] 100
- [ ] 55

::: reveal
110. Each call to `square` copies its argument into t0, so whatever sum was there is lost. After the last call t0 holds 10, and adding the returned 100 gives 110. The rule is simple: anything that must survive a call goes in a saved register or on the stack.
:::
:::

::: nameit
## The calling convention, in brief

| Registers | Role | Who saves them |
|---|---|---|
| a0–a7 | arguments; a0 (and a1) return the result | the caller, if it needs them after the call |
| t0–t6 | temporaries | the caller, if it needs them |
| s0–s11 | saved registers | the callee, if it uses them |
| ra | return address, set by `jal` | the callee, if it calls anything |
| sp | stack pointer, a multiple of 16 | must be back where it started at `ret` |

A **leaf function**, one that calls nothing, can often work entirely in temporaries and needs no stack frame. A function that calls others saves ra, plus any saved registers it uses, in a frame it makes by moving sp down, and restores them before `ret`.

## Recursion

A recursive function is just a function that calls itself, so it follows the same rules: every call gets its own frame holding its own ra and whatever it needs after the inner call returns. The stack grows by one frame per level.

## Testing a function

The graders below put arguments in registers or memory, run your code to `ebreak`, and check results. The last two also check that sp ends where it started, which catches unbalanced frames.
:::

::: example
## Why does the predict question's version lose the sum, even though `square` never touches it on purpose?

::: solution
1. **What t0 is.** t0 is a temporary: the convention says a callee may change it without saving it, and `square` uses it as scratch.
2. **What the caller must assume.** The caller can't know which temporaries a callee uses (it might be in a library compiled separately), so it must assume all of them are destroyed by any call.
3. **The fix.** Keeping the sum in s0 shifts the burden: if `square` wanted s0, it would have to save and restore it.

**Answer:** `square` is allowed to overwrite the temporary t0, and it does; keeping the sum in s0 makes `square` responsible for preserving it.
:::
:::

::: example
## Counting the 1 bits of a word bit by bit takes 32 passes. How can a loop take one pass per 1 bit instead, and how many passes does 0xF0F0 need?

::: solution
1. **Clear the lowest set bit.** `x & (x − 1)` does it: subtracting 1 turns the lowest 1 into 0 and the 0s below it into 1s, and the AND keeps everything above.
2. **Loop until zero.** Repeat until x is 0, counting passes.
3. **Count the passes for 0xF0F0.** It has 8 set bits, so 8 passes, against 32 for testing every bit.
4. **Write the loop.**

```asm
loop:
    beqz a0, done
    addi t0, a0, -1
    and  a0, a0, t0
    addi a1, a1, 1
    j    loop
done:
```

**Answer:** clear the lowest set bit with `x & (x − 1)` on each pass; 0xF0F0 needs 8 passes.
:::
:::

::: check
kind: asm
given: v1 = -1000..1000 int; v2 = -1000..1000 int; v3 = -1000..1000 int; v4 = -1000..1000 int; v5 = -1000..1000 int
expect: a0 = (((v1 + v2 + abs(v1 - v2))/2 + v3 + abs((v1 + v2 + abs(v1 - v2))/2 - v3))/2 + (v4 + v5 + abs(v4 - v5))/2 + abs(((v1 + v2 + abs(v1 - v2))/2 + v3 + abs((v1 + v2 + abs(v1 - v2))/2 - v3))/2 - (v4 + v5 + abs(v4 - v5))/2))/2

## a0 points to an array of a1 signed words (here 5). Return the largest in a0.

```asm starter
.data
vals: .word v1, v2, v3, v4, v5
.text
    la a0, vals
    li a1, 5
    li a0, -2000
    ebreak
```

```asm solution
.data
vals: .word v1, v2, v3, v4, v5
.text
    la a0, vals
    li a1, 5
    lw t0, 0(a0)
loop:
    addi a1, a1, -1
    beqz a1, done
    addi a0, a0, 4
    lw t1, 0(a0)
    ble t1, t0, loop
    mv t0, t1
    j loop
done:
    mv a0, t0
    ebreak
```

::: right
Right. Start with the first element as the best so far, and compare each of the rest against it.
:::
:::

::: check
kind: asm
given: c = 108 | 111 | 119
setup: a1 = c
expect: a0 = 3 - step(c - 110) - step(c - 115)

## a0 points to the string "hello, world" (ending in a zero byte), and a1 holds a character code. Return in a0 how many times that character appears.

```asm starter
.data
s: .asciz "hello, world"
.text
    la a0, s
    li a0, 0
    ebreak
```

```asm solution
.data
s: .asciz "hello, world"
.text
    la a0, s
    li t2, 0
loop:
    lbu t0, 0(a0)
    beqz t0, done
    bne t0, a1, next
    addi t2, t2, 1
next:
    addi a0, a0, 1
    j loop
done:
    mv a0, t2
    ebreak
```

::: right
Right. `lbu` a byte at a time until the zero that ends the string.
:::
:::

::: check
kind: asm
given: w = 1..65535 int
setup: a0 = w
expect: a1 = w - floor(w/2) - floor(w/4) - floor(w/8) - floor(w/16) - floor(w/32) - floor(w/64) - floor(w/128) - floor(w/256) - floor(w/512) - floor(w/1024) - floor(w/2048) - floor(w/4096) - floor(w/8192) - floor(w/16384) - floor(w/32768)

## Count the 1 bits in a0 and return the count in a1.

```asm starter
    li a1, 0
    ebreak
```

```asm solution
    li a1, 0
loop:
    beqz a0, done
    addi t0, a0, -1
    and a0, a0, t0
    addi a1, a1, 1
    j loop
done:
    ebreak
```

::: right
Right. However you count them, the answer is the population count; the `x & (x − 1)` loop runs once per 1 bit.
:::
:::

::: check
kind: asm
given: v1 = -5000..5000 int; v2 = -5000..5000 int; v3 = -5000..5000 int; v4 = -5000..5000 int
expect: mem[4112] = v1; mem[4116] = v2; mem[4120] = v3; mem[4124] = v4

## Copy a2 words from the address in a0 to the address in a1 (here 4 words, from `src` to `dst`).

```asm starter
.data
src: .word v1, v2, v3, v4
dst: .space 16
.text
    la a0, src
    la a1, dst
    li a2, 4
    ebreak
```

```asm solution
.data
src: .word v1, v2, v3, v4
dst: .space 16
.text
    la a0, src
    la a1, dst
    li a2, 4
loop:
    beqz a2, done
    lw t0, 0(a0)
    sw t0, 0(a1)
    addi a0, a0, 4
    addi a1, a1, 4
    addi a2, a2, -1
    j loop
done:
    ebreak
```

::: right
Right. That's `memcpy` for words: a load, a store and two moving pointers.
:::
:::

::: check
kind: asm
given: g = 1..60 int; p = 7 | 9 | 16; q = 5 | 11 | 25
setup: a0 = g*p; a1 = g*q
expect: a0 = g

## Return in a0 the greatest common divisor of a0 and a1, using Euclid's algorithm with `remu`.

```asm starter
    ebreak
```

```asm solution
loop:
    beqz a1, done
    remu t0, a0, a1
    mv a0, a1
    mv a1, t0
    j loop
done:
    ebreak
```

::: right
Right. Replace (a, b) with (b, a mod b) until b is 0; a is the answer.
:::
:::

::: check
kind: asm
given: n = 2..30 int
setup: a0 = n
expect: a0 = n*(n + 1)*(2*n + 1)/6; sp = 65536

## `square` (provided) returns a0² and clobbers t0 and t1. With n in a0, call it for each i from 1 to n and return the sum of the squares in a0.

```asm starter
    ebreak

square:
    mv t0, a0
    li t1, 0x5A5A
    mul a0, t0, t0
    ret
```

```asm solution
    mv s2, a0
    li s0, 0
    li s1, 1
loop:
    bgt s1, s2, done
    mv a0, s1
    jal ra, square
    add s0, s0, a0
    addi s1, s1, 1
    j loop
done:
    mv a0, s0
    ebreak

square:
    mv t0, a0
    li t1, 0x5A5A
    mul a0, t0, t0
    ret
```

::: right
Right. Everything that has to survive a call lives in saved registers.
:::
:::

::: check
kind: asm
given: n = 2..40 int
setup: a0 = n
expect: a0 = n*(n + 1)/2; sp = 65536

## Write `sum` recursively: sum(0) = 0 and sum(n) = n + sum(n − 1). Main calls it with n in a0. Each level must save what it needs on the stack, and sp must end where it started.

```asm starter
    jal ra, sum
    ebreak

sum:
    ret
```

```asm solution
    jal ra, sum
    ebreak

sum:
    beqz a0, base
    addi sp, sp, -16
    sw ra, 12(sp)
    sw a0, 8(sp)
    addi a0, a0, -1
    jal ra, sum
    lw t0, 8(sp)
    add a0, a0, t0
    lw ra, 12(sp)
    addi sp, sp, 16
    ret
base:
    ret
```

::: right
Right. Each level saves its own ra and n, makes the inner call, then adds its n to what comes back.
:::
:::

::: explain
## In the recursive `sum`, why must each call save ra on the stack, and why can't it keep n in s0 without saving s0 first?

::: model
Each `jal` overwrites ra with its own return address, so a function that makes a call loses the address it was supposed to return to unless it saved ra first; with recursion every level makes a call, so every level must save its own ra in its own frame. n is needed after the inner call returns, so it must be somewhere the inner call won't destroy. A saved register would survive, but the inner call is the same function, which would also put its n in s0. The convention says a function that uses s0 must save the caller's value and restore it, so each level would have to push s0 anyway. Either way, each level's n ends up in its own stack frame.
:::
:::
