CComputer Science, Built

Act I · The Machine

Part 6 of 61

The Stored-Program Computer

Degreestarts at this level52 min of film17 chaptersprerequisites: Part 1, Part 3, Part 4, Part 5

How do gates, adders and registers become a machine that runs any program?

The part opens with ENIAC, programmed by plugging cables, and with the 1945 idea that replaced them: keep the instructions in memory beside the data. It designs Pebble-32's instruction set bit by bit, sixteen registers and 34 instructions in four formats, and builds the single-cycle datapath one instruction class at a time from the register file of Part 5 and the ALU of Part 4. The control unit is a 34 by 20 truth table, built as a table of product terms and as minimized logic. A two-pass assembler turns mnemonics and labels into words, and the gate-level machine runs Part 1's Euclid and 300 random programs with the same final state as the emulator. Then the part counts the cost: the iron law, the netlist's critical path, and the Job, version 0, whose linear search takes 1.069 x 10^11 cycles for thirty novels. A Turing-machine interpreter in Pebble assembly runs the busy beavers, which closes Part 1's loop. It ends by planting nine bugs in the emulator to ask how a processor is known to be right.

What you need. Parts 3 to 5 for the gates, the ALU and the register file; Part 1 for Euclid and the universal machine. Programming experience in any language helps with the assembly.

Mathematics, ideas and history
ENIAC, EDVAC, the Baby, ISA design, datapath and control, microcode, assembly
What we build or compute
Pebble-32 from NAND gates; the Job, row 0

What you will be able to do

Degree

  • Encode and decode a Pebble-32 instruction field by field, and trace fetch, decode and execute.
  • Follow a load, a store, a branch and a jump through the single-cycle datapath.
  • Write a loop in Pebble assembly and assemble it by hand with a symbol table.

Graduate

  • Derive a control word from an instruction's needs and compare the table and minimized control units.
  • Compute a program's running time with the iron law and a clock period set by the critical path.
  • Explain why a fixed-width Pebble is finite-state and what universality needs beyond it.

Research

  • Estimate how many random programs are needed to catch a bug of a given rate, and name the bugs they miss.
  • Describe what a formal ISA specification and a verified processor prove, and what remains open.

Industry

  • Compare Pebble-32 with RV32I and explain the design rules of a regular instruction set.
  • Predict the Job's cycle count from its inner loop and find where 99.7% of the time goes.
  • Explain memory-mapped devices, polling and why device registers must not be cached.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 32 min · Graduate 48 min · Research 52 min · Industry 38 min.

  1. 0A machine that reads its own instructionsDegree2 min
  2. 1Cables, then memoryDegree3 min
  3. 2Instructions are dataDegree3 min
  4. 3Designing an instruction setDegree4 min
  5. 4The datapath, one instruction at a timeDegree5 min
  6. 5The control unitDegree3 min
  7. 6The assemblerDegree3 min
  8. 7First programs, gate by gateDegree2 min
  9. 8What a program costsDegree3 min
  10. 9Talking to the worldGraduate2 min
  11. 10The Job, version 0Industry4 min
  12. 11Pebble and the Turing machineGraduate2 min
  13. 12Code is dataGraduate2 min
  14. 13When the world interruptsGraduate3 min
  15. 14The whole machine, countedIndustry3 min
  16. 15Frontier: is the processor right?Research4 min
  17. Recap, problems, and where this comes backAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

A machine that reads its own instructionsDegree2 min

For five parts we have been collecting pieces. Gates, built from switches in Part 3. Arithmetic in Part 4: adders, multipliers, and an ALU that does ten operations. Registers and memory in Part 5, the circuits that remember. Each piece works, and each was checked against a model. But none of them, on its own, computes anything you would call a program. Today they become one machine: Pebble, a thirty-two-bit processor, built entirely from the gates we already have. The question for this part is what turns a pile of parts into a machine that runs programs.

The answer is the stored-program idea, developed during the 1940s and explored in this part. The program is not wired in. It sits in memory, as numbers, beside the data it works on. These words are Part 1's Euclid, the algorithm that found the greatest common divisor by repeated subtraction, written as Pebble instructions. A register called the program counter holds the address of the next instruction. The machine fetches that word, decodes what it asks for, does it, and moves on. Because the program is just numbers in memory, a machine can load a new one in a moment, and a program can even read or write programs. That single fact is why one machine can be a word processor in the morning and a game in the afternoon.

Here is where we are going. A thirty-two-bit processor of about eight thousand gates and five hundred flip-flops, with its own instruction set, an assembler, and programs written for it. Here is one important check: the gate-level machine and a fast emulator run three hundred random programs and end with every register and every byte of memory equal. It will simulate a Turing-machine example within its finite memory, returning to Part 1, and it will run the Job, the word count over thirty novels that the series carries from part to part. Version zero is honest and naive, and it costs a hundred and seven billion cycles.

1Cables, then memoryDegree3 min

In 1945, at the University of Pennsylvania, John Presper Eckert and John Mauchly finished ENIAC, an early general-purpose electronic computer, publicly unveiled in 1946. It filled a room: seventeen thousand vacuum tubes, thirty tons, and it added five thousand numbers a second, a thousand times faster than the relay machines before it. But it had no program in the sense we mean. Each problem was set up by hand: units connected by cables, and switches set on every panel, so that numbers flowed from accumulator to multiplier in the right order. A new problem took days of re-plugging. The people who did it were six women hired as human computers: Kay McNulty, Betty Jennings, Betty Snyder, Marlyn Wescoff, Fran Bilas and Ruth Lichterman. With no manuals, they learned the machine from its logic diagrams and worked out every connection. They were not introduced when ENIAC was shown to the press in 1946, and their work was recognised only decades later.

The first machine to actually run a program from its memory was small. At Manchester, Freddie Williams, Tom Kilburn and Geoff Tootill built a test bed for Williams's tube memory, nicknamed the Baby: thirty-two words of thirty-two bits, stored as dots of charge on a screen. On the twenty-first of June 1948, it ran Kilburn's first program: find the largest proper factor of two to the eighteen. The Baby could not divide, or even add; it could only subtract. So the program tried every number downwards, dividing by repeated subtraction. After fifty-two minutes and about three and a half million instructions, the answer appeared on the screen: a hundred and thirty-one thousand and seventy-two. An instruction set of seven operations, a kilobit of memory, and the first program ever to run from the same store that held its data.

A year later at Cambridge, Maurice Wilkes's EDSAC became the first stored-program computer in regular service. On the sixth of May 1949 it printed its first output, a table of squares, and soon it was computing for scientists across the university. Its team invented much of what programming still is. David Wheeler found a way to call a subroutine and come back: the caller jumps, leaving its own address where the subroutine can find it, and the subroutine ends by jumping to that address. They built a library of tested subroutines, and a loader, the initial orders, that read programs from paper tape and fixed up their addresses. Pebble's jump-and-link instruction does Wheeler's trick in a single step, and Part 11 builds the calling convention on it.

2Instructions are dataDegree3 min

Every stored-program computer does one thing, over and over. Fetch: read the word in memory at the address held in the program counter. Decode: work out which instruction that word is, and which registers and constants it names. Execute: do it, an addition, a comparison, a load from memory or a store to it, and write the result. Next: move the program counter on to the following word, or, if the instruction was a jump or a branch that is taken, to somewhere else. Then start again. An active modern core can retire billions of instructions per second, overlapping much of this work; idle cores may sleep. Everything else in this series, from compilers to databases to the cloud, is built on top of it.

Here is the loop on a tiny program. Memory holds five instructions, each one a thirty-two-bit word, and below them a word of data. The program counter starts at zero. The first two instructions put five and seven into registers a zero and a one. The third adds them. Its word is decoded field by field: the opcode says add, and three four-bit fields name the destination and the two sources. The sum, twelve, goes into a two. The fourth stores a two into memory at address sixty-four, as data. The last one halts. Notice that nothing distinguishes the instruction words from the data word except how the program counter happens to reach them.

The list of instructions a machine understands, and exactly what each one does, is its instruction set architecture. It is a contract. Above it, compilers and programs rely only on what the instructions promise. Below it, the hardware is free to keep the promise any way it likes. This part builds the simplest machine that does: one instruction per clock cycle. Part 7 overlaps instructions like an assembly line, and Part 8 runs them out of order. All three run exactly the same programs, which is why an instruction set can outlive the hardware that first implemented it by decades: much early x86 code can still run in a suitable compatibility environment.

Putting instructions and data in one memory has a cost, and it has a name. Every instruction must travel from memory to the processor, and so must most of the data it works on, along one path, one word at a time. John Backus, who led the team that built FORTRAN, called it the von Neumann bottleneck in his Turing Award lecture of 1977: a connecting tube between the processor and the store, through which every computation is squeezed. Since then processors have grown far faster than memory, so the tube matters more with every decade. Part 9 widens it with caches, small fast memories that keep the words a program is using close to the processor, so most of them never make the trip at all.

