---
title: "Capstone: a tiny CPU that runs C8's instruction set"
heading: A single-cycle RISC-V core described as hardware, the datapath of program counter, register file, ALU and memory, the decoder that pulls fields and immediates out of each instruction, the controller that sets the multiplexers, and a cycle-accurate model in Python that runs a real program
eyebrow: D10 · Lesson 13 · Capstone
xp: 80
---

::: hook
C8 taught RISC-V from the programmer's side: instructions, registers and memory. This capstone builds the other side, the hardware that executes those instructions. A single-cycle core does an entire instruction every clock: fetch it from memory, decode its fields, read two registers, compute with the ALU, touch data memory if needed, and write the result back, all before the next edge. It's the datapath-and-controller design of lesson 3 at full size, and its Verilog fits on two pages. Here you'll model it cycle by cycle in Python and run a real program on it, checked against the reference simulator below.
:::

::: play
- The program the core will run, on the course's RISC-V simulator: it points a0 at the data area (0x1000), sums 10 + 9 + ... + 1 into t1, stores and reloads it, and then exercises slt, sub, and and or before halting with a jump to itself.
- Step through it and watch the registers. Your Python core must end in exactly the same state, after the same 39 instructions.
- Each instruction here takes one clock on a single-cycle core.
:::

```sim cpu
.text
    lui  a0, 1
    addi t0, zero, 10
    addi t1, zero, 0
loop:
    add  t1, t1, t0
    addi t0, t0, -1
    bne  t0, zero, loop
    sw   t1, 0(a0)
    lw   t2, 0(a0)
    slt  t3, t0, t2
    sub  t4, t2, t3
    and  t5, t4, t2
    or   t6, t4, t3
    jal  zero, 0
show: t0, t1, t2, t3, t4, t5, t6
hex: a0
memory: 0x1000..0x1004
forever: on
speed: 4
```

::: predict
## A single-cycle core's slowest instruction (lw) needs 0.3 ns to fetch, 0.2 ns to decode, 1.0 ns to read registers and compute the address, 1.2 ns of data memory, 0.3 ns of multiplexing and 0.2 ns to write back. What's its fastest clock?

- [ ] 1 GHz
- [x] About 313 MHz
- [ ] About 833 MHz
- [ ] 3.2 GHz

::: reveal
Everything for the slowest instruction must fit in one cycle: 0.3 + 0.2 + 1.0 + 1.2 + 0.3 + 0.2 = 3.2 ns, so 312.5 MHz, even though an add needs much less. That waste is why real cores are pipelined (lesson 9, C8): split into five stages, the clock could approach the slowest stage, 1.2 ns plus overhead.
:::
:::

::: nameit
## The datapath

- A **program counter** register, incremented by 4 or loaded with a branch or jump target.
- **Instruction memory** read at the PC.
- A **register file** of 32 × 32 bits with two read ports and one write port; x0 always reads 0.
- An **immediate generator** that assembles and sign-extends the immediate for each format: I (12 bits from 31:20), S (31:25 and 11:7), B (a 13-bit offset with bit 0 zero), J (a 21-bit offset).
- An **ALU** selected by funct3 and funct7: add or subtract, and, or, set-less-than.
- **Data memory** for lw and sw, and a write-back multiplexer choosing the ALU result, the loaded word or PC + 4.

## The controller

A decoder maps the opcode to control signals: whether to write a register, use the immediate as the ALU's second operand, read or write memory, branch, or jump. In Verilog it's a combinational `always @(*)` with a `case` on the opcode (lesson 5).

## The Verilog

```verilog
always @(posedge clk) begin
  pc <= next_pc;
  if (reg_write && rd != 0) regs[rd] <= wb_value;
  if (mem_write) dmem[alu_out[31:2]] <= regs[rs2];
end
assign next_pc = jump ? pc + imm_j
               : (branch && taken) ? pc + imm_b
               : pc + 4;
```

## Running it

A single-cycle core has a CPI of exactly 1, so a program's time is its instruction count times the clock period: 39 instructions at 50 MHz take 780 ns.
:::

