---
title: "Architecture lab: a Tomasulo timing simulator"
heading: Renaming, dataflow timing and a limited common data bus, checked against reference simulators
eyebrow: S4 · Lesson 49 · Architecture lab
xp: 60
---

::: hook
Lesson 9 traced Tomasulo's algorithm by hand. Architects explore designs like it with timing simulators: programs that take an instruction trace and a machine description and compute when every instruction issues, executes and writes its result. In this lab you'll write one in three steps: first the renaming that finds each instruction's true producers, then the pure dataflow timing that renaming makes possible, then the effect of a single common data bus that can broadcast only one result per cycle. The tests compare your simulator with independently written reference simulators on random programs.
:::

::: predict
## In the example program below, instruction 3 writes f0 again while instruction 1 still needs the old f0. With renaming, when can instruction 3 start executing?

- [ ] Only after instruction 1 has read f0
- [ ] Only after instruction 2 finishes
- [x] As soon as it has issued: it has no true dependence
- [ ] Never before instruction 1 writes

::: reveal
As soon as it has issued. Instruction 3 is a load with no source registers; its only conflicts with earlier instructions are on the *name* f0 (a WAW with instruction 0 and a WAR with instruction 1). Renaming gives its result a new tag, so it starts in cycle 4, right after issuing in cycle 3, and writes in cycle 6, while instruction 1, issued earlier, is still waiting for its multiply to finish.
:::
:::

::: nameit
## The program format

A program is a list of `(op, dest, sources)`:

```python
EX = [('ld', 'f0', []),               # 0
      ('mul', 'f4', ['f0', 'f2']),    # 1
      ('add', 'f6', ['f4', 'f8']),    # 2
      ('ld', 'f0', []),               # 3
      ('add', 'f2', ['f0', 'f0'])]    # 4
LAT = {'add': 1, 'mul': 4, 'ld': 2, 'div': 10}
```

Registers never written in the program (f2 and f8 at first) are ready from the start.

## The timing rules

- **Producers:** for each source, the latest earlier instruction whose destination is that register. Later writes to the same name don't matter (renaming).
- **Issue:** in order, `width` per cycle: instruction i issues in cycle `i // width`, into an unlimited supply of reservation stations.
- **Execute:** an instruction starts in the first cycle that's after its issue cycle and after every producer's write cycle, and runs `lat[op]` cycles; its result is ready to write `lat[op]` cycles after it starts.
- **Write:** with an unlimited bus, at once. With `buses` buses, each cycle the oldest ready results are written, at most `buses` of them; the rest wait. A result written in cycle w can be used from cycle w + 1.

## What you'll write

1. `deps(prog)`: for each instruction, the sorted list of producer indices.
2. `schedule(prog, lat, width=1)`: each instruction's write cycle with an unlimited bus.
3. `schedule_cdb(prog, lat, width=1, buses=1)`: write cycles with a limited bus. Simulate cycle by cycle: start every instruction that can start, then write the oldest ready results.
:::

::: example
## Work out the example's write cycles with one issue per cycle and an unlimited bus.

::: solution
1. **Issue.** With one issue per cycle, instructions 0 to 4 issue in cycles 0 to 4.
2. **Instruction 0 (load).** It starts in cycle 1 and writes in 3.
3. **Instruction 1.** It waits for 0: starts in 4, writes in 8.
4. **Instruction 2.** It waits for 1: starts in 9, writes in 10.
5. **Instruction 3.** It has no producers: starts in 4, writes in 6.
6. **Instruction 4.** It waits for 3: starts in 7, writes in 8.
7. **Two issues per cycle.** Instructions 3 and 4 issue two cycles earlier, in cycles 1 and 2, and write in 4 and 6.

**Answer:** the write cycles are [3, 8, 10, 6, 8]; with two issues per cycle they become [3, 8, 10, 4, 6].
:::
:::

::: example
## With a single common data bus, what changes?

::: solution
1. **The clash.** In cycle 8, instructions 1 and 4 both have results ready.
2. **Oldest first.** The older one, 1, takes the bus, and 4 writes in cycle 9.
3. **Instruction 2.** It needed only instruction 1, so it's unaffected.
4. **In larger programs.** In larger random programs, the single bus changed the timing of 39 out of 40 four-wide runs, which is why wide machines have several result buses.

**Answer:** instruction 4 now writes in cycle 9 instead of 8, so the write cycles are [3, 8, 10, 6, 9].
:::
:::

::: check
kind: python

## Step 1. Write `deps(prog)`: each instruction's true producers.

