---
title: Branches and loops in assembly
heading: Making decisions and repeating work
eyebrow: C8 · Lesson 9 · Branches and loops in assembly
xp: 50
---

::: hook
Left alone, a processor runs instructions one after another. Every decision and every loop in a program comes from one kind of instruction: a branch, which compares two registers and, if the comparison holds, loads the PC with a different address. An `if` is a branch that skips some instructions. A loop is a branch that jumps backward. This program finds the largest number in an array with both.

::: play
- Step through and watch a0, the largest value found so far.
- Which instruction decides whether a0 changes? Which one sends the program round again?
- The array holds 27 twice. Does the second 27 change a0?
:::
:::

```sim cpu
.data
vals: .word 14, -3, 27, 8, 27, 19
.text
    la t0, vals         # t0 points at the current element
    li t1, 6            # elements left to look at
    lw a0, 0(t0)        # the largest so far: vals[0]
loop:
    addi t0, t0, 4      # move to the next element
    addi t1, t1, -1
    beqz t1, done       # none left: finished
    lw t2, 0(t0)
    ble t2, a0, loop    # not bigger: go on to the next
    mv a0, t2           # bigger: it's the new largest
    j loop
done:
    ebreak
show: a0, t1, t2
hex: t0
memory: 0x1000..0x1018
speed: 4
```

::: predict
## How many times does `mv a0, t2` run?

- [ ] 0
- [x] 1
- [ ] 2
- [ ] 5

::: reveal
Once. a0 starts at 14, and only the first 27 is bigger. `ble t2, a0, loop` branches past the `mv` whenever the new value is less than or equal to a0, so the second 27 leaves it alone, and so do −3, 8 and 19.
:::
:::

::: nameit
## Branches, jumps and the shapes of control flow

**Conditional branches** compare two registers:

| Instruction | Branches when | Compares as |
|---|---|---|
| `beq a, b, L` / `bne` | a = b / a ≠ b | bits |
| `blt a, b, L` / `bge` | a < b / a ≥ b | signed |
| `bltu a, b, L` / `bgeu` | a < b / a ≥ b | unsigned |

The assembler also accepts `bgt`, `ble`, `beqz`, `bnez` and `bgtz`, which it writes as these with the operands swapped or x0 filled in. Signed and unsigned comparisons differ when a top bit is 1: 0xFFFFFFFF is −1 signed but 4,294,967,295 unsigned.

**Offsets.** A branch stores the distance to its label, in bytes, relative to its own address, as a 13-bit signed number, so it reaches about 4 KiB either way. `jal` (and the pseudo-instruction `j`) jumps unconditionally with a 21-bit offset, about 1 MiB either way.

**If and else.** The branch tests the opposite condition and skips the code that shouldn't run:

```
    bge a0, a1, else    # if (a0 < a1) {
    ...                 #     then part
    j end               # }
else:                   # else {
    ...                 #     else part
end:                    # }
```

**Loops.** Test, body, jump back. A loop that tests at the bottom (like `bnez t1, loop` in lesson 1) always runs its body at least once; one that tests at the top can run it zero times.
:::


::: example
## How many times does the body run here: `li t0, 0`, `li t1, 10`, then `loop:` (the body), `addi t0, t0, 1`, `blt t0, t1, loop`?

::: solution
1. **Follow the counter.** t0 runs from 0 to 9 during the body, and the loop ends when t0 reaches 10.
2. **Where the test sits.** The test is at the bottom, so the body always runs at least once.

**Answer:** ten times, with t0 = 0 to 9 during the body.
:::
:::

::: example
## Write `if (a0 > a1) a2 = a0; else a2 = a1;` with a single branch.

::: solution
1. **Assume the else case.** `mv a2, a1`.
2. **Skip the fix when it holds.** `ble a0, a1, done`.
3. **Otherwise fix it.** `mv a2, a0`, then `done:`.

**Answer:** `mv a2, a1`, `ble a0, a1, done`, `mv a2, a0`, then `done:`.
:::
:::

::: example
## A loop with a test at the bottom runs a 3-instruction body 100 times, with an `addi` and a branch per pass and two instructions to set it up. How many instructions does it execute?

::: solution
1. **Count the instructions.**
   $$\begin{aligned} N &= 2 + 100 \times (3 + 2) \\ &= 502 \end{aligned}$$
2. **The overhead.** The loop overhead, 200 instructions, is 40% of the work here.
3. **Unroll by four.** Four copies of the body per pass and 25 passes cut the overhead to 50 instructions:
   $$\begin{aligned} N &= 2 + 25 \times (12 + 2) \\ &= 352 \end{aligned}$$
   at the cost of a longer program.
4. **Why compilers do it.** Compilers unroll short loops for exactly this reason.

**Answer:** 502 instructions, 200 of them loop overhead; unrolling by four brings it to 352.
:::
:::

::: check
kind: asm
given: n = 5..60 int
setup: a0 = n
expect: a1 = n*(n + 1)/2

## With n in a0, put 1 + 2 + … + n into a1.

```asm starter
    # n is in a0
    li a1, 0
    ebreak
```

```asm solution
    li a1, 0
    li t0, 1
loop:
    bgt t0, a0, done
    add a1, a1, t0
    addi t0, t0, 1
    j loop
done:
    ebreak
```