::: example
## Pull the fields out of `add t1, t1, t0`, encoded 0x00530333.

::: solution
1. **Opcode.** Bits 6:0 are 0x33, an R-type instruction.
2. **Destination.** rd = bits 11:7 = 6 (t1).
3. **Sources.** rs1 = bits 19:15 = 6 (t1) and rs2 = bits 24:20 = 5 (t0).
4. **Function codes.** funct3 = 0 and funct7 = 0, so the instruction is add (a funct7 of 0x20 would be sub).

**Answer:** opcode 0x33 (R-type), rd = 6, funct3 = 0, rs1 = 6, rs2 = 5 and funct7 = 0: an add.
:::
:::

::: example
## Why does the loop run 30 instructions, and how many does the whole program run?

::: solution
1. **The loop.** The body (add, addi, bne) runs once for each value of t0 from 10 down to 1:
   $$3 \times 10 = 30$$
2. **The whole program.** Add 3 instructions to set up and 6 after the loop:
   $$3 + 30 + 6 = 39$$
   before it reaches the self-jump that halts it.

**Answer:** the loop runs 30 instructions, and the whole program 39.
:::
:::

::: example
## The single-cycle core runs at 50 MHz. How long does the 39-instruction program take?

::: solution
1. **One instruction per cycle.** At 50 MHz each cycle lasts 20 ns.
2. **Run time.**
   $$\begin{aligned} t &= 39 \times 20\ \text{ns} \\ &= 0.78\ \mu\text{s} \end{aligned}$$
3. **A pipeline.** A five-stage pipeline could clock faster, but taken branches and the loop's dependent instructions would add stalls.

**Answer:** 0.78 µs.
:::
:::

::: check
kind: python

## Build the core: decode instructions, execute them, and run the program.

```python starter
def sext(x, bits):
    # Sign-extend a bits-wide field to a Python int.
    return x - (1 << bits) if x >> (bits - 1) & 1 else x

def decode(w):
    # Split a 32-bit RV32I instruction into its fields: return a dict with opcode, rd, funct3,
    # rs1, rs2, funct7 and imm, where imm is the sign-extended immediate for the instruction's
    # type: I (opcode 0x13 and loads 0x03), S (stores 0x23), B (branches 0x63), J (jal 0x6f),
    # U (lui 0x37: the top 20 bits, already shifted into place), and 0 for R-type (0x33).
    return {"opcode": w & 0x7f, "rd": 0, "funct3": 0, "rs1": 0, "rs2": 0, "funct7": 0, "imm": 0}

def step(pc, regs, mem, w):
    # Execute one instruction w at address pc on 32 registers (x0 always 0) and a dict of
    # word-addressed memory. Support lui, addi, add, sub, and, or, slt, lw, sw, beq, bne and jal.
    # Return the next pc. Keep register values as 32-bit two's complement Python ints.
    return pc + 4

def run(words, max_steps=1000):
    # Load words at address 0 and run from pc 0 until an instruction jumps to itself.
    # Return (regs, mem, instructions executed, not counting the final self-jump).
    regs = [0]*32
    return regs, {}, 0
```

