---
title: Overflow, comparisons and big numbers
heading: Carries, overflow and comparisons without a flags register
eyebrow: C8 · Lesson 3 · Overflow, comparisons and big numbers
xp: 40
---

::: hook
Many processors keep a flags register: after every addition, hardware records whether it carried, overflowed or came out negative, and the next instruction can test those bits. RISC-V has no flags at all. An `add` just wraps around modulo $2^{32}$ and says nothing. So how does a RISC-V program add two 64-bit numbers, notice that a signed sum has overflowed, or tell whether 0xFFFFFFFF is the largest number or −1?
:::

::: play
- This program adds two 64-bit numbers held as pairs of 32-bit words: $x$ = 0x1_FFFFFFF0 in a1:a0 and $y$ = 0x2_00000020 in a3:a2.
- Step it. The low words' sum wraps to 0x10, and `sltu` notices: a sum smaller than one of its addends means a carry.
- The high words add with that carry, giving 4: the full sum is 0x4_00000010.
:::

```sim cpu
    li a0, 0xFFFFFFF0     # x, low word
    li a1, 1              # x, high word
    li a2, 0x20           # y, low word
    li a3, 2              # y, high word
    add a4, a0, a2        # low sum (wraps)
    sltu t0, a4, a0       # carry = 1 if the sum wrapped
    add a5, a1, a3        # high sum
    add a5, a5, t0        # plus the carry
    ebreak
show: a4, a5, t0
hex: a0, a1, a2, a3, a4, a5
speed: 2
```

::: predict
## t0 holds 0xFFFFFFFF and t1 holds 1. What do `slt t2, t0, t1` and `sltu t3, t0, t1` leave?

- [x] t2 = 1, t3 = 0
- [ ] t2 = 0, t3 = 1
- [ ] Both 1
- [ ] Both 0

::: reveal
t2 = 1 and t3 = 0. The same 32 bits are −1 to `slt`, which compares them as signed numbers, and 4,294,967,295 to `sltu`, which compares them as unsigned. The register doesn't know which it holds; the instruction decides.
:::
:::

::: nameit
## The same bits, two meanings

32 bits hold 0 to $2^{32} - 1$ as an unsigned number, or $-2^{31}$ to $2^{31} - 1$ in two's complement. `add`, `sub` and the loads and stores don't care which: the bits come out the same either way. Only comparisons, right shifts, widening loads and division need to know, so they come in pairs: `slt`/`sltu`, `blt`/`bltu`, `bge`/`bgeu`, `sra`/`srl`, `lb`/`lbu`, `div`/`divu`.

## Carries and borrows

An unsigned sum $s = a + b$ wrapped exactly when $s < a$ (unsigned), so

$$\text{carry} = (s <_u a)$$

is one `sltu`. A subtraction $a - b$ borrows when $a <_u b$. These are what let a 32-bit machine do **multiword arithmetic**: add the low words, compute the carry, add the high words and the carry. Four instructions for a 64-bit add, and the same pattern extends to any length.

## Signed overflow

A signed sum overflows when both operands have the same sign and the result's sign differs: two large positives can't add to a negative. The RISC-V manual's check for `add t0, t1, t2` is

```asm
    add  t0, t1, t2
    slti t3, t2, 0        # is the second operand negative?
    slt  t4, t0, t1       # is the sum below the first operand?
    bne  t3, t4, overflow # they must agree unless it overflowed
```

Adding a negative number must make the result smaller, and adding a non-negative one mustn't; overflow is exactly when that fails. When one operand is a known positive constant, a single `blt` does.

## Wide products

`mul` gives the low 32 bits of a product. `mulhu` gives the high 32 bits of the unsigned 64-bit product, and `mulh` those of the signed one, so a pair of instructions gets the whole product.

## The bounds check in one branch

To test $0 \le i < n$ for a signed index i, compare unsigned: `bgeu a0, t0, out`. A negative i looks like a huge unsigned number, so it fails the same test as one that's too large.
:::

::: example
## Add 0x7FFFFFFF and 1 as signed numbers. What does `add` give, and how does the check catch the overflow?

