---
title: RISC-V instructions and assembly
heading: The words a processor understands
eyebrow: C8 · Lesson 2 · RISC-V instructions and assembly
xp: 50
---

::: hook
A processor understands only a fixed set of instructions, its instruction set. RISC-V is an open instruction set used in microcontrollers, phones' helper cores and research chips, and its base set, RV32I, has only about 40 instructions. Each one does something small: add two registers, add a constant, shift, compare, load, store, branch. Assembly language is those instructions written as text, one per line, which an assembler turns into 32-bit words. Programs that look clever in C are long runs of these small steps.

::: play
- Step through the program and watch each register change (it lights up when it does).
- RV32I has no multiply instruction. How does the program compute 10 × 7?
- The line `li a2, 0x12345678` is special. Watch how far the PC moves when it runs.
:::
:::

```sim cpu
    li a0, 7            # x = 7
    slli t0, a0, 3      # t0 = x shifted left 3 places = 8x
    slli t1, a0, 1      # t1 = 2x
    add t2, t0, t1      # t2 = 8x + 2x = 10x
    addi a1, t2, 3      # a1 = 10x + 3
    li a2, 0x12345678   # a big constant
    xori a3, a0, -1     # flip every bit of x
    sub a4, zero, a0    # 0 - x
    ebreak
show: a0, a1, a2, a3, a4, t0, t1, t2
hex: a2
speed: 2
```

::: predict
## Every RISC-V instruction is 32 bits long. How many instructions does `li a2, 0x12345678` (load a 32-bit constant) turn into?

- [ ] 1
- [x] 2
- [ ] 4
- [ ] It can't be done

::: reveal
Two. The constant needs all 32 bits, and an instruction also has to carry its opcode and destination register, so it can't fit in one. The assembler writes `lui a2, 0x12345`, which loads the upper 20 bits, and then `addi a2, a2, 0x678`, which adds the lower 12. The PC moves 8 bytes over that one line. `li` is a pseudo-instruction: a convenience the assembler expands into real ones.
:::
:::

::: nameit
## Registers, instructions and their formats

**Registers.** 32 registers of 32 bits, x0 to x31. x0 always reads as 0, and writes to it are thrown away. Each has a conventional name for how programs use it: a0 to a7 for function arguments and results, t0 to t6 for temporaries, s0 to s11 for values kept across calls, sp the stack pointer and ra the return address.

**Assembly.** The destination comes first: `add t2, t0, t1` means t2 = t0 + t1.

| Kind | Examples | Does |
|---|---|---|
| register-register | `add sub and or xor sll srl sra slt sltu` | rd = rs1 op rs2 |
| register-immediate | `addi andi ori xori slli srli srai slti` | rd = rs1 op constant |
| load and store | `lw lh lb lbu sw sh sb` | move data between registers and memory |
| branch and jump | `beq bne blt bge jal jalr` | change the PC |
| upper immediate | `lui auipc` | load the upper 20 bits |

`sll` shifts left (×2 per place), `srl` shifts right filling with 0s, and `sra` shifts right copying the sign bit, which divides a signed number by 2 per place. `slt` sets rd to 1 if rs1 < rs2.

**Encoding.** The fields sit in fixed places, so decoding is quick. An I-type instruction such as `addi` holds a 12-bit signed immediate, from −2048 to 2047:

| bits | 31 to 25 | 24 to 20 | 19 to 15 | 14 to 12 | 11 to 7 | 6 to 0 |
|---|---|---|---|---|---|---|
| R-type (`add`) | funct7 | rs2 | rs1 | funct3 | rd | opcode |
| I-type (`addi`) | imm[11:5] | imm[4:0] | rs1 | funct3 | rd | opcode |

For example, `addi x1, x0, 5` has imm = 5, rs1 = 0, funct3 = 000, rd = 1 and opcode 0010011 (0x13), which packs into the word 0x00500093.

**Pseudo-instructions** are shorthands: `li` (load a constant), `mv a0, a1` (`addi a0, a1, 0`), `not` (`xori` with −1, which is all 1s), `neg` (`sub` from zero) and `nop` (`addi x0, x0, 0`).

**Big constants.** `lui` loads 20 bits into bits 31 to 12, and `addi` adds a 12-bit signed value. Because `addi` sign-extends, a lower part with bit 11 set counts as negative, so `lui` takes one more: 0x12345FFF becomes `lui 0x12346` plus `addi −1`.
:::


::: example
## t0 = 12 and t1 = 5. What do `sub t2, t0, t1`, `slli t3, t1, 3` and `slt t4, t1, t0` leave?

