How computers work

Pipeline: several instructions at once

A pipeline splits the execution of an instruction into stages, like an assembly line. While one instruction writes its result, the next one accesses memory, a third computes in the ALU, a fourth is being decoded, and a fifth is being fetched. The clock cycle gets shorter, and ideally one instruction finishes every cycle. The teaching model is the classic five-stage RISC-V pipeline; it shows where delays come from and why forwarding and a branch predictor are needed.

Open in 3D →

The idea: an assembly line

Picture a laundry: washing takes 30 minutes, drying 30, ironing 30. If you wait for one basket to go through all three stages before starting the next, four baskets take 6 hours. But if you load the washing machine as soon as it is free, then after an hour and a half a finished basket comes out every 30 minutes: four baskets take 3 hours. Each basket takes just as long as before, but several are in progress at the same time.

In a single-cycle core an instruction passes through all the blocks in one cycle, and the cycle must fit the slowest instruction, the load: fetch 200 ps, decode and register read 100 ps, ALU 200 ps, memory 200 ps, write-back 100 ps, for a total of 800 ps (textbook numbers from Patterson and Hennessy). A pipeline places registers between the stages and makes the cycle equal to the slowest stage: 200 ps.

Each instruction now goes through five cycles of 200 ps, 1000 ps in total, which is even longer than before: the ID and WB stages fit into 100 ps but still take a whole cycle. In return, every cycle a new instruction enters the pipeline and one leaves it. The latency of a single instruction went up, while the throughput went up 4 times: 800 ps versus 200 ps per instruction.

This limit of × 4 (rather than × 5) is due to the unequal stages. To make a pipeline efficient, designers try to split the work into parts of equal duration. But the ideal is reachable only as long as instructions do not get in each other’s way, and they do. The main part of this article is about how.

IF: fetch

The 32-bit instruction at the address in the program counter is read from the instruction cache, and the PC is incremented by 4. The stage delay in the textbook numbers is 200 ps: the time it takes to read the instruction cache.

The difficulty is that fetch must pick the next instruction already in the next cycle, while the previous instruction is only being decoded at that moment. If it is a branch, fetch does not know how it will turn out. The simplest option is to always take the next instruction in order (PC + 4), that is, to predict “branch not taken.” A better option is to ask the predictor: given the instruction’s address, it recalls whether there was a branch here and where it went last time.

The fetched instruction, together with its PC, is latched into the IF/ID register and enters the decoder on the next cycle.

ID: decode and register read

The instruction is broken into fields, the operands rs1 and rs2 are read from the register file, the immediate generator assembles imm, and the decoder produces control signals for the following stages. All of this, together with the data, moves on into the ID/EX register.

This is also where the hazard detection unit checks whether the instruction needs a result that is not ready yet. If it does and forwarding cannot help, the instruction stays in ID, fetch freezes too, and a “bubble” goes into EX: an empty instruction that does nothing. The pipeline loses a cycle.

Registers are written in the first half of the cycle and read in the second half, so an instruction in ID sees the result that WB is writing in the same cycle. This saves a cycle on every dependency on an instruction three positions earlier.

EX: execute

The ALU computes the result of an arithmetic instruction or the address for a load or store. Conditional branches are also resolved here: the branch unit compares registers and computes the target address.

If the branch is taken but fetch has already brought in instructions from the wrong path (or it is not taken, but fetch followed the branch path), the two instructions already started, one in ID and one in IF, are flushed and turned into bubbles. Two cycles are lost. In the model such instructions are shown as flushed.

In the teaching pipeline branches are resolved in EX; some textbook variants move the comparison into ID so the penalty is 1 cycle, but then the comparison needs its own forwarding paths. In real cores branches are resolved 10–20 stages after fetch, hence a penalty of 15–20 cycles and the enormous importance of predictor accuracy.

MEM: memory

Loads and stores access the data cache. Other instructions pass straight through the stage: their result simply moves into the next register.

Load data is ready only at the end of MEM. If the next instruction needs it right away in EX, it has to wait one cycle even with forwarding: this is a load-use hazard. For example, ld x1, 0(x2) followed immediately by add x3, x1, x4: the add stalls in ID for one cycle.

Compilers try to reorder instructions so that some other useful work sits between a load and its use. In the “All formats” program, find the stall after lw: even forwarding does not remove it.

In the model the data cache always hits in one cycle. In reality a cache miss would stop such a simple pipeline for tens or hundreds of cycles, which is exactly why big cores execute instructions out of order.

WB: write-back

The result is written to the destination register: a value from the ALU, data from memory, or PC + 4 for jal and jalr. From this moment it is visible to all subsequent instructions through the register file. The write happens in the first half of the cycle so that ID can read the new value in the second half.

A single-cycle core does all five steps in one long 800 ps cycle; the pipeline takes five cycles of 200 ps but finishes an instruction every cycle. Hence the speedup limit of × 4. For 40 instructions without hazards, a single-cycle core needs 40 × 800 = 32,000 ps, and the pipeline needs (40 + 4) × 200 = 8800 ps: 4 cycles go into filling the pipeline.

Pipeline registers

Between the stages sit the latches IF/ID, ID/EX, EX/MEM, MEM/WB, which are sets of flip-flops. On the clock edge each instruction, with all its data and control signals, moves into the next stage. Without them the stages would interfere with each other: the result of one instruction would get mixed up with the inputs of the next.