::: right
Right. A counter, a running total, and a branch that leaves once the counter passes n.
:::
:::

::: check
kind: asm
given: x = 100..900 int; y = 100..900 int; s = -1 | 1; t = -1 | 1; let a = s*x; let b = t*y
setup: a0 = a; a1 = b
expect: a2 = (a + b + abs(a - b))/2

## a0 and a1 hold two signed numbers. Put the larger of them in a2.

```asm starter
    # the numbers are in a0 and a1
    ebreak
```

```asm solution
    mv a2, a0
    bge a0, a1, done    # a0 is already the larger
    mv a2, a1
done:
    ebreak
```

::: right
Right. Assume one answer, then branch past the fix when it's already correct. `bge` compares as signed numbers, which these are.
:::
:::

::: check
given: p = 300..900 int; d = 2..40 int; let a = 4*p; let b = 4*(p - d)
answer: b - a
tolerance: 0

## A branch at address 0x{a:hex4} jumps back to a label at 0x{b:hex4}. What offset, in bytes, is stored in the instruction?

::: right
Right: {answer}. The target minus the branch's own address.
:::

::: misses
- [a - b] The target is before the branch, so the offset is negative.
- [-d] Offsets count bytes, and each instruction is 4.
- [any] Not yet. Subtract the branch's address from the target's.
:::
:::

::: check
given: k = 3..7 int; q = 3..20 int; r = 1..2 int; let s = k*q + r
answer: q + 1
tolerance: 0

## How many times does the body of this loop run?

```
    li t0, {s}
loop:
    ...                 # the body
    addi t0, t0, -{k}
    bgtz t0, loop
```

::: right
Right: {answer}. After {q} passes t0 is {r}, still above 0, so the body runs once more.
:::

::: misses
- [q] Check the last pass: after {q} passes t0 is still positive.
- [s] t0 drops by {k} each pass.
- [any] Not yet. Count passes until t0 reaches 0 or below.
:::
:::

::: check
kind: choice

## t0 holds 0xFFFFFFFF and t1 holds 1. Which of these branches is taken?

- [x] `blt t0, t1, L`
- [ ] `bltu t0, t1, L`
- [ ] `beq t0, t1, L`
- [ ] `bge t0, t1, L`

::: right
Right. As a signed number 0xFFFFFFFF is −1, which is less than 1.
:::

::: misses
- [2] Unsigned, 0xFFFFFFFF is 4,294,967,295, which isn't less than 1.
- [3] They aren't equal.
- [4] Signed, −1 isn't greater than or equal to 1.
:::
:::

::: check
kind: asm
given: n = 3..40 int
setup: a0 = n
expect: a1 = n*(n - 1)

## With n in a0, put n × (n − 1) into a1 using only additions in a loop (no `mul`).

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

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

::: right
Right. A counted loop of additions: multiplication the slow way.
:::
:::

::: check
kind: parts
given: N = 50 | 100 | 1000; b = 2 | 3 | 6; u = 2 | 4

## A bottom-tested loop runs a {b}-instruction body {N} times with 2 instructions of overhead per pass and 2 to set it up.

::: part
answer: 2 + N*(b + 2)
tolerance: 0

### How many instructions does it execute?

::: misses
- [any] Setup plus passes × (body + overhead).
:::
:::

::: part
answer: 2 + N/u*(u*b + 2)
tolerance: 0

### And unrolled by {u}?

::: misses
- [any] N/u passes, each with u copies of the body.
:::
:::
:::

::: explain
## When an `if` statement becomes assembly, why does the branch test the opposite of the `if`'s condition?

::: model
The processor falls through to the next instruction unless a branch jumps, and the instructions of the `if`'s body come right after the test. So the body runs by default, and the branch's job is to jump over it when it shouldn't run, which is when the condition is false. That's why `if (a < b)` becomes `bge a, b, skip`: the branch is taken exactly when the body must be skipped. At the end of the body, a `j` jumps over any `else` part.
:::
:::

::: practice

::: check
kind: asm
given: n = 3..40 int
setup: a0 = n
expect: a1 = n*(n + 1)

## With n in a0, put 2 + 4 + … + 2n into a1.

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

```asm solution
    li a1, 0
    li t0, 2
    slli t1, a0, 1
loop:
    bgt t0, t1, done
    add a1, a1, t0
    addi t0, t0, 2
    j loop
done:
    ebreak
```

::: misses
- [any] Count up by 2 and stop past 2n.
:::
:::

::: check
given: p = 100..900 int; d = 2..60 int; let a = 4*p; let b = 4*(p + d)
answer: b - a
tolerance: 0

## A branch at 0x{a:hex4} jumps forward to 0x{b:hex4}. Offset in bytes?

::: misses
- [d] In bytes: 4 per instruction.
- [any] Target minus branch address.
:::
:::

::: check
given: k = 3..9 int; q = 2..15 int; r = 1..2 int; let s = k*q + r
answer: q + 1
tolerance: 0

## `li t0, {s}`, then a body ending `addi t0, t0, -{k}` and `bgtz t0, loop`. Passes?

::: misses
- [q] One more: t0 is still {r} after {q} passes.
- [any] Count until t0 ≤ 0.
:::
:::
:::