3Designing an instruction setDegree4 min

Designing an instruction set starts with what a program can see. Pebble has sixteen registers of thirty-two bits. Registers are the processor's working values: a handful of fast storage cells right next to the ALU, and few enough that four bits can name any of them. Register zero always reads zero, which turns out to be wonderfully useful: it is a free constant, and writing to it throws a result away. Memory is a long array of bytes, numbered from zero. A word is four consecutive bytes at an address divisible by four, stored little end first, the convention used here and by x86; ARM and RISC-V also support little-endian systems. And there is the program counter, which no instruction reads or writes directly: it moves on by itself, or jumps.

Every Pebble instruction is one thirty-two-bit word, in one of four formats. R format, for register operations like add, names two source registers and a destination. I format replaces the second source with an eighteen-bit constant, the immediate, so adding minus one is a single instruction. S format, for stores and branches, names two registers to read and carries a constant: the offset to the address, or how far to branch. J format gives a twenty-two-bit constant to jumps and to lui, which loads the upper bits of a register. The layout is regular on purpose. The opcode is always the top six bits, and register fields sit in the same places, so the hardware can read the registers before it has even finished working out what the instruction is.

Pebble has thirty-four instructions. Ten that combine two registers, the ALU operations of Part 4. Nine that combine a register with a constant. Five that move data between registers and memory, a word or a byte at a time. Six conditional branches. And jumps, lui, and halt, which stops the machine until Part 31 gives it an operating system to return to. The design follows a few rules that every good instruction set shares. Keep it regular. Keep it simple to decode: Pebble gives every instruction its own opcode, so the decoder is a table you can read. Make the common case fast: most constants in real programs are small, so they fit inside the instruction, and a large one costs two instructions. And make mistakes loud: opcode zero means nothing, so a program that jumps into empty memory stops at once instead of running garbage.

Pebble is a close cousin of RISC-V, the open instruction set begun at Berkeley in 2010, and the differences are deliberate. RISC-V has thirty-two registers and five-bit register fields; Pebble's sixteen leave room for longer constants. RISC-V packs several instructions under one opcode, told apart by extra function fields; Pebble gives each its own. And RISC-V scatters the bits of its constants around the word, so sign extension can start from bit thirty-one for signed immediates; the branch and jump layouts also reduce immediate-routing hardware. That is a good engineering trade, and a terrible one for drawing, so Pebble keeps each constant in one piece. Both descend from the reduced instruction set computers of around 1980, IBM's 801, Berkeley's RISC and Stanford's MIPS, which bet that a few simple instructions, run fast, beat many complicated ones.

4The datapath, one instruction at a timeDegree5 min

Now we build the machine that runs this loop, one piece at a time, and send instructions through it. It starts with the program counter, a thirty-two-bit register from Part 5, and the instruction memory, which takes an address and returns the word stored there. In the same cycle, a small adder computes the program counter plus four, the address of the next instruction, ready to be loaded at the next clock edge. That is the whole of fetch: a register, a memory, an adder, and a wire looping back.

Next, an instruction that adds two registers. The instruction's bits fan out. Two four-bit fields go to the register file's read ports, which is Part 5's register file exactly. The two values flow into Part 4's ALU, and a few bits from the control unit tell it to add. The sum flows back around to the register file's write port, addressed by the third field, and is written at the next clock edge, at the same moment as the program counter moves on. In this synchronous model, combinational signals settle between edges; state is captured at the edges.

To add a constant instead, the instruction's low eighteen bits go to the immediate unit. It sign-extends them: copies the top bit into the fourteen bits above, so minus one in eighteen bits becomes minus one in thirty-two. No gates at all, just wires. A multiplexer in front of the ALU chooses the second operand: the register, for an R-format instruction, or the immediate. Which one is chosen is another bit from the control unit.

Loads and stores need the second memory, for data. For a load, the ALU adds the base register and the offset, and the sum is an address. The data memory reads the word there, and a second multiplexer, at the end, chooses what is written back: the ALU's result or the loaded word. A store uses the same address calculation, but sends the second register's value to the memory's data input, and tells the register file not to write. The load is the longest journey any instruction makes in this machine: through the instruction memory, the register file, the ALU, the data memory and the write-back multiplexer, all within one clock cycle. That path sets the clock for every instruction.

Last, the instructions that change the flow. A branch compares two registers in the ALU, by subtracting them and testing for zero, or comparing signs. Meanwhile a second adder computes the target: the program counter plus four times the offset in the instruction. If the condition holds, the multiplexer in front of the program counter takes the target instead of pc plus four. A jump-and-link always takes its target, and writes pc plus four into a register on the way, so that the code it jumps to can return: EDSAC's Wheeler jump, in hardware. Jump-and-link-register takes its target from the ALU instead, which is how a function returns.

That is the whole datapath: about a dozen blocks, every one of them a circuit from an earlier part, with the control unit's dashed lines steering the multiplexers and the ALU. Built as a netlist in this series' library, it comes to a little over eight thousand gates and five hundred and twelve flip-flops: the program counter and fifteen registers of thirty-two bits. One instruction finishes in every clock cycle.

It helps to watch one cycle in time. At the rising edge, the program counter and the registers load their new values, and everything downstream starts to change. The instruction word comes out of memory first, then the register file's outputs settle, then the ALU's result, then, for a load, the data from memory, and last of all the value to be written back. Before each one settles, the wires may carry glitches and unfinished values; synchronous registers must sample only after their timing requirements are met. At the next rising edge, the register file and the program counter capture what is on their inputs, and the cycle starts again. Part 5's timing rules still apply: values must settle before the next edge with setup margin, and remain stable for the required hold window. The next chapter opens the one block we have treated as a black box: the control unit.

5The control unitDegree3 min

The datapath has about twenty control wires: whether to write a register, which input the ALU takes, which operation it does, whether to touch memory, what to write back, whether this is a branch. For each instruction, those wires take fixed values, so the control unit is a truth table with the six-bit opcode as its input and twenty outputs. Here it is, one row per instruction, a bright cell for every one. The load-word row, for example, asks for a register write, the immediate as the ALU's second operand, an addition, a memory read, and the loaded word on the write-back path. Every other opcode, thirty of the sixty-four, is illegal.

A truth table can be built in two ways, and Pebble's library builds both. The direct way gives every opcode its own detector, an AND of six literals, and makes each control signal the OR of the detectors where it is one. This is a programmable logic array, or a read-only memory: an AND plane and an OR plane, and changing the instruction set means changing which dots are connected. It costs about three hundred gates. The clever way minimizes each signal with Part 3's Quine–McCluskey method, using the thirty illegal opcodes as don't-cares, and shares the product terms between signals. Two hundred and five gates, a third fewer. Both versions of the processor run the same three hundred random programs, and end in exactly the same state.

There is a third way, and for decades it was the usual one. In 1951 Maurice Wilkes, of EDSAC, proposed that control should itself be a program: a store of microinstructions, each a row of control signals plus the address of the next row, kept in a matrix of diodes. A simple instruction uses one row. A complicated one, a multiplication or a string copy, walks through several, one per clock cycle, just as a program walks through instructions. Microcode let IBM's System/360 of 1964 offer one instruction set on a whole family of machines, small to huge, most of them microcoded. Modern x86 processors still hard-wire the common instructions and microcode the rare complex ones, and the microcode can be patched after the chip is sold: some of the fixes for the Spectre attacks in 2018 shipped exactly this way. Pebble's instructions are all simple, so its whole control store would be one row each: thirty-four words of twenty bits.

6The assemblerDegree3 min

The machine wants words like these. People want to write something like this: a short name for each operation, names for the registers, and, most importantly, names for places in the program, called labels, instead of addresses that change every time a line is added. A program that translates one into the other is an assembler. Kathleen Booth designed one of the first assembly notations in 1947, for the ARC computer at Birkbeck College, and EDSAC's initial orders of 1949 already translated letters into orders as they loaded the tape. Pebble's assembler, in the series' library, is a few hundred lines of Python.

Labels create a chicken-and-egg problem: a branch near the top of a program may name a label near the bottom, whose address is not known yet. So the assembler reads the program twice. The first pass encodes nothing. It walks down the lines with a counter, adding the size of each one: four bytes for most instructions, eight for li, which becomes two. Whenever it meets a label, it records the counter's value in a symbol table. Here, loop is at address sixteen.