Pipeline registers are wide: ID/EX holds two 64-bit operands, the immediate, register numbers, the PC and a dozen control signals, hundreds of bits in all. Control signals travel along with the instruction: the decoder generates them in ID, but they are used by later stages. For example, “write to a register or not” is needed only in WB.

Registers are not free: each adds its own delay to the cycle (tens of picoseconds) and consumes energy on every clock edge. That is why chopping the pipeline into ever smaller pieces makes no sense.

In the model the registers flash on every cycle: this is the clock frequency in action.

Hazards: what gets in the pipeline’s way

A hazard is a situation in which the next instruction cannot enter a stage in its cycle. There are three kinds.

Data hazards: an instruction needs the result of a previous one that has not been written yet. add x1, x2, x3 followed immediately by sub x4, x1, x5: sub reads x1 in ID while add is only in EX. Without countermeasures sub would read the old value and the result would be wrong.

Control hazards: after a branch it is unknown which instruction to fetch until the branch is resolved in EX.

Structural hazards: two instructions need the same block in the same cycle. For example, if instructions and data lived in one single-port memory, IF and MEM would interfere with each other. The teaching model has none: the instruction and data caches are separate, and the register file is written and read in different halves of the cycle.

The simplest fix for any hazard is to wait by inserting bubbles. But every bubble is a lost cycle, so forwarding was invented against data hazards and prediction against control hazards.

Backward paths: forwarding, write-back, branch

Forwarding (bypass) passes a result directly from the EX/MEM or MEM/WB registers to the ALU input without waiting for it to be written to the register file. The result of add is ready at the end of its EX, exactly when sub enters EX. Multiplexers at the ALU inputs choose between the value from the register file, from EX/MEM (an instruction 1 position earlier) or from MEM/WB (2 positions earlier).

Without forwarding a dependent instruction waits until the producer reaches WB: two stall cycles for every such pair. Turn forwarding off in the lab and the cycle count grows noticeably. For a load, forwarding cuts the wait from two cycles to one: the data appears only at the end of MEM.

At the back of the model are the path for writing the result from WB into the register file and the branch path from EX to IF. The red path is the branch on a misprediction: fetch restarts from the correct address, and the wrongly started instructions are flushed.

Forwarding is not cheap: in cores with 4–6 ALUs the result of each must be deliverable to the inputs of all the others, and the forwarding network becomes one of the most wire-heavy parts of the core.

Branch prediction

The model uses a 1-bit predictor with a branch target buffer (BTB): for each branch instruction it remembers where it went last time and next time fetches instructions from the same place. In a loop it is wrong only twice: on the first pass (the branch is still unfamiliar) and on loop exit (the branch is not taken for the last time). Turn on the predictor for a program with a loop and find these two mistakes.

A 2-bit saturating counter does a bit better: it changes its prediction only after two mistakes in a row, so a single exit from an inner loop does not spoil the prediction for the next entry.

Modern predictors take into account the history of the last hundreds of branches: for example, the TAGE scheme keeps several tables indexed by histories of different lengths and picks the longest one that matches. Separate structures predict function return addresses (the return stack) and indirect branches. Accuracy is 95–99%, and the remaining mistakes still cost a noticeable share of performance: with a 20-cycle penalty and one mistake per 200 instructions, that is 0.1 cycles per instruction, and a wide core that otherwise spends 0.25–0.3 cycles per instruction loses about a quarter of its time to mispredictions.

Let’s count: CPI and the real speedup

CPI (cycles per instruction) is the number of cycles per instruction; the pipeline ideal is 1. Suppose a program has 100 instructions, 20 of them loads, and half of those are followed immediately by a use: 10 stall cycles. There are also 15 branches, of which the predictor got three wrong: 3 × 2 = 6 cycles. Plus 4 cycles to fill the pipeline. In total 100 + 10 + 6 + 4 = 120 cycles, CPI = 1.2.

Time: 120 × 200 ps = 24 ns. A single-cycle core would take 100 × 800 ps = 80 ns. The real speedup is × 3.3 instead of the ideal × 4.

The level’s model computes the same thing for real for your program: how many cycles, how many bubbles and flushes, what the CPI is, and how long a single-cycle core would have taken.

Deep and wide pipelines

If 5 stages gave × 4, why not make 50? There are several reasons. Each pipeline register adds delay, and with very short stages it eats up the gain. The longer the pipeline, the more costly a misprediction and the longer the wait for a dependent instruction. And the higher the frequency, the higher the power.

A historical example is the Intel Pentium 4 (2000–2006): a pipeline of 20 and later 31 stages for the sake of high clock speeds. The processor hit a thermal wall at 3.8 GHz, and on branchy code it lost to shorter pipelines. Intel’s next architecture, Core, went back to 14 stages.

Modern x86 and ARM cores have 14–20 stages, fetch and issue 6–8 instructions per cycle (superscalar execution) and execute out of order with a buffer of hundreds of instructions. The teaching 5-stage pipeline shows the same phenomena (dependencies, bubbles, flushes) in their simplest form.

Common misconceptions

“A pipeline speeds up every instruction.” No: each individual instruction takes even longer. What speeds up is the stream of instructions, the throughput.

“5 stages means 5 times faster.” Only with equal stages and no hazards. Unequal stages, pipeline registers, bubbles and flushes make the real speedup smaller.

“A mispredicted branch breaks the program.” No: instructions from the wrong path are flushed before they write their results, and the program runs correctly, just more slowly.

Open in 3D →

All articles

Overviews

Logic: from transistor to arithmetic

Processor

Computer

Servers and data centers

Networks and the internet

Software