::: solution
1. **The sum.** `add` gives 0x80000000, which as a signed number is −2,147,483,648: two positives produced a negative.
2. **The first test.** `slti` on the second operand (1) gives 0.
3. **The second test.** `slt` asks whether the sum (−2,147,483,648) is below the first operand (2,147,483,647): yes, 1.
4. **The branch.** They disagree, so the branch goes to the overflow handler.
5. **As unsigned numbers.** The same addition is perfectly fine: 2,147,483,647 + 1 = 2,147,483,648, and `sltu` finds no carry.

**Answer:** `add` gives 0x80000000, which is −2,147,483,648; `slti` gives 0 and `slt` gives 1, and because they disagree the branch goes to the overflow handler.
:::
:::

::: example
## Subtract the 64-bit numbers 0x00000003_00000005 − 0x00000001_00000009 with 32-bit instructions.

::: solution
1. **Low words first.** 5 − 9 wraps to 0xFFFFFFFC, and `sltu` finds 5 < 9, a borrow of 1.
2. **High words, less the borrow.**
   $$3 - 1 - 1 = 1$$
3. **Join the halves.** The result is 0x00000001_FFFFFFFC.
4. **Check in decimal.**
   $$\begin{aligned} 12{,}884{,}901{,}893 \\ {} - 4{,}294{,}967{,}305 \\ {} = 8{,}589{,}934{,}588 \end{aligned}$$
   which is 0x1_FFFFFFFC.

**Answer:** 0x00000001_FFFFFFFC, which is 8,589,934,588.
:::
:::

::: example
## a0 holds a signed index that must satisfy 0 ≤ i < 100. Check it with one branch.

::: solution
1. **Compare as unsigned.** `li t0, 100` then `bgeu a0, t0, out`.
2. **A valid index.** Any i from 0 to 99 is below 100 as an unsigned number, so it falls through.
3. **Too large.** An index of 100 or more is caught as usual.
4. **Negative.** A negative one such as −3 reads as 0xFFFFFFFD = 4,294,967,293 unsigned, far above 100, so it's caught too.
5. **Where it's used.** Compilers use this trick for array bounds and for `switch` jump tables.

**Answer:** `li t0, 100` and then `bgeu a0, t0, out`: the one unsigned branch catches both an index of 100 or more and a negative one.
:::
:::

::: check
kind: asm
given: l1 = 4000000000..4294967295 int; h1 = 0..1000 int; l2 = 300000000..4000000000 int; h2 = 0..1000 int
setup: a0 = l1; a1 = h1; a2 = l2; a3 = h2
expect: a4 = l1 + l2 - 2^32*floor((l1 + l2)/2^32); a5 = h1 + h2 + floor((l1 + l2)/2^32)

## a1:a0 and a3:a2 hold two 64-bit numbers (high word first). Put their sum in a5:a4.

```asm starter
    add a4, a0, a2
    add a5, a1, a3
    ebreak
```

```asm solution
    add a4, a0, a2
    sltu t0, a4, a0
    add a5, a1, a3
    add a5, a5, t0
    ebreak
```

::: right
Right. The carry out of the low word is one `sltu`, added into the high word.
:::
:::

::: check
kind: parts
given: a = 2000000000 | 3000000000 | 4000000000; b = 1500000000 | 2500000000

## Two unsigned 32-bit numbers, {a} and {b}, are added.

::: part
answer: a + b - 2^32*floor((a + b)/2^32)
tolerance: 0

### What does `add` leave, as an unsigned number?

::: misses
- [any] If the true sum reaches $2^{32}$, it wraps: subtract $2^{32}$.
:::
:::

::: part
answer: floor((a + b)/2^32)
tolerance: 0

### What carry does `sltu` find (1 or 0)?

::: misses
- [any] 1 if the true sum reached $2^{32}$.
:::
:::
:::

::: check
kind: parts
given: n = 8 | 12 | 16 | 32

## An n-bit register, n = {n}.

::: part
answer: -2^(n - 1)
tolerance: 0

### What's the most negative two's-complement value?

::: misses
- [-2^n] Half the patterns are negative: $-2^{n-1}$.
- [any] $-2^{n-1}$.
:::
:::

::: part
answer: 2^n - 1
tolerance: 0

### What's the largest unsigned value?