The second pass encodes. Each line becomes a word: look up the opcode, put each register number in its field, and place the constant. A branch to a label stores not the label's address but its distance from the branch, counted in instructions. The branch at twenty-four goes back to sixteen, so its offset is minus two. Because the distance, not the address, is stored, this internal branch keeps working if the whole block moves together and its relative layout stays fixed.

Assemblers also accept instructions the machine does not have. Load-immediate of a big constant becomes two real instructions, lui for the top twenty-two bits and ori for the low ten. Move is an add of zero. Jump is a jump-and-link that writes its return address into the zero register, which throws it away. Branch-if-zero compares with the zero register. Call and return are jump-and-link and jump-to-register. Half of these exist only because register zero always reads zero, which is exactly why the architecture has one.

7First programs, gate by gateDegree2 min

The first program anyone writes for a new machine is a loop. This one adds the numbers from one to ten: a zero counts down from ten, a one accumulates the sum, and the branch jumps back until a zero reaches zero. Here it runs on the gate-level Pebble, the netlist itself, every one of its eight thousand gates evaluated in every clock cycle. The highlighted line is where the program counter points. Thirty-five cycles later the machine halts with fifty-five in a one.

Now Euclid's algorithm from Part 1, the oldest algorithm in this series, on a machine built from NAND gates. The program subtracts the smaller number from the larger until one of them is zero, swapping them when necessary. Watch the two registers, cycle by cycle. A zero starts at one thousand and seventy-one and drops by four hundred and sixty-two, twice; then the registers swap, and the remainders shrink, a hundred and forty-seven, then twenty-one. After sixty cycles the machine halts with twenty-one in a zero, the greatest common divisor, exactly as Euclid's pebbles found it.

Two programs are not a proof. To trust the gate-level machine, the series' library tests it against an independent model. The emulator is a short Python program that states what each instruction means, with no circuits at all. A generator writes random programs, the base instruction set with random registers and constants, branches and jumps, loads and stores of words and bytes. Both machines run three hundred of them, with both versions of the control unit. After each completed program, all registers, every memory byte, the program counter and the step count agree. This is a final-state comparison, not a comparison at every instruction boundary or a proof for all programs. To make that affordable, the netlist is compiled to C, one line per gate, so the gate-level Pebble runs a few thousand cycles a second: slow, but fast enough to run real programs.

8What a program costsDegree3 min

How long does a program take? Computer architects call the answer the iron law of performance. Time is the number of instructions executed, times the average number of clock cycles per instruction, times the length of a cycle. The three factors belong to different people. The instruction count belongs to the algorithm and the compiler. Cycles per instruction belong to how the processor is organized. The cycle time belongs to the circuits. Our single-cycle Pebble makes the middle factor exactly one: every instruction takes one cycle. The price is that the cycle must be long enough for the slowest instruction of all.

The slowest instruction is the load. In one cycle it must fetch itself from memory, be decoded, read a register, add the offset in the ALU, read the data memory, and write the result back. The series' library measures the logic part of that path in the netlist itself. The deepest chain of gates is fifty-nine long; the unit-delay simulation observes at most fifty-six gate delays across four thousand and ninety-six sampled inputs. That sample maximum is not a worst-case timing proof. assume fifty-six ten-picosecond delays and seventy picoseconds of register overhead: six hundred and thirty picoseconds before memory. But the two memory accesses are in the cycle too, and our budget assumes one nanosecond for each. The total is two point six three nanoseconds, or about three hundred and eighty megahertz. An add still fetches its instruction, and waits through the cycle budget for a load's data access too. Part 7 fixes that by cutting the path into pieces.

Most real work is a loop over data, so it is worth costing one exactly. This loop adds a hundred numbers stored in memory. A pointer register walks along the array a word at a time, and a counter counts down. Each trip runs five instructions: a load and an add do the work, and three more move the pointer, decrement the counter and branch back. With six instructions to start and a halt, that is five hundred and seven for a hundred elements, and the gate-level machine agrees. Three in every five instructions are bookkeeping. A compiler can unroll the loop, handling four elements per trip so the bookkeeping is paid a quarter as often, which is one of the optimizations Part 13 builds.

Which instructions does a real program actually run? Here is the Job, version zero, counting the words of the first chapter of Pride and Prejudice: eight hundred thousand instructions, sorted by kind. A quarter are add-immediates, mostly stepping pointers and counters. Then branches, loads, and jumps back to the top of a loop. Arithmetic beyond addition hardly appears. This is the evidence behind the design rule to make the common case fast: real programs mostly move data, compare it and branch, and that is what the hardware should do quickly.

9Talking to the worldGraduate2 min

A computer that cannot print is not much use. Pebble talks to the world without any special instructions at all. Its addresses run from zero to four billion, but only the first megabyte here is memory. The top of the address space belongs to devices. Store a byte to this address, and it appears on the console. Load from this one, and you get the next byte of input from the tape, or minus one when it runs out. This one counts the instructions run so far. This is memory-mapped input and output. The same loads and stores that reach memory reach the devices, and the address alone decides who answers. DEC's PDP-11 made it famous in 1970, and many modern microcontrollers work this way: switching on an LED is a store to the right address.

So printing a message is a loop of loads and stores. A pointer walks along the string in memory. Each trip loads a byte, stops if it is the zero that ends the string, and otherwise stores it to the console's address, then moves on. On the gate-level machine, the letters appear one at a time, five instructions apart, a hundred and two instructions in all.

Reading works the same way. To get the next character, the program loads from the tape's address, and checks for minus one, the end. The Job reads all of its input like this. Asking a device over and over is called polling. It is perfect for a tape that always has the next byte ready, and wasteful for a keyboard, where the program would spin for minutes between keys. The alternative is to let the device interrupt the processor when something happens, which chapter thirteen previews. And device addresses bring a subtlety: a cache, in Part 9, must never keep a copy of one, because each read must consume the next input position, even when consecutive bytes have equal values.

10The Job, version 0Industry4 min

Now the Job, the task that travels through the whole series: count the words of thirty novels and list the twenty most common. Version zero does it in the most direct way there is. Read the text one character at a time from the tape, folding capitals to lower case, and collect letters into a word. At the end of each word, look it up in a table by comparing it with every entry in turn, from the top. If it is there, add one to its count. If not, append it at the bottom. At the end, find the largest count, print that word, cross it off, and repeat twenty times. No sorting, no hashing, nothing clever: Parts 16 and 17 will supply the clever versions.

Here is the heart of it in Pebble assembly. For each table entry, the loop checks whether it has reached the end, loads the entry's length, and if the lengths differ, steps to the next entry. Six instructions per entry. Only entries of the right length go on to compare letters. The whole program, reading, the table, and printing the counts in decimal by repeated subtraction, since Pebble has no divide instruction yet, is about a hundred lines.

Time to run it. The opening paragraph of Pride and Prejudice, six hundred and thirteen bytes, on the gate-level machine: fifty-three thousand six hundred and sixty-five clock cycles, with every gate evaluated in every cycle; the simulation time shown is specific to the recorded host run. The whole first chapter is more than the gates can comfortably do, so it runs on the emulator: four thousand seven hundred bytes, eight hundred and twenty-seven thousand instructions. On the paragraph, the two machines print exactly the same thing in exactly the same number of steps. And here is what Pebble prints for chapter one: you, of, to, a, the. It is a chapter of conversation between Mr and Mrs Bennet.

Running thirty novels instruction by instruction on this Python emulator would be expensive. But we do not need to run them to know exactly how long Pebble would take. Every path through the program costs a fixed number of instructions: each byte read costs nine, each letter three more, each table entry scanned six, each entry of the same length nine more, each matching letter eight. So the total is a sum over events in the text, which Python can count directly. The formula is not an estimate. On twenty random passages from the novels, it matches the emulator's instruction count exactly, every one, to the last instruction. These checks support the path-count derivation; they are not a formal proof for every input.

So here is version zero on all thirty novels. Twenty-five million bytes; four and a half million words, of fifty-eight thousand different kinds. Because the table is searched from the top every time, the program scans fifteen billion table entries. In total, a hundred and seven billion Pebble cycles, more than four thousand per byte of text, and more than ninety-nine percent of them inside the linear search. For scale, divide that same Pebble instruction count by historical operation rates: at five point three operations per second, six centuries; at five thousand, eight months. These are rate illustrations, not ports to the Z3 or ENIAC. Under our assumed single-cycle budget of about three hundred and eighty megahertz, the projection is under five minutes. That is the first row of the ledger. Every later row will say what a better machine, or a better idea, buys; and the numbers on this screen already hint which will matter more.

11Pebble and the Turing machineGraduate2 min

