In this lesson, you will learn how to design the "hazard detection unit" that physically freezes your pipeline to prevent data corruption when an instruction depends on a result not yet written.
The Problem: The "Raw" Hazard
In a standard pipeline, an instruction might need the result of a previous instruction that hasn't finished calculating yet. For example, consider a load operation followed by an addition:
LW R1, 0(R2) ; Load value from memory into R1
ADD R3, R1, R4 ; Add the loaded value (R1) to R4
In the pipeline, the LW takes several stages to get the data from memory, but the ADD needs that data at the very start of its own execution phase. Because the data isn't ready in time, we have a Read-After-Write (RAW) data hazard. If the ADD proceeds, it will simply grab "stale" data currently sitting in the register file, leading to an incorrect calculation.
The Solution: Pipeline Stalling
To solve this, we introduce a Hazard Detection Unit. This logic lives in the Decode stage and compares the source registers of the current instruction with the destination register of the instruction currently in the Execute or Memory stage.
When this unit detects a conflict, it performs two critical hardware actions to "freeze" the pipeline:
- Disable the Program Counter (PC) Update: By preventing the PC from incrementing, we keep the pipeline from fetching the next instruction. The
ADDinstruction stays stuck in the Decode stage for one extra cycle. - Disable the Instruction Register (IF/ID) Update: We keep the current instruction latched in the Decode stage.
- Inject a "Bubble": We clear the control signals for the stage following the Decode stage. By setting these to zero (a
NOPor "No Operation"), we essentially insert a "bubble" into the pipeline that flows through the hardware, doing nothing, while theLWgets one more cycle to finish loading the data.
Once the LW completes, the Hazard Detection Unit releases the stall, and the ADD proceeds with the correct data.
Key Takeaway: Pipeline stalling resolves data hazards by holding the dependent instruction in the Decode stage and inserting an empty "bubble" into the pipeline, giving previous stages the time they need to produce the required data.