```python starter
def deps(prog):
    # prog: list of (op, dest, [sources]). For each instruction, return the sorted
    # indices of the earlier instructions that produce its sources (the latest writer of each).
    return [[] for _ in prog]

EX = [('ld', 'f0', []), ('mul', 'f4', ['f0', 'f2']), ('add', 'f6', ['f4', 'f8']), ('ld', 'f0', []), ('add', 'f2', ['f0', 'f0'])]
print(deps(EX))
```

```python solution
def deps(prog):
    last = {}
    out = []
    for i, (op, dest, srcs) in enumerate(prog):
        out.append(sorted({last[s] for s in srcs if s in last}))
        last[dest] = i
    return out

EX = [('ld', 'f0', []), ('mul', 'f4', ['f0', 'f2']), ('add', 'f6', ['f4', 'f8']), ('ld', 'f0', []), ('add', 'f2', ['f0', 'f0'])]
print(deps(EX))
```

```python tests
import random
LAT = {'add': 1, 'mul': 4, 'ld': 2, 'div': 10}
EX = [('ld', 'f0', []), ('mul', 'f4', ['f0', 'f2']), ('add', 'f6', ['f4', 'f8']), ('ld', 'f0', []), ('add', 'f2', ['f0', 'f0'])]
def rand_prog(seed, n=14, regs=6):
    rng = random.Random(seed)
    names = [f'r{k}' for k in range(regs)]
    prog = []
    for _ in range(n):
        op = rng.choice(['add', 'add', 'mul', 'ld', 'div'])
        srcs = [] if op == 'ld' else [rng.choice(names), rng.choice(names)]
        prog.append((op, rng.choice(names), srcs))
    return prog
def ref_deps(prog):
    out = []
    for i, (op, dest, srcs) in enumerate(prog):
        ps = set()
        for s in srcs:
            for j in range(i - 1, -1, -1):
                if prog[j][1] == s:
                    ps.add(j)
                    break
        out.append(sorted(ps))
    return out
def ref_sim(prog, lat, width, buses):
    # event-driven reference: process cycle by cycle, tracking which register values are on the bus
    n = len(prog); dp = ref_deps(prog)
    state = ['wait'] * n; fin = [0] * n; wr = [None] * n; t = 0
    while any(w is None for w in wr):
        for i in range(n):
            if state[i] == 'wait' and i // width < t and all(wr[p] is not None and wr[p] <= t - 1 for p in dp[i]):
                state[i] = 'run'; fin[i] = t + lat[prog[i][0]]
        cand = sorted(i for i in range(n) if state[i] == 'run' and fin[i] <= t)
        for i in cand[:buses]:
            wr[i] = t; state[i] = 'done'
        t += 1
    return wr
assert deps(EX) == [[], [0], [1], [], [3]], f"For the example, the producers are [[], [0], [1], [], [3]]; got {deps(EX)}."
assert deps([('add', 'r1', ['r1', 'r1']), ('add', 'r1', ['r1', 'r2'])]) == [[], [0]], "An instruction that reads and writes the same register depends only on the earlier writer."
for seed in range(40):
    p = rand_prog(seed)
    assert deps(p) == ref_deps(p), f"Random program {seed}: producers should be {ref_deps(p)}; got {deps(p)}."
```

::: right
Right. Keeping only the latest writer of each register is renaming: every later reader is tied to a value, and the false WAR and WAW dependences never appear.
:::
:::

::: check
kind: python

## Step 2. Write `schedule(prog, lat, width)`: write cycles with an unlimited result bus.

```python starter
def deps(prog):
    last = {}
    out = []
    for i, (op, dest, srcs) in enumerate(prog):
        out.append(sorted({last[s] for s in srcs if s in last}))
        last[dest] = i
    return out

def schedule(prog, lat, width=1):
    # Issue in order, width per cycle (instruction i issues in cycle i // width).
    # Start the cycle after issue and after every producer's write; write lat cycles after starting.
    return [0 for _ in prog]

LAT = {'add': 1, 'mul': 4, 'ld': 2, 'div': 10}
EX = [('ld', 'f0', []), ('mul', 'f4', ['f0', 'f2']), ('add', 'f6', ['f4', 'f8']), ('ld', 'f0', []), ('add', 'f2', ['f0', 'f0'])]
print(schedule(EX, LAT))
```

```python solution
def deps(prog):
    last = {}
    out = []
    for i, (op, dest, srcs) in enumerate(prog):
        out.append(sorted({last[s] for s in srcs if s in last}))
        last[dest] = i
    return out

def schedule(prog, lat, width=1):
    d = deps(prog)
    write = []
    for i, (op, dest, srcs) in enumerate(prog):
        start = max([i // width + 1] + [write[p] + 1 for p in d[i]])
        write.append(start + lat[op])
    return write

LAT = {'add': 1, 'mul': 4, 'ld': 2, 'div': 10}
EX = [('ld', 'f0', []), ('mul', 'f4', ['f0', 'f2']), ('add', 'f6', ['f4', 'f8']), ('ld', 'f0', []), ('add', 'f2', ['f0', 'f0'])]
print(schedule(EX, LAT))
```

