How a CPU runs one instruction

· 2 min read

#how-it-works#hardware

A CPU runs a program one instruction at a time. The idea to keep: a register called the program counter points at an instruction, and the CPU fetches it, decodes it, executes it, then moves on.

The short version

Arm describes its instructions with a simple model: the processor fetches an instruction, decodes it and executes it, in the order the instructions sit in memory. Real processors overlap these steps, so this is simplified, but they must give the same result as if they ran one at a time. In RISC-V, the program counter (pc) holds the address of the current instruction, and fetching it is an implicit read from memory.

The fetch, decode, execute loop Four boxes in a row. The program counter points at an instruction. Fetch reads it from memory. Decode works out what it asks for. Execute does the work. A dashed arrow returns from execute to the program counter, which now points at the next instruction. pc points at it Fetch read from memory Decode which operation? Execute do the work 1 2 3 4 pc moves to the next instruction
Simplified: real CPUs overlap these steps, but behave as if they ran one at a time.

Step by step

  1. The pc holds the address of the current instruction.
  2. Fetch: the CPU reads that instruction from memory. In RV32I, every instruction is 32 bits and sits on a 4-byte boundary.
  3. Decode: it works out which operation the bits ask for.
  4. Execute: ADD x3, x1, x2 reads x1 and x2 and writes the sum to x3, ignoring overflow. Only load and store instructions touch memory; arithmetic works on registers.
  5. The pc moves to the next instruction. A jump can send it elsewhere: JAL adds an offset to its own address and saves pc+4 in a register to return to.

Why it matters

This loop is why a program is a list: the order in memory is the order of work, until a jump says otherwise. Pipelines make the loop faster, not different: Arm requires the result to match the one-at-a-time model.

Sources