RISC-V 5-Stage Pipeline and Hazards Visualizer

Enter a few instructions, turn forwarding on or off, and see where the pipeline stalls and why.

Data hazards only: branches are treated as not taken. The register file writes in the first half of a cycle and reads in the second.

5 instructions, 10 cycles, 1 stall, CPI 1.20 once the pipeline is full
Instruction12345678910
lw x1, 0(x2)IFIDEXMEMWB
sub x4, x1, x5IFstallIDEXMEMWB
and x6, x1, x7stallIFIDEXMEMWB
or x8, x1, x9IFIDEXMEMWB
add x10, x4, x6IFIDEXMEMWB
  • sub x4, x1, x5 reads x1, written by lw x1, 0(x2): a load-use hazard, 1 stall even with forwarding.
  • add x10, x4, x6 reads x6, written by and x6, x1, x7: a read-after-write hazard, resolved by forwarding with no stall.

The formulas

cycles=N+4+stalls\text{cycles} = N + 4 + \text{stalls}

N instructions in a 5-stage pipeline: the first takes 5 cycles, each later one adds 1, and every stall adds 1.

CPI=1+stallsN\text{CPI} = 1 + \dfrac{\text{stalls}}{N}

Cycles per instruction once the pipeline is full.

Worked example: a load followed by its uses

  1. lw x1, 0(x2); sub x4, x1, x5; and x6, x1, x7; or x8, x1, x9; add x10, x4, x6.
  2. With forwarding: sub needs x1 in EX, but the load only has it at the end of MEM, so sub waits 1 cycle (a load-use hazard). Everything else is forwarded. 5 + 4 + 1 = 10 cycles.
  3. Without forwarding: sub must wait until lw writes back, 2 stalls. and and or are far enough behind to read x1 from the register file. add needs x6 from and, two instructions earlier: 1 more stall. 5 + 4 + 3 = 12 cycles.
  • Only data hazards are modeled. Branches are treated as not taken, so control hazards don't appear.
  • Reordering independent instructions into the slot after a load removes the load-use stall; compilers do exactly this.

Sources