```python tests
import random
LAT = {'add': 1, 'mul': 4, 'ld': 2, 'div': 10}
EX = [('ld', 'f0', []), ('mul', 'f4', ['f0', 'f2']), ('add', 'f6', ['f4', 'f8']), ('ld', 'f0', []), ('add', 'f2', ['f0', 'f0'])]
def rand_prog(seed, n=14, regs=6):
    rng = random.Random(seed)
    names = [f'r{k}' for k in range(regs)]
    prog = []
    for _ in range(n):
        op = rng.choice(['add', 'add', 'mul', 'ld', 'div'])
        srcs = [] if op == 'ld' else [rng.choice(names), rng.choice(names)]
        prog.append((op, rng.choice(names), srcs))
    return prog
def ref_deps(prog):
    out = []
    for i, (op, dest, srcs) in enumerate(prog):
        ps = set()
        for s in srcs:
            for j in range(i - 1, -1, -1):
                if prog[j][1] == s:
                    ps.add(j)
                    break
        out.append(sorted(ps))
    return out
def ref_sim(prog, lat, width, buses):
    # event-driven reference: process cycle by cycle, tracking which register values are on the bus
    n = len(prog); dp = ref_deps(prog)
    state = ['wait'] * n; fin = [0] * n; wr = [None] * n; t = 0
    while any(w is None for w in wr):
        for i in range(n):
            if state[i] == 'wait' and i // width < t and all(wr[p] is not None and wr[p] <= t - 1 for p in dp[i]):
                state[i] = 'run'; fin[i] = t + lat[prog[i][0]]
        cand = sorted(i for i in range(n) if state[i] == 'run' and fin[i] <= t)
        for i in cand[:buses]:
            wr[i] = t; state[i] = 'done'
        t += 1
    return wr
assert schedule(EX, LAT) == [3, 8, 10, 6, 8], f"With one issue per cycle, the example writes at [3, 8, 10, 6, 8]; got {schedule(EX, LAT)}."
assert schedule(EX, LAT, width=2) == [3, 8, 10, 4, 6], f"With two issues per cycle: [3, 8, 10, 4, 6]; got {schedule(EX, LAT, width=2)}."
for seed in range(40):
    p = rand_prog(seed)
    for w in (1, 2, 4):
        want = ref_sim(p, LAT, w, 10**6)
        assert schedule(p, LAT, w) == want, f"Random program {seed}, width {w}: writes should be {want}; got {schedule(p, LAT, w)}."
```

::: right
Right. With renaming and unlimited buses, timing is pure dataflow: each instruction waits only for its issue slot and its producers.
:::
:::

::: check
kind: python

## Step 3. Write `schedule_cdb(prog, lat, width, buses)`: write cycles with a limited common data bus.

```python starter
def deps(prog):
    last = {}
    out = []
    for i, (op, dest, srcs) in enumerate(prog):
        out.append(sorted({last[s] for s in srcs if s in last}))
        last[dest] = i
    return out

def schedule_cdb(prog, lat, width=1, buses=1):
    # As schedule, but at most `buses` results can be written each cycle, oldest first;
    # a result that can't be written waits, and so do the instructions that need it.
    return [0 for _ in prog]

LAT = {'add': 1, 'mul': 4, 'ld': 2, 'div': 10}
EX = [('ld', 'f0', []), ('mul', 'f4', ['f0', 'f2']), ('add', 'f6', ['f4', 'f8']), ('ld', 'f0', []), ('add', 'f2', ['f0', 'f0'])]
print(schedule_cdb(EX, LAT))
```

```python solution
def deps(prog):
    last = {}
    out = []
    for i, (op, dest, srcs) in enumerate(prog):
        out.append(sorted({last[s] for s in srcs if s in last}))
        last[dest] = i
    return out

def schedule_cdb(prog, lat, width=1, buses=1):
    d = deps(prog)
    n = len(prog)
    ready = [None] * n
    write = [None] * n
    t = 0
    while None in write:
        for i in range(n):
            if ready[i] is None and t >= i // width + 1 and all(write[p] is not None and write[p] < t for p in d[i]):
                ready[i] = t + lat[prog[i][0]]
        done = [i for i in range(n) if ready[i] is not None and ready[i] <= t and write[i] is None]
        for i in done[:buses]:
            write[i] = t
        t += 1
    return write

LAT = {'add': 1, 'mul': 4, 'ld': 2, 'div': 10}
EX = [('ld', 'f0', []), ('mul', 'f4', ['f0', 'f2']), ('add', 'f6', ['f4', 'f8']), ('ld', 'f0', []), ('add', 'f2', ['f0', 'f0'])]
print(schedule_cdb(EX, LAT))
```