```python solution
def sext(x, bits):
    return x - (1 << bits) if x >> (bits - 1) & 1 else x

def decode(w):
    op = w & 0x7f
    d = {"opcode": op, "rd": (w >> 7) & 31, "funct3": (w >> 12) & 7, "rs1": (w >> 15) & 31,
         "rs2": (w >> 20) & 31, "funct7": w >> 25, "imm": 0}
    if op in (0x13, 0x03):
        d["imm"] = sext(w >> 20, 12)
    elif op == 0x23:
        d["imm"] = sext(((w >> 25) << 5) | ((w >> 7) & 31), 12)
    elif op == 0x63:
        d["imm"] = sext(((w >> 31) << 12) | (((w >> 7) & 1) << 11) | (((w >> 25) & 63) << 5) | (((w >> 8) & 15) << 1), 13)
    elif op == 0x37:
        d["imm"] = sext(w & 0xfffff000, 32)
    elif op == 0x6f:
        d["imm"] = sext(((w >> 31) << 20) | (((w >> 12) & 255) << 12) | (((w >> 20) & 1) << 11) | (((w >> 21) & 1023) << 1), 21)
    return d

def _w32(x):
    return sext(x & 0xffffffff, 32)

def step(pc, regs, mem, w):
    d = decode(w)
    op, rd, f3, a, b, imm = d["opcode"], d["rd"], d["funct3"], regs[d["rs1"]], regs[d["rs2"]], d["imm"]
    nxt = pc + 4
    val = None
    if op == 0x37:
        val = imm
    elif op == 0x13 and f3 == 0:
        val = a + imm
    elif op == 0x33:
        if f3 == 0:
            val = a - b if d["funct7"] == 0x20 else a + b
        elif f3 == 7:
            val = a & b
        elif f3 == 6:
            val = a | b
        elif f3 == 2:
            val = 1 if a < b else 0
    elif op == 0x03:
        val = mem.get(a + imm, 0)
    elif op == 0x23:
        mem[a + imm] = b
    elif op == 0x63:
        if (f3 == 0 and a == b) or (f3 == 1 and a != b):
            nxt = pc + imm
    elif op == 0x6f:
        val = pc + 4
        nxt = pc + imm
    if val is not None and rd != 0:
        regs[rd] = _w32(val)
    return nxt

def run(words, max_steps=1000):
    regs = [0]*32
    mem = {}
    pc, n = 0, 0
    while n < max_steps:
        nxt = step(pc, regs, mem, words[pc//4])
        if nxt == pc:
            break
        pc, n = nxt, n + 1
    return regs, mem, n
```

```python tests
_prog = [0x00001537, 0x00a00293, 0x00000313, 0x00530333, 0xfff28293, 0xfe029ce3, 0x00652023,
         0x00052383, 0x0072ae33, 0x41c38eb3, 0x007eff33, 0x01ceefb3, 0x0000006f]
_d = decode(0x00a00293)
assert _d["opcode"] == 0x13 and _d["rd"] == 5 and _d["rs1"] == 0 and _d["imm"] == 10, f"addi t0, zero, 10 decodes as opcode 0x13, rd 5, rs1 0, imm 10; got {_d}."
assert decode(0xfff28293)["imm"] == -1, "addi t0, t0, -1 has immediate -1: sign-extend it."
assert decode(0xfe029ce3)["imm"] == -8, "The bne back to the loop has a B-type offset of -8."
assert decode(0x00652023)["imm"] == 0 and decode(0x00652023)["rs2"] == 6 and decode(0x00652023)["rs1"] == 10, "sw t1, 0(a0) is S-type with offset 0, rs1 = a0 (10) and rs2 = t1 (6)."
assert decode(0x00001537)["imm"] == 4096 and decode(0x00001537)["rd"] == 10, "lui a0, 1 puts 1 << 12 = 4096 into a0."
assert decode(0x0000006f)["imm"] == 0, "jal zero, 0 jumps to itself."
_r, _m, _n = run(_prog)
assert _r[10] == 4096 and _r[6] == 55 and _m.get(4096) == 55 and _r[7] == 55, f"The loop should sum 10 + 9 + ... + 1 = 55 into t1, store it at 0x1000 and load it into t2; got t1 = {_r[6]}, mem[0x1000] = {_m.get(4096)}, t2 = {_r[7]}."
assert (_r[28], _r[29], _r[30], _r[31]) == (1, 54, 54, 55), f"slt, sub, and, or should leave t3..t6 = 1, 54, 54, 55; got {_r[28:32]}."
assert _r[0] == 0 and _r[5] == 0, "x0 stays 0, and the counter t0 ends at 0."
assert _n == 39, f"The program runs 39 instructions before halting; got {_n}."
```

::: right
Right. Your core runs the 39 instructions and ends with t1 = 55, t3 to t6 = 1, 54, 54, 55, matching the reference simulator.
:::
:::

::: check
given: w = 0x00a00293 | 0x00530333 | 0x0072ae33 | 0x41c38eb3
answer: floor(w/128) - 32*floor(w/4096)
tolerance: 0.4