Part 1 connected ideal computers with Turing machines. Our fixed thirty-two-bit Pebble has finite memory, so it is a finite-state machine, not an unbounded universal computer. Let us demonstrate a bounded simulation and then state the idealization needed. First, Pebble can run a Turing machine. The tape is a row of bytes in memory, the head is a pointer, and the machine's rules are a table of words. The interpreter is a loop of fifteen instructions: load the symbol under the head, look up the rule for this state and symbol, write, move the pointer left or right, and change state. Fed the three-state busy beaver from Part 1, it stops after twenty-one steps with five ones on the tape, exactly as before, on the emulator and on the gates alike. On the emulator, the four-state champion takes a hundred and seven steps and leaves thirteen; that larger case is not run at gate level here.

Universality has a very practical face: emulation. Here are two measured execution methods and one hypothetical hardware projection. The bars show host-dependent rates from the cached paragraph and chapter runs: a C-evaluated gate netlist and a Python instruction emulator. The third bar assumes the clock budget of problem 3. It is a projection, not a third machine we ran. On the paragraph that both actually ran, output and step count agree. That is how QEMU runs ARM programs on an x86 laptop, and how a phone runs games written for consoles of the 1980s. These implementations have very different speeds. The test establishes agreement on the example, rather than a universal speed ratio or proof of equivalence.

12Code is dataGraduate2 min

Because instructions are data, a program can change itself, and early programmers did it all the time. EDSAC had no way to say load the next element of an array: an instruction's address was fixed in the instruction. So to walk through an array, a program added one to the address inside its own load instruction, each time round the loop. Here is that trick on Pebble. The load reads the element at offset zero. Then the program loads the load instruction itself, as an ordinary word, adds four to it, which adds four to its offset field, and stores it back. Next time round, the same instruction reads the next element. Eight trips later the sum is thirty-one, on the emulator and on the gates.

Self-modifying code has almost disappeared, for three reasons. The first was invented in 1949 at Manchester: the B-lines, the first index registers, which add a register to an instruction's address. Pebble's loads work this way, base plus offset, so the trick is unnecessary. The second is speed. Pipelined processors and caches fetch instructions long before they run, so a rewritten instruction may already be on its way in its old form. The third is security. Writable executable memory can make code injection easier. Many systems therefore restrict pages from being writable and executable at the same time: write xor execute, which Part 55 returns to. And yet the idea lives on, carefully fenced. A JavaScript engine with a just-in-time compiler compiles hot code to machine code while your page runs, writes it into memory as data, and only then flips that memory to executable. Code is data, still.

13When the world interruptsGraduate3 min

Polling asks a device again and again whether anything has happened. For a keyboard, that means checking thousands of times for every key, and doing nothing useful in between. The alternative turns it round. The processor gets on with its work, and when the key is pressed, the device raises a signal. At the end of the instruction it is running, the processor saves the program counter, jumps to a piece of code called a handler, deals with the key, and returns to exactly where it was, as though nothing had happened. The idea appeared in the mid-1950s, with early systems including the DYSEAC of 1954, and it changed what computers could be: interrupts let an operating system respond to devices and regain control without relying only on polling, which is Part 31's subject.

What does the hardware have to do when an interrupt arrives? Finish the instruction it is running. Copy the program counter into a special register, the exception program counter, and record the cause in another. Load the program counter with the address of the handler. The handler saves any registers it is going to use, does its work, restores them, and runs a return-from-exception instruction that puts the saved program counter back. Pebble's instruction set already reserves the opcodes for this, ready for Part 31. The subtle requirement is that the interrupt be precise: every instruction before the saved point has completely finished, and no later instruction has made an architectural change visible, so the program can resume as if nothing happened. A single-cycle machine makes this boundary simpler, though it still needs interrupt-control hardware and correct saved-state handling. On a pipeline with five instructions in flight, or an out-of-order core with a hundred, it is one of the hardest things to get right.

The same mechanism handles events that come from inside. An instruction the machine does not understand: Pebble's control unit already raises a signal for that, and today the machine simply stops. Pebble's emulator also stops on division by zero; an operating system could handle such an event. That is a Pebble design choice: RISC-V integer division instead defines a result without a divide-by-zero trap. A load from memory that has been moved to disk, which the operating system quietly fetches before re-running the load. And a system call, a synchronous exception by which a program asks the operating system to do something on its behalf. These are called exceptions or traps, and they are how an operating system takes control. Until Part 31, Pebble has none to return to, so it stops.

14The whole machine, countedIndustry3 min

Now count the whole machine. The biggest block is not the ALU. It is the register file's two read ports: thirty-two-bit multiplexer trees choosing among sixteen registers, about three thousand logic gates. The four hundred and eighty register-state inputs belong to storage and are excluded from that logic count. Next are the multiplexers that write a register or keep its value, then the ALU itself, the two adders and multiplexers that choose the next program counter, and finally the control unit, a few hundred gates, and the immediates, almost nothing. Eight thousand two hundred and twenty-four gates and five hundred and twelve flip-flops. Most of a processor, it turns out, is choosing and moving data, not computing on it.

Pebble is a complete computer, but a modest one, and the next acts add what real processors have. Pipelines and then out-of-order execution, to work on many instructions at once. Multiplication, division and floating point, from Part 4's circuits. Caches, so that most memory accesses never leave the chip. Several cores, and the surprisingly deep problem of letting them share memory. And privilege levels and virtual memory, so that an operating system can keep programs from trampling each other. Each of these keeps the contract of the instruction set. The Job's program will not change for the next three parts; only the machine under it will.

Before we leave Act One, take the trip down the tower once, all the way. Here is Pebble's datapath. Pick the ALU, and look inside. Its adder is a row of full adders, one per bit, with carries rippling between them, or racing through a prefix tree, as in Part 4. Pick one full adder: five gates. Pick one gate, built as NANDs, and one NAND is four transistors, two pulling the output up and two pulling it down, as in Part 3. And back up again: transistors make gates, gates make adders, adders make an ALU, and an ALU, registers and a little control make a computer that runs programs within its instruction set and available memory. Every layer of that tower, in this series, is code you can read and run.

15Frontier: is the processor right?Research4 min

This part trusted random programs: the gate-level machine had to agree with the emulator on hundreds of them. How much does that prove? Verification engineers answer with mutation analysis. Plant one known bug in a copy of the emulator, run two thousand fixed-seed random programs on it, using the generator with a multiply-and-divide extension, and count how many end differently. Some bugs are caught almost at once: a store that also writes the next byte shows up in two programs out of three, and shifts that read only four bits of their amount in more than half. Others are rare. A byte load that forgets its sign shows up in one program in four hundred, because memory mostly holds zeros, and a branch that misbehaves only when both registers are zero in one in forty. And one bug is caught by zero of these two thousand programs: dividing minus two to the thirty-one by minus one, the single input where a thirty-two-bit quotient overflows. That observation does not give its true hit probability. The generator evolves correlated register values and forces the divisor odd; there is no justified one-in-four-billion rate for this experiment. This study mutates the instruction emulator, not a gate-level divider.

Turn those rates into a budget. Under independent tests with a fixed true per-test hit rate r, the chance of at least one detection in N tests is one minus, one minus r, to the N. Plugging in our observed rates is only an illustration, not a guarantee. The common bugs are caught within a handful of programs, and the rare byte-load bug within a few hundred. The faint curve assumes a hypothetical rate of two to the minus thirty-two. For the overflow pair, two independent uniform thirty-two-bit operands instead give two to the minus sixty-four; fixing the divisor to minus one gives two to the minus thirty-two. Neither describes our evolving generator. Testing can reveal bugs without proving their absence. A directed test puts the boundary pair in registers deliberately: the correct wrapped quotient is the most-negative integer; the planted mutant returns zero. One suitable test exposes it. In 1994 Thomas Nicely publicly exposed the Pentium FDIV problem; Intel had already discovered it internally. Part 4 examined that different arithmetic bug.

Industry and research do not give up on random testing; they steer it. A fuzzer generates a program, runs it on the hardware design and on a reference model, and measures coverage: which states of the hardware's control logic the program reached. Programs that reached something new are kept and mutated, so the search drifts towards the unexplored corners. DifuzzRTL, in 2021, measured coverage through the registers of the control logic and found new bugs in open RISC-V cores. Cascade, in 2024, generated long programs whose control flow and data flow are tangled together, and found thirty-seven new bugs in five of the six RISC-V processors it tested. Boundary-value generation or a suitable coverage objective can improve the chance of reaching an overflow case, but no time-to-discovery guarantee follows from coverage alone. Cascade's result also shows the value of generating long valid programs; it is not simply the same coverage-feedback loop as DifuzzRTL.

Recap, problems, and where this comes backAll tracks3 min

