---
title: Fetch, decode, execute
heading: How a processor runs a program
eyebrow: C8 · Lesson 1 · Fetch, decode, execute
xp: 50
---

::: hook
A processor is built from the parts of C7. A register called the program counter (PC) holds the address of the next instruction. A memory holds the instructions. A register file holds 32 working values. An ALU adds, subtracts, compares and does bitwise logic. Multiplexers choose which value goes where. Every instruction goes through the same cycle: fetch the instruction word at the PC, decode its fields, compute in the ALU, maybe read or write data memory, write the result back, and move the PC on. Below, a small RISC-V processor runs a short program, and the datapath lights every wire the last instruction used.

::: play
- Press Step. Each press runs one instruction, and the datapath shows the one that just ran.
- Compare `addi` with `lw` (load word) and `sw` (store word). Which units does each one use?
- Watch the PC. How much does it go up by on each step, and when does it jump instead?
:::
:::

```sim cpu
    li t0, 0x1000     # t0 holds an address in data memory
    li t1, 3          # t1 counts down the passes
loop:
    lw t2, 0(t0)      # load the word at that address
    addi t2, t2, 5    # add 5 to it
    sw t2, 0(t0)      # store it back
    addi t1, t1, -1   # one fewer pass to go
    bnez t1, loop     # go round again until t1 is 0
    ebreak
show: t0, t1, t2
hex: t0
memory: 0x1000..0x1008
view: datapath
```

::: predict
## The loop starts at address 0x08, and its last instruction, `bnez`, sits at 0x18. When that branch is taken, what does the PC hold next?

- [ ] 0x1C, the next instruction
- [x] 0x08, the start of the loop
- [ ] 0x18, the branch itself
- [ ] 0x00, the start of the program

::: reveal
0x08. A taken branch loads the PC with the address of its label. The instruction stores that as an offset from its own address: here 0x08 − 0x18 = −16 bytes. When the branch isn't taken (on the last pass, when t1 has reached 0), the PC goes on to 0x1C as usual.
:::
:::

::: nameit
## The instruction cycle

Each instruction is one 32-bit word, 4 bytes, and memory is addressed in bytes. So the PC normally goes up by 4.

1. **Fetch.** Read the word at the address in the PC from instruction memory.
2. **Decode.** Split the word into fields: the operation (the opcode), up to three register numbers (5 bits each, enough to pick one of 32 registers) and an immediate, a constant built into the instruction. Control logic turns the opcode into the select lines of the multiplexers and the ALU's operation.
3. **Execute.** The ALU works on two operands: two registers, or a register and the immediate. For a load or store it adds the base register and the offset to get the address. For a branch it compares the two registers.
4. **Memory.** A load reads data memory at that address; a store writes it.
5. **Write back.** The result goes into the destination register.
6. **Next PC.** PC + 4, or the branch target when a branch is taken.

In the simplest design, the **single-cycle processor**, all of this happens in one clock period. The PC is a register, and everything between its output and its input is combinational logic, the register-and-logic pattern of C7. The time a program takes is

$$t = \frac{N \cdot \text{CPI}}{f}$$

for N instructions, CPI clock cycles per instruction (1 here) and clock frequency f.
:::


::: example
## A program runs 3 million instructions on a single-cycle processor at 50 MHz. How long does it take?

::: solution
1. **Cycles per instruction.** On a single-cycle processor, CPI is 1.
2. **Run time.** Divide the cycles by the clock rate:
   $$\begin{aligned} t &= \frac{3 \times 10^6}{50 \times 10^6}\ \text{s} \\ &= 0.06\ \text{s} \\ &= 60\ \text{ms} \end{aligned}$$

**Answer:** the program takes 0.06 s, which is 60 ms.
:::
:::

::: example
## Follow `addi t0, t0, 4` through the cycle.

::: solution
1. **Fetch.** Fetch reads the word at the PC.
2. **Decode.** Decode finds an I-type arithmetic instruction with rs1 = rd = t0 and the immediate 4, and reads t0.
3. **Execute.** The ALU adds t0 and 4.
4. **Memory.** The memory step does nothing.
5. **Write back.** Write back puts the sum in t0, and the PC moves on by 4.

**Answer:** fetch reads the word, decode reads t0 and the immediate 4, the ALU adds them, the memory step does nothing, and write back puts the sum in t0 while the PC moves on by 4.
:::
:::

::: example
## A multi-cycle processor runs at 200 MHz, taking 5 cycles for loads and 4 for everything else. A program of 3 million instructions is 25% loads. How long does it take, against the single-cycle machine's 60 ms at 50 MHz?

::: solution
1. **Average cycles per instruction.**
   $$\begin{aligned} \text{CPI} &= 0.25 \times 5 + 0.75 \times 4 \\ &= 4.25 \end{aligned}$$
2. **Run time.**
   $$\begin{aligned} t &= \frac{3 \times 10^6 \times 4.25}{200 \times 10^6}\ \text{s} \\ &= 63.75\ \text{ms} \end{aligned}$$
3. **Compare with the single-cycle machine.** It is slightly slower than the 60 ms, despite a clock four times as fast: each instruction takes several short cycles instead of one long one.
4. **The general rule.** The time is always instructions × CPI ÷ clock rate, and improving one factor helps only if the others don't worsen as much.

**Answer:** 63.75 ms, slightly slower than the single-cycle machine's 60 ms.
:::
:::

::: check
given: p = 0..200 int; k = 2..9 int; let a = 4*p
answer: a + 4*k
base: 16
width: 4

## The PC holds 0x{a:hex4}. With no branches taken, what does it hold after {k} more instructions?

::: right
Right: 0x{answer}. Each instruction is 4 bytes, so the PC goes up by 4 each time.
:::