```python tests
import random
LAT = {'add': 1, 'mul': 4, 'ld': 2, 'div': 10}
EX = [('ld', 'f0', []), ('mul', 'f4', ['f0', 'f2']), ('add', 'f6', ['f4', 'f8']), ('ld', 'f0', []), ('add', 'f2', ['f0', 'f0'])]
def rand_prog(seed, n=14, regs=6):
    rng = random.Random(seed)
    names = [f'r{k}' for k in range(regs)]
    prog = []
    for _ in range(n):
        op = rng.choice(['add', 'add', 'mul', 'ld', 'div'])
        srcs = [] if op == 'ld' else [rng.choice(names), rng.choice(names)]
        prog.append((op, rng.choice(names), srcs))
    return prog
def ref_deps(prog):
    out = []
    for i, (op, dest, srcs) in enumerate(prog):
        ps = set()
        for s in srcs:
            for j in range(i - 1, -1, -1):
                if prog[j][1] == s:
                    ps.add(j)
                    break
        out.append(sorted(ps))
    return out
def ref_sim(prog, lat, width, buses):
    # event-driven reference: process cycle by cycle, tracking which register values are on the bus
    n = len(prog); dp = ref_deps(prog)
    state = ['wait'] * n; fin = [0] * n; wr = [None] * n; t = 0
    while any(w is None for w in wr):
        for i in range(n):
            if state[i] == 'wait' and i // width < t and all(wr[p] is not None and wr[p] <= t - 1 for p in dp[i]):
                state[i] = 'run'; fin[i] = t + lat[prog[i][0]]
        cand = sorted(i for i in range(n) if state[i] == 'run' and fin[i] <= t)
        for i in cand[:buses]:
            wr[i] = t; state[i] = 'done'
        t += 1
    return wr
assert schedule_cdb(EX, LAT) == [3, 8, 10, 6, 9], f"With one bus, the example writes at [3, 8, 10, 6, 9]; got {schedule_cdb(EX, LAT)}."
for seed in range(40):
    p = rand_prog(seed, n=16)
    for w, b in ((1, 1), (2, 1), (4, 1), (4, 2), (4, 99)):
        want = ref_sim(p, LAT, w, b)
        got = schedule_cdb(p, LAT, w, b)
        assert got == want, f"Random program {seed}, width {w}, {b} bus(es): writes should be {want}; got {got}."
```

::: right
Right. With one bus, results that finish together queue for it, and the delay ripples to everything that depends on them.
:::
:::

::: explain
## Why does a timing simulator need a model of the result bus, when the functional units are what do the work?

::: model
Every result has to be broadcast before any instruction that needs it can start, so the bus is on the path from every producer to every consumer. With unlimited buses, an instruction's timing depends only on its issue slot and on when its producers finish. With a single bus, results that finish in the same cycle must take turns, and each delayed result delays its consumers, which can delay their consumers in turn. A simulator that ignores the bus would predict a schedule the hardware can't achieve and overstate the benefit of a wide machine. Modeling the shared resources, buses, ports and stations, is what makes a timing simulator's numbers trustworthy.
:::
:::

::: practice

::: check
given: s = 1 | 3 | 5; w = 1 | 2; i = 4 | 7; l = 2 | 4 | 10
answer: (floor(i/w + 0.01) + 1 + s + 1 + abs(floor(i/w + 0.01) - s))/2 + l
tolerance: 0

## Instruction {i} issues in cycle {i} // {w}, and its only producer writes in cycle {s}. It runs for {l} cycles. In which cycle does it write, with an unlimited bus?

::: misses
- [any] Start the cycle after the later of its issue and its producer's write, then add the latency.
:::
:::

::: check
given: a = 3 | 6; b = 5 | 8; l = 1 | 4
answer: (a + b + abs(a - b))/2 + 1 + l
tolerance: 0

## An instruction issued long ago needs two producers, which write in cycles {a} and {b}. It runs for {l} cycles. In which cycle does it write, with an unlimited bus?

::: right
Right. It starts the cycle after the later write and writes {l} cycles after that: cycle {answer}.
:::

::: misses
- [any] Not yet. Start the cycle after the later producer writes.
:::
:::

::: check
given: k = 2 | 3 | 5; t = 6 | 10
answer: t + k - 1
tolerance: 0

## {k} results are all ready in cycle {t}, and there's one result bus, oldest first. In which cycle does the youngest of them write?

::: misses
- [any] One per cycle, starting in cycle t.
:::
:::
:::