What we built in this part. An instruction set, designed bit by bit. A single-cycle datapath, assembled from the circuits of Parts 3 to 5, and a control unit that is a truth table, built two ways. An assembler, the first programs, and devices at memory addresses. A gate-level machine that agrees with its emulator on every program we tried, runs Euclid and a Turing machine, and counts the words of a paragraph. And the first row of the ledger: a hundred and seven billion cycles for thirty novels.

Where this comes back. Part 7 cuts the single-cycle machine's long path into a pipeline, and Part 8 runs instructions out of order. Part 9 builds the memory hierarchy behind the loads and stores. Part 11 turns jump-and-link into a calling convention, and Part 13 writes a compiler whose output runs on Pebble. Interrupts and exceptions become an operating system in Parts 31 and 32. And the ledger gains a row each time the Job gets faster, from better hardware or better ideas.

In practice: RISC-V now runs in microcontrollers and data centres, ARM in phones and laptops, x86 in PCs and servers. QEMU runs one instruction set on another, the same idea as our emulator. Simulators like gem5 are where processors are designed before they are built. Every microcontroller's peripherals are addresses. And every chip team checks its hardware description against an instruction-set model, running random programs on both, exactly as this part did.

Seven problems, with full solutions in the part's notes. Pause on any of them. The sixth is a build problem: it asks you to change the Job's program yourself and measure what a small idea buys. The last, marked with a star, is a research problem about the tests themselves.

Next time, Act Two begins: making it fast. Pebble's clock waits for the slowest instruction. Part 7 cuts the datapath into five stages, like an assembly line, so that five instructions are in flight at once and the clock can run several times faster. Then we find out everything that goes wrong when an instruction needs a result that has not been written yet.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. Part 7 cuts the single-cycle machine's long path into a pipeline, and Part 8 runs instructions out of order. Part 9 builds the memory hierarchy behind the loads and stores. Part 11 turns jump-and-link into a calling convention, and Part 13 writes a compiler whose output runs on Pebble. Interrupts and exceptions become an operating system in Parts 31 and 32, and the Job's ledger gains a row whenever a later part makes it faster or cheaper.

Key results

The part's results in one place, for revision.

The iron law\(\displaystyle \text{time}=\text{instructions}\times\frac{\text{cycles}}{\text{instruction}}\times\frac{\text{seconds}}{\text{cycle}}\)
The R format\(\displaystyle \text{word}=\text{op}\cdot2^{26}+\text{rd}\cdot2^{22}+\text{rs1}\cdot2^{18}+\text{rs2}\cdot2^{14}\)
The control unit\(\displaystyle 34\times20 \text{ truth }\allowbreak \text{table}:\ 307 \text{ gates }\allowbreak \text{as }\allowbreak \text{a }\allowbreak \text{table},\ 205 \text{ minimized}\)
The single-cycle clock\(\displaystyle T \ge t_{\text{instr mem}}+t_{\text{logic}}+t_{\text{data mem}}+t_{\text{flip-flop}}\)
The Job, version 0\(\displaystyle 1.069\times10^{11} \text{ cycles},\quad\allowbreak 4{,}279 \text{ per }\allowbreak \text{byte},\quad\allowbreak 99.7\% \text{ searching}\)
A testing budget\(\displaystyle P(\text{caught }\allowbreak \text{in } N)=1-(1-r)^{N}\)

Try it

Lab 6 · Programs on Pebble: Euclid, a Turing machine, and the Job, version 0

Assemble Euclid's algorithm and run it on random pairs; run the 3- and 4-state busy beavers on a Turing-machine interpreter written in Pebble assembly; count words in random passages with the Job, version 0, and compare its cycle count with the exact formula; and check both control units against the truth table they implement.

Figure produced by Lab 6: Programs on Pebble: Euclid, a Turing machine, and the Job, version 0
Produced by the lab below, seed 0, in 1.0 s.
python -m videos.cs.labs 6 needs numpy, scipy, matplotlib · download lab06.py · source on GitHub
Euclid on Pebble: gcd(1071, 462)            21 after 60 instructions   (the rectangle of Part 1: 21)
40 random pairs below 2000                  all equal to math.gcd
3-state busy beaver, interpreted on Pebble  21 steps, 5 ones, 5,466 Pebble instructions
4-state busy beaver, interpreted on Pebble  107 steps, 13 ones, 6,794 Pebble instructions
the Job on 6,239 bytes                      967,944 cycles on the emulator, 967,944 by the formula
cycles per byte                             71 at 392 bytes, 155 at 6,239   (thirty novels: 4,279)
control unit                                34 opcodes x 20 signals: 307 gates as a table, 205 minimized   (the film: 307 and 205)
the whole CPU                               8,224 gates and 512 flip-flops   (the film: 8,224 and 512)

A program is numbers in memory: the same machine runs Euclid, imitates a Turing machine and counts words, and because every path through the Job costs a fixed number of instructions its running time can be computed from the text alone.
The code (128 lines; it asserts its own result)
"""Lab 6: assemble programs for Pebble, run them on the emulator, and predict the Job's cycle count before running it."""

import math

import numpy as np

from videos.coursekit import labs
from explainer.cs import turing
from explainer.cs.pebble import asm, cpu, emu, hdl, programs

TITLE = "Programs on Pebble: Euclid, a Turing machine, and the Job, version 0"
GOAL = ("Assemble Euclid's algorithm and run it on random pairs; run the 3- and 4-state busy beavers on a "
        "Turing-machine interpreter written in Pebble assembly; count words in random passages with the Job, "
        "version 0, and compare its cycle count with the exact formula; and check both control units against the "
        "truth table they implement.")
TASKS = [
    "Replace Euclid's repeated subtraction by the rem instruction and compare the instruction counts on the same pairs.",
    "Double VOCAB and rerun. Which term of the Job's cycle formula grows, and why does a linear search make it quadratic?",
    "Assemble programs.SELFMOD, run it with trace=True, and find the store in m.log that rewrites an instruction.",
]
VOCAB = 300

EUCLID = """
        li   a0, {a}
        li   a1, {b}
loop:   beqz a1, done        # b = 0? stop
mod:    bltu a0, a1, swap    # a < b? swap
        sub  a0, a0, a1      # a = a - b
        j    mod
swap:   mv   t0, a0          # a, b = b, a
        mv   a0, a1
        mv   a1, t0
        j    loop
done:   halt                 # a0 = gcd
"""