::: misses
- [a + k] Memory is addressed in bytes, and each instruction takes 4 of them.
- [any] Not yet. Add 4 for each instruction, in hex.
:::
:::

::: check
kind: choice

## In the program above, which instructions use the data memory?

- [ ] All of them
- [ ] `addi` and `li`
- [x] `lw` and `sw`
- [ ] `bnez`

::: right
Right. Only loads and stores touch data memory. Everything else works on registers.
:::

::: misses
- [1] Every instruction is fetched from instruction memory, but only loads and stores read or write data memory.
- [2] Those work on registers and an immediate.
- [4] A branch compares registers and changes the PC.
:::
:::

::: check
given: n = 8 | 16 | 32 | 64
answer: round(log(n)/log(2))
tolerance: 0

## A processor has {n} registers. How many bits does an instruction need to name one of them?

::: right
Right: {answer} bits, since $2^{\text{bits}}$ must reach {n}. RISC-V has 32 registers, so its register fields are 5 bits wide.
:::

::: misses
- [n] That's how many registers there are. The answer is how many bits it takes to write a register's number.
- [any] Not yet. Find the number of bits b with $2^b$ = {n}.
:::
:::

::: check
kind: order

## Put the steps of a load instruction (`lw t2, 0(t0)`) in order.

1. Fetch the instruction word at the address in the PC
2. Decode the opcode and the register fields
3. Read t0 from the register file
4. Add t0 and the offset in the ALU
5. Read data memory at that address
6. Write the word into t2

::: right
Right. A load uses every unit, which makes it the slowest instruction in a single-cycle design.
:::
:::

::: check
given: d = 2 | 2.5 | 4 | 5 | 8
answer: 1000/d
unit: MHz
tolerance: 0.5%

## A single-cycle processor's slowest instruction takes {d} ns to settle from one clock edge to the next. What's the fastest clock it can use?

::: right
Right: {answer}. Every instruction gets the same clock period, so the slowest one sets it.
:::

::: misses
- [d] Turn the period into a frequency: $f = 1/T$.
- [any] Not yet. $f = 1/T$, with T = {d} ns.
:::
:::

::: check
given: N = 200 | 500 | 800; f = 50 | 100 | 200
answer: N/f
unit: ms
tolerance: 0.5%

## A single-cycle processor (CPI = 1) at {f} MHz runs a program of {N} thousand instructions. How long does it take?

::: right
Right: {answer}.
:::

::: misses
- [N*f/1000] Divide the instruction count by the clock rate.
- [any] Not yet. $t = N \cdot \text{CPI}/f$.
:::
:::

::: check
kind: parts
given: N = 1 | 5 | 20; f = 50 | 200 | 500; L = 20 | 30; cl = 5 | 6; co = 3 | 4

## A multi-cycle processor at {f} MHz takes {cl} cycles for loads ({L}% of instructions) and {co} for the rest, running {N} million instructions.

::: part
answer: L/100*cl + (1 - L/100)*co
tolerance: 0.5%

### What's its average CPI?

::: misses
- [any] Weight each class's cycles by its share.
:::
:::

::: part
answer: N*1e6*(L/100*cl + (1 - L/100)*co)/(f*1e6)*1000
unit: ms
tolerance: 0.5%

### How long does the program take?

::: misses
- [any] Instructions × CPI ÷ clock rate.
:::
:::
:::

::: check
kind: derivation
vars: N = 1000..10000000000, c = 0.5..10, f = 1000000..5000000000

## A program of N instructions runs at an average CPI of c on a clock of frequency f.

::: step
answer: N*c/f

### How long does it take?
:::

::: step
answer: f/c

### How many instructions per second?
:::

::: step
answer: N*c/f/2

### How long would it take if the clock doubled with no change in CPI?
:::

::: right
Right. The iron law: time = instructions × CPI ÷ frequency.
:::
:::

::: explain
## Why does a single-cycle processor's clock period have to be long enough for its slowest instruction?

::: model
The clock doesn't know which instruction is running, so every instruction gets the same period. Between two edges, the new instruction's signals have to travel from the PC through instruction memory, the register file, the ALU and, for a load, data memory, and then settle at the register file's input before the next edge writes it. If the period were shorter than a load's path, the register would capture a value that hadn't finished arriving. So the slowest path sets the clock for everything, which is the waste that pipelining (lesson 39) recovers.
:::
:::

::: practice

::: check
given: p = 0..120 int; k = 3..12 int; let a = 4*p
answer: a + 4*k
base: 16
width: 4

## The PC is 0x{a:hex4}. After {k} instructions with no branch, the PC?

::: misses
- [a + k] 4 bytes per instruction.
- [any] Add 4k.
:::
:::

::: check
given: k = 1 | 4 | 16 | 64
answer: round(log(1024*k)/log(2))
tolerance: 0

## How many address bits does a memory of {k} KiB (1 KiB = 1024 bytes) need?

::: misses
- [round(log(k)/log(2))] Count bytes: {k} × 1024 of them.
- [any] Find b with $2^b$ = {k} × 1024.
:::
:::

::: check
given: d = 1.25 | 2 | 3.2 | 10
answer: 1000/d
unit: MHz
tolerance: 0.5%

## A single-cycle CPU's longest path is {d} ns. Fastest clock?

::: misses
- [any] $f = 1/T$.
:::
:::

::: check
given: N = 10 | 40 | 60; c = 1.5 | 2 | 3; f = 20 | 50
answer: N*c/f
unit: ms
tolerance: 0.5%

## {N} thousand instructions at a CPI of {c} on a {f} MHz clock. Run time?

::: misses
- [N/f] Multiply by the CPI too.
- [any] $t = N \cdot \text{CPI}/f$.
:::
:::
:::