::: solution
1. **The subtraction.** `sub t2, t0, t1` gives
   $$\begin{aligned} \text{t2} &= 12 - 5 \\ &= 7 \end{aligned}$$
2. **The shift.** `slli t3, t1, 3` shifts 5 left 3 places, which multiplies it by 8:
   $$\begin{aligned} \text{t3} &= 5 \times 8 \\ &= 40 \end{aligned}$$
3. **The comparison.** `slt t4, t1, t0` gives t4 = 1, because 5 < 12.

**Answer:** t2 = 7, t3 = 40 and t4 = 1.
:::
:::

::: example
## Why does `li t0, 5000` become two instructions?

::: solution
1. **Check the immediate's range.** An `addi` immediate is 12 bits, at most 2047, so 5000 doesn't fit.
2. **Split the constant.**
   $$5000 = 4096 + 904$$
3. **Load the upper part.** `lui t0, 1` puts 4096 in t0.
4. **Add the rest.** `addi t0, t0, 904` adds the other 904.

**Answer:** 5000 is too big for a 12-bit immediate, so the assembler uses `lui t0, 1` (4096) and then `addi t0, t0, 904`.
:::
:::

::: example
## t0 holds −16 (0xFFFFFFF0). What do `srli t1, t0, 2` and `srai t2, t0, 2` leave?

::: solution
1. **The logical shift.** `srli` shifts in zeros: 0x3FFFFFFC, which is 1,073,741,820, a huge positive number.
2. **The arithmetic shift.** `srai` copies the sign bit into the vacated places: 0xFFFFFFFC, which is −4, exactly −16 ÷ 4.
3. **Which to use.** Use the arithmetic shift to divide signed numbers by powers of two, and the logical shift for unsigned numbers and bit fields.
4. **Rounding.** For negative odd values the arithmetic shift rounds toward −∞, unlike C's division, which rounds toward zero.

**Answer:** `srli` leaves 0x3FFFFFFC (1,073,741,820) in t1, and `srai` leaves 0xFFFFFFFC (−4) in t2.
:::
:::

::: check
kind: asm
given: n = 3..300 int
setup: a0 = n
expect: a1 = 5*n

## RV32I has no multiply instruction. With n in a0, put 5 × n in a1 using shifts and adds.

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

```asm solution
    slli t0, a0, 2      # 4n
    add a1, t0, a0      # 4n + n
    ebreak
```

::: right
Right. Shifting left by 2 multiplies by 4, and one more n makes 5n. Compilers turn multiplications by constants into shifts and adds like this.
:::
:::

::: check
kind: asm
given: q = 6..180 int; r = 1..15 int; let n = 16*q + r
setup: a0 = n
expect: a1 = 16*q

## With n in a0, put n with its lowest 4 bits cleared into a1. Use one instruction before the `ebreak`.

```asm starter
    # n is in a0
    mv a1, a0
    ebreak
```

```asm solution
    andi a1, a0, -16    # -16 is 1111...10000
    ebreak
```

::: right
Right. −16 sign-extends to 0xFFFFFFF0: every bit is 1 except the lowest four, so the AND keeps the rest of n and clears those.
:::
:::

::: check
given: rd = 1..31 int; imm = 1..2047 int
answer: imm*1048576 + rd*128 + 19
base: 16
width: 8

## Encode `addi x{rd}, x0, {imm}` as a 32-bit word in hex.

::: right
Right: 0x{answer}. The immediate sits in bits 31 to 20, rs1 (0) in 19 to 15, funct3 (0) in 14 to 12, rd in 11 to 7 and the opcode 0x13 in 6 to 0.
:::

::: misses
- [imm*1048576 + rd*128] The opcode for `addi`, 0010011 (0x13), fills the lowest 7 bits.
- [imm*1048576 + rd + 19] rd starts at bit 7, so it's multiplied by $2^7$ = 128.
- [any] Not yet. Place each field: imm × $2^{20}$ + rd × $2^7$ + 0x13.
:::
:::

::: check
given: u = 4096..65535 int; l = 2048..4095 int; let v = u*4096 + l; let m = l - 4096
answer: u + 1
base: 16
width: 5

## The assembler splits `li a0, 0x{v:hex8}` into `lui` and `addi`. What 20-bit value does `lui` load?

::: right
Right: 0x{answer}. The low 12 bits, 0x{l:hex3}, have bit 11 set, so `addi` reads them as {m}. `lui` loads one more to make up for it.
:::

