Codiode

Read After Write Hazard Detection

EasyVerilog / SystemVerilogBuild

An instruction that reads a register the previous instruction hasn't written back yet will see the old value. The hazard unit spots that by comparing register numbers.

The hazard detection unit continuously monitors the source registers of the instruction currently in the decode stage and compares them against the destination register of the instruction in the execute stage. If the executing instruction is going to write to a register that the decoding instruction needs to read, the unit asserts a stall signal. This stall forces the decode stage to wait until the data is ready to be forwarded or written back.

This module is purely combinational. There is no clock or reset. The output stall must reflect the current inputs immediately. Register 0 (5'b00000) is hardwired to zero in architectures like RISC-V and MIPS; writing to register 0 never causes a hazard.

Trace 1: ex_reg_write=1, ex_rd=5, id_rs1_en=1, id_rs1=5, id_rs2_en=0, id_rs2=0 → stall=1 (RAW on rs1)
Trace 2: ex_reg_write=1, ex_rd=0, id_rs1_en=1, id_rs1=0, id_rs2_en=0, id_rs2=0 → stall=0 (Register 0 exemption)
Trace 3: ex_reg_write=0, ex_rd=5, id_rs1_en=1, id_rs1=5, id_rs2_en=0, id_rs2=0 → stall=0 (Previous instruction does not write)
Trace 4: ex_reg_write=1, ex_rd=7, id_rs1_en=0, id_rs1=5, id_rs2_en=1, id_rs2=7 → stall=1 (RAW on rs2)

Signal Direction Width Description
id_rs1 input 5 Source register 1 address of current instruction
id_rs2 input 5 Source register 2 address of current instruction
id_rs1_en input 1 Asserted if current instruction reads id_rs1
id_rs2_en input 1 Asserted if current instruction reads id_rs2
ex_rd input 5 Destination register address of previous instruction
ex_reg_write input 1 Asserted if previous instruction writes to a register
stall output 1 Combinational output; asserted when a RAW hazard is detected

Constraints

  • The module is purely combinational; outputs must not be registered
  • A hazard only exists if ex_reg_write is asserted
  • A hazard only exists if the matching source register is actually read meaning id_rs1_en or id_rs2_en is asserted
  • A hazard never occurs for register 0 (5'b00000) regardless of other signals
  • All register addresses are 5-bit values

Topics

PipeliningHazard DetectionRISC-V

Solve this problem

Write the module in Verilog, SystemVerilog or VHDL. Your submission is compiled and simulated against the problem's testbench. You get the waveform back, not a stored answer.

This problem is part of Codiode Pro. The statement above is free to read.

The circuit builder and code editor need a desktop screen. On a phone, read the problem here and open it on a laptop to solve.

Part of Memory and Storage

Problem 6 of 26 in the Memory and Storage track.

Related problems

Browse all problems · Verilog practice problems · Learning tracks

Solve this on a laptopSend yourself the link and continue there.