Home / Learn Chip Programming / The Fetch, Decode, Execute Cycle (Build a CPU Simulator)
The Fetch, Decode, Execute Cycle (Build a CPU Simulator)
This one loop is what every CPU does, billions of times per second. Step through it with a real working simulator.
Theory in plain words
What it is
The fetch-decode-execute cycle is the endless loop of a CPU. It reads an instruction from memory, works out what it means and does it, then moves to the next one.
Why we use it
It is the answer to "how does a chip run my program?". Once you see this loop, assembly, debuggers, interrupts and pipelines all make sense.
How it works
Fetch: IR = memory[PC]; PC = PC + 1. Decode: the control unit reads the opcode and operands. Execute: the ALU or memory does the work, registers and flags change. Jumps simply load a new value into PC.
Where it is used
- The core of every CPU
- What a debugger "single step" does
- Writing emulators and virtual machines
Our teaching CPU
The simulator below has four 8 bit registers (R0 to R3), a zero flag (Z) and a program counter. The instructions are:
| Instruction | Meaning |
|---|---|
| LDI R0, 5 | load the number 5 into R0 |
| MOV R1, R0 | copy R0 into R1 |
| ADD R0, R1 | R0 = R0 + R1 (sets Z) |
| SUB / INC / DEC | subtract, add 1, subtract 1 (set Z) |
| CMP R0, 5 | set Z if R0 equals 5 |
| JMP label / JNZ label / JZ label | jump always / if Z is 0 / if Z is 1 |
| OUT R0 | send a value to the output |
| HLT | stop |
Press Step and watch PC, the registers and the arrow in the listing. This is what a debugger does when you single step firmware.
Machine code: instructions are numbers too
Real CPUs do not store text. Each instruction is encoded as bits: some bits say what to do (the opcode), the others say which registers or what number. For example, a 16 bit AVR instruction 0xE005 means LDI R16, 5.
| Field | Bits | Example (AVR LDI R16, 5) |
|---|---|---|
| Opcode | 1110 | load immediate |
| High nibble of value | 0000 | 0 |
| Register (R16 + d) | 0000 | R16 |
| Low nibble of value | 0101 | 5 |
| Whole instruction | 1110 0000 0000 0101 | 0xE005 |
Quick quiz
1. What is the order of the cycle?
Fetch the instruction, decode it, execute it.
2. What does a jump instruction change?
A jump loads a new value into PC.
Common questions
What is the order of the cycle?
Fetch, decode, execute. Fetch the instruction, decode it, execute it.
What does a jump instruction change?
The program counter. A jump loads a new value into PC.