::: misses
- [2^(n - 1) - 1] That's the largest signed value.
- [any] $2^n - 1$.
:::
:::
:::

::: check
kind: asm
given: a = -2147483648..2147483647 int; b = 1000000000..2147483647 int
setup: a0 = a; a1 = b
expect: a2 = a + b - (a + b - 2^31 + 1)*step(a + b - 2^31)

## a0 holds a signed number and a1 a positive one. Put their sum in a2, saturated: if the addition overflows, a2 gets the largest signed value, 0x7FFFFFFF, instead.

```asm starter
    li a2, 0
    ebreak
```

```asm solution
    add a2, a0, a1
    bge a2, a0, done
    li a2, 0x7FFFFFFF
done:
    ebreak
```

::: right
Right. Adding a positive number must make the result bigger; a smaller sum means it wrapped.
:::
:::

::: check
kind: parts
given: v = 3 | 100 | 5000; n = 10 | 64 | 1000

## a0 holds −{v} and t0 holds {n}.

::: part
answer: 2^32 - v
tolerance: 0

### What unsigned value does `bgeu` see in a0?

::: misses
- [any] $2^{32} - v$.
:::
:::

::: part
answer: 1
tolerance: 0

### Does `bgeu a0, t0, out` branch (1 for yes)?

::: misses
- [any] A negative index looks huge unsigned.
:::
:::
:::

::: check
kind: derivation
vars: h = 0..4294967295, l = 0..4294967295, m = 0..4294967295, k = 0..4294967295

## A 64-bit number is stored as a high word h and a low word l; a second as m and k.

::: step
answer: h*2^32 + l

### What value does the first represent?
:::

::: step
answer: floor((l + k)/2^32)

### What's the carry out of the low words' sum?
:::

::: step
answer: h + m + floor((l + k)/2^32)

### What's the high word of the sum, before it wraps?
:::

::: right
Right. Multiword arithmetic is long addition in base $2^{32}$.
:::
:::

::: check
kind: choice

## Which pair of instructions gives the full 64-bit product of two unsigned 32-bit numbers?

- [ ] `mul` and `mulh`
- [x] `mul` and `mulhu`
- [ ] `mul` alone
- [ ] `mulhu` and `divu`

::: misses
- [1] `mulh` treats both operands as signed, which changes the high word when either top bit is set.
- [3] `mul` keeps only the low 32 bits.
- [4] Division doesn't come into it.
:::
:::

::: check
given: a = 305419896 | 2596069104 | 4000000000; b = 3 | 7 | 255
answer: floor(a*b/2^32)
tolerance: 0

## What does `mulhu` give for {a} × {b}?

::: right
Right: the high word, {answer}.
:::

::: misses
- [any] Not yet. Divide the full product by $2^{32}$ and drop the fraction.
:::
:::

::: explain
## Why do RISC-V's `add` and `sub` need no signed and unsigned versions, when its comparisons do?

::: model
Two's complement was chosen so that adding and subtracting the bit patterns gives the right bits whether you read them as signed or unsigned: both are arithmetic modulo $2^{32}$, and only the meaning of the top bit differs. Comparison is different, because the order isn't the same: 0xFFFFFFFF is the largest unsigned number but −1 as a signed one, so "less than" gives different answers. The same goes for anything that widens or shrinks a number (right shifts, byte loads, division), which has to know whether to copy the sign bit.
:::
:::

::: practice
::: check
given: a = 4294967295 | 4000000000; b = 1 | 300000000 | 500000000
answer: a + b - 2^32*floor((a + b)/2^32)
tolerance: 0

## What does `add` leave for {a} + {b} (unsigned)?

::: misses
- [any] Subtract $2^{32}$ if the sum reaches it.
:::
:::

::: check
given: v = 1 | 16 | 255 | 4096
answer: 2^32 - v
tolerance: 0

## What unsigned number has the same bits as −{v}?

::: misses
- [any] $2^{32} - v$.
:::
:::

::: check
given: l = 5 | 9 | 100; k = 9 | 12 | 200
answer: step(k - l - 0.5)
tolerance: 0

## Does {l} − {k} borrow in unsigned arithmetic (1 for yes)?

::: misses
- [any] It borrows when the first is smaller.
:::
:::
:::
