Our goal is to build a CPU — a Central Processing Unit. This is the “brains” of a computer, the part responsible for following programs.
We already know that a program is just a list of instructions for the computer to follow. Let’s unpack exactly how this works.
To follow a list of instructions, we need to keep track of which instruction we’re currently at. Computers track this using a program counter (PC), which stores a number indicating what instruction we’re at.
So to execute a program, a computer must:
- Read the Program Counter to find out what instruction we’re at
- Read the instruction that corresponds to the PC
- Perform that instruction
- Increment the PC
This will make our computer step through its instructions one by one. We’ll also need to let certain instructions change the PC directly, making it jump to different parts of the program. This is what will give us branching behaviour.
implementation
Our PC is just storing a number, so to begin with we can reuse our register:
Here’s how we might design the program loop:
- Read the current value of the PC. Call this
A
. - Create a clone of
A
, calledB
. - Dispatch
B
to the instruction processor, which will handle finding and executing the corresponding instruction. - Meanwhile, increment
A
and write it back into the PC.
This might seem a bit risky — we’re incrementing the PC and performing the instruction in parallel, instead of one at a time. What if they interfere with each other?
We should generally be careful with this kind of thing, but in this instance it’s safe. Incrementing A
happens much quicker than the instruction execution, so it’ll be done long before B
needs to touch the PC. If the instruction happens to affect the PC, it’ll just overwrite the incremented value.
next
We have the basic idea of how we’ll read each instruction. Next we’ll look at the instruction processor, the device that receives and executes those instructions.
continue