In this lesson, you will learn how to identify Read-After-Write (RAW) data hazards that occur when a processor attempts to use data before it has been safely stored in the register file.
The Challenge of Timing
In a pipelined CPU, instructions are executed in stages (Fetch, Decode, Execute, Memory, Write-back). Usually, the result of an arithmetic operation is only written back to the register file during the final "Write-back" stage. A Read-After-Write (RAW) hazard occurs when a later instruction tries to read a register that is still being calculated by a previous instruction currently in the pipeline.
Because the register file hasn't been updated yet, the second instruction would read "stale" or incorrect data, leading to a functional error.
Identifying the Dependency
Consider this simple sequence of instructions:
ADD R1, R2, R3 ; Result of R2+R3 is stored in R1
SUB R4, R1, R5 ; R1 is used as an input for the SUB operation
In a standard five-stage pipeline, the ADD instruction calculates the result in the Execute stage, but it won't write that value into R1 until the Write-back stage. Meanwhile, the SUB instruction needs to read R1 during its own Decode stage. If the SUB instruction reaches the Decode stage before the ADD instruction finishes its Write-back, it will fetch the old value of R1.
We detect this by comparing the source register of the following instruction with the destination register of the preceding instruction.
Why Detection Matters
Hardware logic in the CPU must constantly compare these register indices. If Source_Register_Instruction_B == Destination_Register_Instruction_A, the control unit realizes that instruction B cannot proceed normally. The hardware must either stall the pipeline (forcing instruction B to wait until the write-back is complete) or implement "forwarding" (grabbing the result directly from the ALU before it reaches the register file). Without this detection mechanism, the CPU would silently process incorrect data, leading to unpredictable system behavior in your embedded application.
Key Takeaway: A Read-After-Write hazard is detected when the hardware identifies that an instruction’s source operand is the same as the destination register of an instruction currently sitting earlier in the pipeline.