## Which register does the instruction {w:hex8} write? (rd is bits 11:7.)

::: right
Right. rd = {answer}.
:::

::: misses
- [any] Not yet. Shift right by 7 and keep five bits.
:::
:::

::: check
given: n = 5 | 10 | 100; s = 2 | 6
answer: s + 3*n + 6
tolerance: 0.4

## A program spends {s} instructions setting up, runs a 3-instruction loop {n} times and then 6 more instructions. How many instructions does it execute?

::: right
Right. {s} + 3 × {n} + 6 = {answer}.
:::

::: misses
- [3*n] Count the setup and the code after the loop.
- [any] Not yet. Add up each part.
:::
:::

::: check
given: N = 39 | 1000 | 50000; f = 25 | 50 | 100
answer: N*1000/f
unit: ns
tolerance: 0.5%

## A single-cycle core runs {N} instructions at {f} MHz. How long does it take?

::: right
Right. CPI 1: {answer} ns.
:::

::: misses
- [any] Not yet. Instructions times the clock period.
:::
:::

::: check
given: a = 0.2 | 0.3; b = 0.8 | 1; c = 0.8 | 1.2 | 2
answer: 1000/(a + 0.2 + b + c + 0.3 + 0.2)
unit: MHz
tolerance: 0.5%

## A single-cycle lw takes {a} ns to fetch, 0.2 ns to decode, {b} ns for registers and the ALU, {c} ns of data memory, 0.3 ns of multiplexing and 0.2 ns to write back. What's the fastest clock?

::: right
Right. One over the whole chain: {answer} MHz.
:::

::: misses
- [1000/c] Every step of the instruction is in the same cycle.
- [any] Not yet. Add the delays.
:::
:::

::: check
kind: parts
given: n = 39 | 100 | 1000; f = 25 | 50 | 100

## A single-cycle core runs {n} instructions at {f} MHz.

::: part
answer: n/f
unit: µs
tolerance: 0.5%

### How long does it take?

::: misses
- [any] Instructions × period.
:::
:::

::: part
answer: n/f*1.3/1.5
unit: µs
tolerance: 0.5%

### A pipelined version clocks 1.5 times faster but needs a CPI of 1.3. How long does it take?

::: misses
- [any] × CPI ÷ speedup.
:::
:::
:::

::: check
kind: parts
given: k = 3 | 5; b = 4 | 10 | 20

## A loop body of {k} instructions runs {b} times, after 3 setup instructions and before 6 more.

::: part
answer: 3 + k*b + 6
tolerance: 0

### How many instructions run in all?

::: misses
- [any] Setup + body × iterations + the rest.
:::
:::

::: part
answer: k*b/(3 + k*b + 6)*100
unit: %
tolerance: 0.5%

### What share is the loop?

::: misses
- [any] Loop ÷ total.
:::
:::
:::

::: explain
## Why is a single-cycle CPU simple to design but slow to run?

::: model
A single-cycle core finishes every instruction within one clock period, so it needs no pipeline registers, no hazard detection and no forwarding: each instruction simply flows through fetch, decode, register read, ALU, memory and write-back before the next edge, and the controller is one combinational decoder. But the clock must be long enough for the slowest instruction, usually a load, which passes through both instruction and data memory, so simple instructions like add waste most of every cycle waiting. Pipelining splits that path into stages so different instructions overlap, letting the clock run several times faster at the cost of the hazards that C8 and S4 deal with.
:::
:::

::: practice

::: check
given: N = 10 | 1000000; f = 10 | 500
answer: N*1000/f
unit: ns
tolerance: 0.5%

## Run time: {N} instructions at {f} MHz, CPI 1?

::: misses
- [any] N/f.
:::
:::

::: check
given: w = 0x00a00293 | 0x00000313 | 0x00530333 | 0xfff28293 | 0x00052383 | 0x0072ae33 | 0x41c38eb3 | 0x007eff33
answer: floor(w/32768) - 32*floor(w/1048576)
tolerance: 0.4

## rs1 (bits 19:15) of {w:hex8}?

::: misses
- [any] Shift right by 15, keep five bits.
:::
:::
:::