def passage(rng, words, n):
    """n words drawn from a made-up vocabulary (frequencies falling like 1 / sqrt(rank)), some capitalized, with
    punctuation."""
    p = 1 / np.sqrt(np.arange(1, len(words) + 1))
    out = []
    for i in rng.choice(len(words), n, p=p / p.sum()):
        w = words[i]
        out.append((w.capitalize() if rng.random() < 0.1 else w) + (", " if rng.random() < 0.1 else " "))
    return "".join(out)


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()

    # 1. Euclid in Pebble's machine language
    m = emu.run(asm.assemble(EUCLID.format(a=1071, b=462)), trace=True, mem_size=4096)
    lab.row("Euclid on Pebble: gcd(1071, 462)", f"{m.regs[3]} after {m.steps} instructions   (the rectangle of Part 1: 21)")
    assert m.regs[3] == 21
    regs, a0, a1 = [0] * 16, [], []
    for s in m.log:  # the two registers after every instruction, for the figure
        if s.reg:
            regs[s.reg[0]] = s.reg[1]
        a0.append(regs[3])
        a1.append(regs[4])
    pairs = rng.integers(1, 2000, (40, 2))
    for a, b in pairs:
        assert emu.run(asm.assemble(EUCLID.format(a=a, b=b)), mem_size=4096).regs[3] == math.gcd(int(a), int(b))
    lab.row("40 random pairs below 2000", "all equal to math.gcd")

    # 2. a Turing machine on Pebble: Part 1's loop closed
    for n in (3, 4):
        table, steps, ones, _, _ = turing.CHAMPIONS[n]
        t = emu.run(asm.assemble(programs.tm_program(turing.TM.parse(table))))
        lab.row(f"{n}-state busy beaver, interpreted on Pebble", f"{t.regs[3]} steps, {t.regs[4]} ones, {t.steps:,} Pebble instructions")
        assert (t.regs[3], t.regs[4]) == (steps, ones)

    # 3. the Job, version 0: right answer, and a cycle count known before it runs
    job = asm.assemble(programs.JOB_V0)
    letters = "abcdefghijklmnopqrstuvwxyz"
    words = sorted({"".join(rng.choice(list(letters), rng.integers(2, 9))) for _ in range(VOCAB)})
    sizes, cycles, formula = [], [], []
    for n in (60, 125, 250, 500, 1000):
        tape = programs.job_tape(passage(rng, words, n))
        r = emu.run(job, tape=tape)
        f = programs.job_features(tape)
        assert bytes(r.output) == programs.job_reference(tape), "the twenty most common words, with their counts"
        assert r.steps == programs.job_cycles(f), "the formula is exact"
        sizes.append(len(tape))
        cycles.append(r.steps)
        formula.append(programs.job_cycles(f))
    lab.row(f"the Job on {sizes[-1]:,} bytes", f"{cycles[-1]:,} cycles on the emulator, {formula[-1]:,} by the formula")
    lab.row("cycles per byte", f"{cycles[0] / sizes[0]:.0f} at {sizes[0]} bytes, {cycles[-1] / sizes[-1]:.0f} at {sizes[-1]:,}"
                               "   (thirty novels: 4,279)")
    assert cycles[-1] / sizes[-1] > 1.5 * cycles[0] / sizes[0], "the linear search makes the cost per byte grow"

    # 4. the control unit, two ways, against its truth table
    table = cpu.control_table()
    gates = {}
    for style in ("table", "minimized"):
        c = hdl.Circuit("control")
        out, _ = cpu.build_control(c, c.input("op", 6), style)
        for name, wire in out.items():
            c.output(name, wire)
        got = {k: hdl.unpack(v[0], 64) for k, v in c.evaluate(hdl.exhaustive(c)).items()}
        for code in range(64):
            assert got["ill"][code] == (code not in table)
            assert all(got[s][code] == table[code][s] for s in cpu.SIGNALS if code in table), (style, code)
        gates[style] = c.size()
    whole = cpu.build_cpu("table")
    lab.row("control unit", f"{len(table)} opcodes x {len(cpu.SIGNALS)} signals: {gates['table']} gates as a table, "
                            f"{gates['minimized']} minimized   (the film: 307 and 205)")
    lab.row("the whole CPU", f"{whole.c.size():,} gates and {whole.flip_flops} flip-flops   (the film: 8,224 and 512)")
    assert (len(table), len(cpu.SIGNALS)) == (34, 20) and (gates["table"], gates["minimized"]) == (307, 205)
    assert (whole.c.size(), whole.flip_flops) == (8224, 512)
    lab.note = ("A program is numbers in memory: the same machine runs Euclid, imitates a Turing machine and counts "
                "words, and because every path through the Job costs a fixed number of instructions its running "
                "time can be computed from the text alone.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    t = np.arange(1, len(a0) + 1)
    ax[0].step(t, a0, where="post", color=labs.BLUE, label="a0")
    ax[0].step(t, a1, where="post", color=labs.GOLD, label="a1")
    ax[0].set(title="Euclid on Pebble: gcd(1071, 462), register by register", xlabel="instructions executed", ylabel="register value")
    ax[0].legend()
    ax[1].plot(sizes, np.array(cycles) / np.array(sizes), "o", ms=8, color=labs.BLUE, label="emulator")
    ax[1].plot(sizes, np.array(formula) / np.array(sizes), "-", color=labs.GOLD, label="formula from the text alone")
    ax[1].set(title="The Job, version 0: cycles per byte of text", xlabel="bytes on the tape", ylabel="cycles per byte", ylim=(0, None))
    ax[1].legend()
    lab.fig = fig
    return lab

Now change it

  1. Replace Euclid's repeated subtraction by the rem instruction and compare the instruction counts on the same pairs.
  2. Double VOCAB and rerun. Which term of the Job's cycle formula grows, and why does a linear search make it quadratic?
  3. Assemble programs.SELFMOD, run it with trace=True, and find the store in m.log that rewrites an instruction.

Problems, with solutions

Try each problem before opening its solution.

  1. Encode by hand. Encode sub t0, a1, a2 and sw t0, -8(sp) in hexadecimal, field by field.

    Solution

    sub is opcode 2, R format: rd = t0 = 9, rs1 = a1 = 4, rs2 = a2 = 5, so the word is 2·2²⁶ + 9·2²² + 4·2¹⁸ + 5·2¹⁴ = 0x0A514000. sw is opcode 23, S format: rs1 = sp = 2 in bits 25–22, rs2 = t0 = 9 in bits 21–18, and −8 as an 18-bit two's complement immediate, 0x3FFF8: 23·2²⁶ + 2·2²² + 9·2¹⁸ + 0x3FFF8 = 0x5CA7FFF8.

  2. A control word. Which of the 20 control signals does jalr ra, 4(t1) set?

    Solution

    rw (write a register), imm (the immediate is the ALU's second operand), wb1 with wb0 = 0 (write back the link, pc + 4) and jalr (take the next pc from the ALU). The ALU operation is add (all four aop bits 0), and every other signal is 0: no memory access, no branch.

  3. The single-cycle clock. Assume a worst-case teaching budget: instruction and data memory take 1 ns each; logic takes 56 gate delays of 10 ps, plus 70 ps of flip-flop overhead. What is f_max? How much faster could a machine run that never touched data memory?

    Solution

    The period must hold both memory accesses and the logic: 1 + 1 + 0.56 + 0.07 = 2.63 ns, so f_max ≈ 380 MHz within this assumed model. The sampled netlist maximum does not certify this budget for physical hardware. Without the data memory the period is 1.63 ns, 613 MHz, 1.61 times faster: the single-cycle design makes every add pay for the loads. Part 7's pipeline instead gives each stage its own cycle.

  4. Reverse a string. Write a Pebble program that reverses a zero-terminated string in place. How many instructions does it run for n letters?

    Solution
            la   a0, str          # a0: the first letter
            mv   a1, a0
    find:   lbu  t0, 0(a1)        # a1: walk to the terminating zero
            beqz t0, found
            addi a1, a1, 1
            j    find
    found:  addi a1, a1, -1       # a1: the last letter
    swap:   bgeu a0, a1, done     # the pointers have met
            lbu  t0, 0(a0)
            lbu  t1, 0(a1)
            sb   t1, 0(a0)
            sb   t0, 0(a1)
            addi a0, a0, 1
            addi a1, a1, -1
            j    swap
    done:   halt
    

    Counting (la is two instructions): 3 to start, 4 per letter to find the end, 3 more to leave the loop and step back, 8 per swap, and 2 to finish: 8 + 4n + 8⌊n/2⌋. On the emulator, "stressed" (n = 8) becomes "desserts" in 72 instructions, and "pebble" (n = 6) becomes "elbbep" in 56.

  5. Rewrite a branch. Write a program that turns one of its own beq instructions into a bne. Why does it work on single-cycle Pebble, and why might it fail on a pipeline?

    Solution

    beq is opcode 25 and bne 26, and the opcode is the top six bits, so adding 2²⁶ to the word changes one into the other:

            la   s0, test
            lw   t0, 0(s0)        # the beq, as a word
            li   t1, 0x04000000   # 1 << 26
            add  t0, t0, t1
            sw   t0, 0(s0)        # now it is bne
            li   a0, 0
    test:   beq  a0, zero, skip   # as written: taken; rewritten: not taken
            li   a1, 1
            halt
    skip:   li   a1, 2
            halt
    

    It ends with a1 = 1: the rewritten branch is not taken. Single-cycle Pebble fetches every instruction from memory in the cycle it runs, so it always sees the newest word. A pipeline fetches several instructions ahead, and a cache may hold an old copy of the instruction, so without an explicit flush the processor can run the stale beq.

  6. Build: move the found word up. Change JOB_V0 so that a word that is found swaps places with the entry above it. Run both versions on chapter 1 with the emulator: how many instructions does the change save?

    Solution

    At found, after adding one to the count, if the entry is not first, copy the entry above down one place (three loads and stores) and store this word's pointer, length and count above it (three stores). Frequent words drift towards the top, where the linear search finds them sooner. On chapter 1 of Pride and Prejudice the count drops from 827,576 to 822,271 instructions (0.6%); on the first 60 kB of the novel, from 27.45 to 26.53 million (3.4%). The printed top twenty is identical. A small idea buys a little; Part 17's hash table removes the search altogether.

  7. ★ Research: define what a generator covers. Add boundary-value generation to random_program, then rerun all nine planted mutants on 2,000 fixed seeds. Define the operand classes your generator is intended to cover and report the evidence, including misses.

    Starting point. Include 0, 1, −1, 2³¹−1, −2³¹, 0x7F, 0x80 and 0xFF. Initializing a register does not ensure a later instruction consumes that value: instructions overwrite registers and the current generator forces division’s divisor odd. Instrument the values actually consumed by each opcode. Enumerate a finite set of ordered operand classes and check that each appears. A separate directed program with li a0, 0x80000000; li a1, -1; div a2, a0, a1; halt already distinguishes the overflow mutant: the reference returns 0x80000000 and the mutant returns 0. Do not label this directed example as a random-generator success.

    Independent per-operand sampling would give a pair probability equal to the product of the two marginal probabilities; it does not give that probability for correlated evolving registers. Coverage-guided testing can help exploration, but does not imply discovery within a fixed time. Finite coverage guarantees and proof-guided test generation exist; scaling useful guarantees to realistic processor state spaces is the research challenge. Report the precise class coverage you established and the properties still unproved.

Notes and sources

Glossary

存储程序计算机 stored-program computer · 冯·诺依曼体系结构 von Neumann architecture · 程序计数器 program counter · 取指、译码、 执行 fetch, decode, execute · 指令集体系结构 instruction set architecture · 操作码 opcode · 立即数 immediate · 符号扩展 sign extension · 小端序 little-endian · 数据通路 datapath · 控制单元 control unit · 控制字 control word · 多路选择器 multiplexer · 可编程逻辑阵列 PLA · 微码 / 控制存储器 microcode / control store · 汇编器 assembler · 标号 label · 符号表 symbol table · 伪指令 pseudo-instruction · 相对 pc 的偏移 PC-relative offset · 每条指令周期数 CPI · 铁律 the iron law · 关键路径 critical path · 内存映射输入输出 memory-mapped I/O · 轮询 polling · 中断 interrupt · 异常 / 陷阱 exception / trap · 系统调用 system call · 自修改 代码 self-modifying code · 变址寄存器 index register · 写异或执行 write xor execute · 即时编译 JIT · 协同仿真 co-simulation

Sources

Books: Patterson & Hennessy, Computer Organization and Design, RISC-V Edition, ch. 2 and 4; Harris & Harris, Digital Design and Computer Architecture, ch. 6–7; Nisan & Schocken, The Elements of Computing Systems, ch. 4–6; Haigh, Priestley & Rope, ENIAC in Action (2016); Waterman & Asanović (eds.), The RISC-V Instruction Set Manual, Volume I.

Papers and reports: von Neumann, First Draft of a Report on the EDVAC (1945); Booth & Booth, "Coding for A.R.C." (1947); Williams & Kilburn, "Electronic digital computers", Nature 162 (1948); Wilkes, "The best way to design an automatic calculating machine" (1951); Wilkes, Wheeler & Gill, The Preparation of Programs for an Electronic Digital Computer (1951); Patterson & Ditzel, "The case for the reduced instruction set computer" (1980).

Primary references for the verification chapter:

  • Solt, Ceesay-Seitz & Razavi, Cascade: CPU Fuzzing via Intricate Program Generation, USENIX Security 2024 (paper). The paper reports 37 new bugs in 5 of 6 tested CPUs; Cascade’s program-construction approach is distinct from a generic coverage-feedback loop.
  • Hur et al., DifuzzRTL: Differential Fuzz Testing to Find CPU Bugs, NDSS 2021, cited and compared in Cascade.
  • Lööw et al., Verified Compilation on a Verified Processor, PLDI 2019 (paper); Silver is a proof-of-concept processor, with explicit initialization/environment assumptions.
  • Kami project, RISC-V Sail model, and RISC-V integer divide semantics. RISC-V division by zero defines results; Pebble’s stop is a local design choice.
  • Cambridge EDSAC history: first logged squares program, 6 May 1949, initial orders and subroutine work.
About this partfrom its README

Part 6 of a sixty-one-part course in computer science (see the series plan and the syllabus), and the end of Act I. ENIAC was initially programmed with cables; the EDVAC report described instructions in memory beside data, drawing on the team’s discussions. This part builds that machine, Pebble, from the gates, adders and registers of Parts 3–5: an instruction set designed bit by bit, a single-cycle datapath and its control unit, an assembler, and programs. The gate-level CPU is one netlist (explainer/cs/pebble/cpu.py), compiled to C (fast.py) and checked against the instruction-level emulator (emu.py) on random programs. It runs Euclid, bounded Turing-machine examples, and the Job, version 0, whose exact cycle count for thirty novels is the first row of the ledger. Every number is computed in compute.py.

  • A machine that reads its own instructions. Five parts of pieces; the program as numbers in memory and the program counter walking Part 1's Euclid; what the part builds; objectives.
  • 1. Cables, then memory. ENIAC (1945: 17,468 tubes, 5,000 additions a second, programmed by plugging cables) and its six programmers; von Neumann's First Draft (June 1945) and the credit dispute; the Manchester Baby's first program (21 June 1948: the largest proper factor of 2¹⁸, 52 minutes, about 3.5 million instructions); EDSAC (6 May 1949), the Wheeler jump and the initial orders.
  • 2. Instructions are data. Fetch, decode, execute, next; a five-instruction program stepped register by register; the instruction set as a contract above single-cycle, pipelined and out-of-order machines.
  • 3. Designing an instruction set. Sixteen registers (r0 = 0), byte-addressed little-endian memory, the program counter; the R, I, S and J formats bit by bit; 34 instructions, one opcode each, and the design rules; Pebble-32 beside RV32I.
  • 4. The datapath, one instruction at a time. Fetch (pc, instruction memory, +4); R format through the register file and ALU; immediates and the operand multiplexer; loads and stores through data memory and write-back; branch target adder and the next-pc multiplexer; jal's link; 8,224 gates and 512 flip-flops.
  • 5. The control unit. The 34 × 20 truth table; built as a PLA (one product term per opcode, 307 gates) and as minimized logic (Quine–McCluskey with the 30 illegal opcodes as don't-cares, 205 gates), both verified; microcode (Wilkes, 1951), System/360, patchable x86 microcode.
  • 6. The assembler. Mnemonics and labels (Kathleen Booth, 1947; EDSAC's initial orders); pass 1 and the symbol table; pass 2 and PC-relative offsets; pseudo-instructions and why the zero register makes half of them possible.
  • 7. First programs, gate by gate. 1 + … + 10 traced on the gate-level machine; Euclid's registers as a staircase over 60 cycles; 300 random programs, both control units, all final registers, memory bytes, program counters and step counts equal to the emulator. This checks completed program states, not each instruction boundary or all possible programs.
  • 8. What a program costs. The iron law (instructions × CPI × cycle time); a load's path through the cycle, the the netlist's structural depth of 59 and sampled maximum of 56 unit gate delays (4,096 inputs), neither a certified silicon clock nor a worst-case delay proof; an explicit teaching timing budget including memory; the Job's instruction mix.
  • 9. Talking to the world. Memory-mapped devices (console, tape, cycle counter) and the PDP-11; printing a string; polling, and why device addresses must not be cached.
  • 10. The Job, version 0. Linear search in an unsorted table, animated; the inner loop in assembly (6 instructions per entry); a paragraph at gate level (613 bytes, 53,665 cycles) and chapter 1 on the emulator (827,576); an exact cycle formula, checked on 20 random passages; thirty novels: 1.069 × 10¹¹ cycles, 4,279 per byte, 99.7% of them in the search; rate analogies of 640 years at 5.3 operations/s and 8 months at 5,000/s, not actual ports to Z3 or ENIAC; 4.7 minutes at an assumed 380 MHz Pebble clock, not measured silicon; ledger row 0.
  • 11. Pebble and the Turing machine. A Turing-machine interpreter in Pebble assembly runs the 3-state busy beaver (21 steps, 5 ones) and the 4-state one (107, 13); the converse simulation argument. Fixed 32-bit Pebble is finite-state; universality requires an ideal family with unbounded effective storage and addressing. These examples do not prove the Church–Turing thesis. Only the 2- and 3-state examples are gate-checked; the 4-state case uses the emulator.
  • 12. Code is data. Summing an array EDSAC-style by rewriting a load's offset field; index registers (the Manchester Mark 1's B-lines, 1949), stale prefetched instructions, write-xor-execute, and JIT compilers.
  • 13. When the world interrupts. Polling against interrupts (DYSEAC, 1954); exceptions: illegal instructions, divide by zero, page faults, system calls.
  • 14. The whole machine, counted. Gates by block (the register file's read ports are the biggest); a synthetic estimate of ≈ 90,000 transistors (NAND equivalents × 4 plus flip-flops × 24), excluding memory, I/O, clocks, buffers and layout, against the 6502, 8086, 80386 and the whole 16-billion-transistor Apple M1 system on a chip (2020), with different counting scopes rather than an area comparison; a trip down the tower, datapath to transistors, and back.
  • 15. Frontier: is the processor right? A separate mutation study using the random generator with multiply/divide enabled (the gate CPU implements the base ISA): nine bugs planted one at a time in a copy of the emulator, each run against 2,000 random programs. A store that also writes the next byte is caught by 67% of them and shifts that read 4 bits of their amount by 54%; a byte load that forgets its sign by 0.25%, a branch wrong only for two zeros by 2.7%; dividing −2³¹ by −1 by 0 of these 2,000 programs. This does not establish zero hit probability. Independent uniform 32-bit operands would give 2⁻⁶⁴ for that pair; a uniform dividend with divisor fixed at −1 gives 2⁻³². Neither is the evolving generator’s distribution. Detection budgets, 1 − (1 − r)^N, require independent tests and a fixed true per-test rate; empirical rates are illustrations. A directed boundary test distinguishes the mutant in one run. CPU fuzzing (DifuzzRTL, 2021; Cascade, 2024: 37 new bugs in 5 of 6 RISC-V CPUs). Sail, an executable formal reference for supported RISC-V features, not by itself a proof of a core; verified designs (Kami, 2017; Silver + CakeML, 2019). Abstract out-of-order proofs and selected industrial verification exist; scaling complete correctness and security arguments to complex implementations remains difficult.
  • Recap, where this comes back, in practice, problems.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. History: ENIAC (1945) and its six programmers; von Neumann's First Draft (1945); the Manchester Baby (21 June 1948); EDSAC (1949), Wilkes and the Wheeler jump.
  2. The idea: instructions are data. Fetch, decode, execute; the program counter.
  3. Designing an ISA: Pebble-32's word size, registers, formats and encodings (bit fields on screen); the design rules (regularity, simple decode, the common case fast); comparison card with RV32I.
  4. The single-cycle datapath, built step by step (R-type, loads and stores, branches, jumps), with data flowing through it.
  5. The control unit: decoding as a truth table, as combinational logic, and as microcode (Wilkes 1951); the trade-offs.
  6. The assembler: two passes, labels, the symbol table, pseudo-instructions.
  7. First programs: sum 1…n, and Part 1's Euclid on gate-level Pebble, traced.
  8. Loops, arrays and branches; the cost model, time = cycles × clock period, with the period taken from the measured critical path.
  9. Memory-mapped I/O: the console and the tape that delivers the novels' characters.
  10. The Job, version 0: hand-written assembly with an unsorted word list. A paragraph runs at gate level and a chapter on the emulator, with identical results. Ledger row 0, projected to the Z3's relays, ENIAC and 1 GHz.
  11. Universality closed: a Turing-machine interpreter in Pebble assembly runs Part 1's BB(3); a TM can simulate Pebble. Part 1's loop closes.
  12. Code as data: self-modifying code in EDSAC's day, and why we forbid it later (W^X, Part 55).
  13. Interrupts and exceptions previewed (Part 31).
  14. The whole machine counted: Pebble's gates and critical path, against the 6502 (~3,500 transistors) and a modern core (cited).
  15. Outro.

Computed: the whole CPU netlist; gate-level/emulator co-simulation on random programs; the Job v0; BB(3) on Pebble. Visuals: instruction bits lighting their fields; the datapath with glowing packets; the camera zooms from the block diagram into one NAND gate and back, the first trip down the tower. In practice: ISA design (RISC-V, ARM, x86), emulators and simulators (QEMU, gem5), memory-mapped peripherals in embedded firmware. Reading: Patterson & Hennessy, Computer Organization and Design (RISC-V) ch. 2, 4; Harris & Harris ch. 6–7; Nisan & Schocken ch. 4–6; von Neumann 1945; Wilkes 1951; Haigh, Priestley & Rope, ENIAC in Action; the RISC-V unprivileged specification.


中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. 手工编码。 把 sub t0, a1, a2 和 sw t0, -8(sp) 逐字段编码成十六进制。

    解答

    sub 的操作码是 2,R 格式:rd = t0 = 9,rs1 = a1 = 4,rs2 = a2 = 5,所以这个字是 2·2²⁶ + 9·2²² + 4·2¹⁸ + 5·2¹⁴ = 0x0A514000。sw 的操作码是 23,S 格式:rs1 = sp = 2 放在第 25–22 位, rs2 = t0 = 9 放在第 21–18 位,−8 写成 18 位补码立即数 0x3FFF8:23·2²⁶ + 2·2²² + 9·2¹⁸ + 0x3FFF8 = 0x5CA7FFF8。

  2. 一个控制字。 jalr ra, 4(t1) 会置位 20 个控制信号中的哪些?

    解答

    rw(写寄存器)、imm(立即数作为算术逻辑单元的第二个操作数)、wb1(wb0 = 0,写回链接地址 pc + 4),以及 jalr(下一个 pc 取自算术逻辑单元)。运算是加法(四个 aop 位全为 0),其余信号都为 0:不访问存储器,也不是分支。

  3. 单周期时钟。 假设一个最坏情况教学预算:两次存储器访问各需 1 ns,逻辑为 56 个 10 ps 的门延迟,另加 70 ps 的触发器开销。f_max 是多少? 一台从不访问数据存储器的机器能快多少?

    解答

    一个周期要容下两次存储器访问和逻辑:1 + 1 + 0.56 + 0.07 = 2.63 ns,所以在此假设模型中 f_max ≈ 380 MHz。抽样网表最大值并不能验证真实芯片的这项预算。去掉数据存储器,周期为 1.63 ns,即 613 MHz,快 1.61 倍:单周期设计让每一条加法都为取数指令买单。第 7 部分的流水线则让每一级各有自己的周期。

  4. 反转字符串。 写一个 Pebble 程序,原地反转一个以零结尾的字符串。对 n 个字母它要执行多少条指令?

    解答

    程序见上文英文部分。计数(la 是两条指令):开头 3 条,找结尾时每个字母 4 条,离开循环并退回一步再 3 条,每次交换 8 条,结束 2 条:8 + 4n + 8⌊n/2⌋。在模拟器上,"stressed"(n = 8)用 72 条指令变成 "desserts","pebble"(n = 6)用 56 条 变成 "elbbep"。

  5. 改写一条分支。 写一个程序,把它自己的一条 beq 改成 bne。为什么它在单周期 Pebble 上可行?为什么在流水线上可能失败?

    解答

    beq 的操作码是 25,bne 是 26,而操作码是最高的六位,所以给这个字加上 2²⁶ 就把前者变成后者(程序见上文)。它结束时 a1 = 1:改写后的分支没有跳转。单周期 Pebble 在每条指令执行的那个周期才从存储器取它,所以总能看到最新的字。流水线会提前取 好几条指令,缓存也可能保留指令的旧副本,因此如果不显式刷新,处理器可能执行那条过时的 beq。

  6. 动手:把找到的词往上移。 修改 JOB_V0,让找到的词与它上面的条目交换位置。用模拟器在第 1 章上运行两个版本:这一改动省了多少 条指令?

    解答

    在 found 处把计数加一之后,如果这个条目不在最前面,就把上面的条目下移一格(三次取数和存数),再把这个词的指针、长度 和计数存到上面(三次存数)。常用词会逐渐漂到前面,线性查找就能更早找到它们。在《傲慢与偏见》第 1 章上,指令数从 827,576 降到 822,271(0.6%);在小说的前 60 kB 上,从 2745 万降到 2653 万(3.4%)。打印出的前二十个词完全相同。小主意只换来一点点; 第 17 部分的哈希表则彻底去掉了查找。

  7. ★ 研究题:定义生成器覆盖了什么。 在 random_program 中加入边界值生成,用两千个固定种子重跑全部九个变异体。定义预期覆盖的操作数类别,报告证据和仍然漏掉的情况。

    起点。 可加入 0、1、−1、2³¹−1、−2³¹、0x7F、0x80、0xFF。但寄存器的初值不等于后来指令真正读到的值:中间指令会覆盖它,当前生成器还把除数强制变成奇数。因此要记录每种操作真正消耗的值,枚举有限的有序操作数类别,并检查是否全部出现。另一个定向程序 li a0, 0x80000000; li a1, -1; div a2, a0, a1; halt 能直接区分溢出变异体:参考实现返回 0x80000000,变异体返回 0。不要把它算成随机生成器已经发现了错误。

    只有独立抽样,才能把两个边缘概率相乘;不能把这种计算套到相互关联、不断变化的寄存器上。覆盖率引导能帮助探索,但不保证固定时间内发现错误。有限覆盖保证和证明引导测试已经存在;研究难点在于把有用保证扩展到现实处理器状态空间。应明确已确立的类别覆盖,以及仍未证明的性质。

Build the film

python -m videos.cs.cs6.compute        # the part's numbers, into .cache/cs6
python tools/build.py cs6                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs6 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs6. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.cs.cs6.compute            # every number in the part (a few minutes: the CPU compiles once)
python tools/build.py cs6 -q l             # a 480p preview
python tools/build.py cs6                  # 1080p

The Job's corpus is AI, Built Part 1's thirty Gutenberg novels (downloaded into .cache/ai1/books). Ledger row 0 is written to .cache/cs6/ledger.json.