::: misses
- [u] Those are the top 20 bits as written, but `addi` sign-extends 0x{l:hex3} to {m}, so the upper part needs one more.
- [any] Not yet. Take the top 20 bits, then add 1 if the low 12 bits are 0x800 or more.
:::
:::

::: check
kind: choice

## `mv a0, a1` is a pseudo-instruction. Which real instruction does the assembler write for it?

- [x] `addi a0, a1, 0`
- [ ] `add a0, a1, a1`
- [ ] `lw a0, 0(a1)`
- [ ] `sub a0, a0, a1`

::: right
Right. Adding 0 copies the register.
:::

::: misses
- [2] That doubles a1.
- [3] That loads from memory at the address in a1.
- [4] That subtracts.
:::
:::

::: check
given: b = 5 | 8 | 12 | 13
answer: 2^(b - 1) - 1
tolerance: 0

## What's the largest value a signed {b}-bit immediate can hold?

::: right
Right: {answer}. A signed b-bit field runs from $-2^{b-1}$ to $2^{b-1} - 1$.
:::

::: misses
- [2^b - 1] That's the unsigned range. Signed loses a bit to the sign.
- [2^(b - 1)] One less: the positive side ends just below $2^{b-1}$.
- [any] Not yet. $2^{b-1} - 1$.
:::
:::

::: check
kind: asm
given: n = -1000..-1 int; k = 1..4 int
setup: a0 = n; a1 = k
expect: a2 = floor(n/2^k)

## a0 holds a negative number and a1 a shift amount. Put a0 shifted right arithmetically by a1 into a2.

```asm starter
    srl a2, a0, a1
    ebreak
```

```asm solution
    sra a2, a0, a1
    ebreak
```

::: right
Right. `sra` copies the sign bit in, so the result stays negative: division by $2^k$ rounded toward −∞.
:::
:::

::: check
kind: parts
given: v = 7 | 99 | 1001; k = 1 | 2 | 3

## t0 holds −{v} and is shifted right by {k}.

::: part
answer: -ceil(v/2^k)
tolerance: 0

### What does `srai` give?

::: misses
- [-v/2^k] For a value that doesn't divide evenly, `srai` rounds toward −∞.
- [any] Divide by $2^k$ and round down.
:::
:::

::: part
answer: floor((2^32 - v)/2^k)
tolerance: 0

### What does `srli` give, as an unsigned number?

::: misses
- [any] Treat the pattern as $2^{32} - v$ and divide by $2^k$, rounding down.
:::
:::
:::

::: explain
## Why does RISC-V need two instructions to put an arbitrary 32-bit constant in a register?

::: model
Every RISC-V instruction is exactly 32 bits, and some of those bits have to say what the instruction is (the opcode) and where the result goes (the destination register). That leaves at most 20 bits for a constant, so a full 32-bit value can't fit. Instead `lui` loads the upper 20 bits and `addi` adds the lower 12. The designers chose fixed-width instructions because they make fetching and decoding simple and fast, and most constants in real programs are small enough for one instruction anyway.
:::
:::

::: practice

::: check
kind: asm
given: k = 3 | 9 | 17; n = 2..500 int
setup: a0 = n
expect: a1 = k*n

## With n in a0, put {k} × n in a1 using shifts and adds.

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

```asm solution
    li t1, k
    addi t1, t1, -1     # k - 1 is a power of 2
    li a1, 0
    li t2, 0
find:
    srli t3, t1, 1
    beqz t3, done
    mv t1, t3
    addi t2, t2, 1
    j find
done:
    sll a1, a0, t2      # n shifted by log2(k - 1)
    add a1, a1, a0
    ebreak
```

::: misses
- [any] {k} is a power of 2 plus 1: shift, then add n.
:::
:::

::: check
given: b = 6 | 10 | 12 | 20
answer: -(2^(b - 1))
tolerance: 0

## Smallest value of a signed {b}-bit field?

::: misses
- [any] $-2^{b-1}$.
:::
:::

::: check
given: rd = 1..31 int; imm = 1..2047 int
answer: imm*1048576 + rd*128 + 19
base: 16
width: 8

## `addi x{rd}, x0, {imm}` in hex?

::: misses
- [any] imm × $2^{20}$ + rd × $2^7$ + 0x13.
:::
:::

::: check
given: x = 1..100 int; s = 1..4 int
answer: x*2^s
tolerance: 0

## t0 holds {x}. What does `slli t1, t0, {s}` put in t1?

::: misses
- [x*s] A shift left by one place doubles.
- [floor(x/2^s)] That's a right shift.
- [any] {x} × $2^\given{s}$.
:::
:::
:::
