Data Hazards

Data Hazards

Recap of chapter 33: without nops, the pipeline computes wrong results (see hazard_tb.v). With nops it works, but more than half of all executed instructions are nops (85 cycles instead of 37).

In this chapter, the hardware itself takes care of data hazards - so the program no longer has to. Two techniques do the job: forwarding (most cases, no lost cycle) and stalling (the one case forwarding cannot fix). The nops behind branches stay for now - they are the topic of chapter 35.

Tip

All examples of this chapter are in the folder 34_data_hazards of our repository hdl-training: 00-forwarding, 01-load-use. If you cloned it earlier, git pull fetches the latest version.

Three kinds of hazards

Note

A hazard is a situation in which the next instruction cannot execute in the next cycle as planned. There are three kinds:

  • Structural hazard: two instructions need the same hardware in the same cycle. Example: ONE memory for instructions and data - IF and MEM would collide. That was fine in the multi-cycle CPU of chapter 32, but it is a problem in the pipeline. Our design avoids it: two memories, separate adders.

  • Data hazard: an instruction needs a result that is not written yet - this chapter.

  • Control hazard: the pipeline does not know yet which instruction comes next - chapter 35.

The data hazard in detail

Example from chapter 33: add x1, x1, x2 directly followed by sw x1, 4(x0). add writes x1 in WB (cycle 5), but sw reads x1 in ID (cycle 3) - two cycles too early.

Pipeline diagram with dependency arrows, without and with forwarding

As the upper half of the figure shows, the arrows point backwards in time - impossible without help.

The name of this kind of hazard is RAW (read after write). It is the only kind of data hazard in our in-order pipeline.

Key observation: the result of add does not appear only in WB - it is already computed at the end of EX and sits in the EX/MEM register. sw needs it only at the start of its own EX stage, one cycle later (lower half of the figure).

The value exists in time, it is just in the wrong place.

Forwarding

The idea

Instead of waiting for the register file, we take the value directly from the pipeline register where it already is, and feed it into the ALU. This is called forwarding (or bypassing).

There are two places where a newer value can be:

  • in EX/MEM - the result of the instruction directly before

  • in MEM/WB - the result of the instruction two before, or a loaded value

The third case (three instructions before) is already handled by the write-through of the register file (see chapter 33).

So each ALU input gets a 3-input multiplexer: register file (00), EX/MEM (10), MEM/WB (01). Something has to decide, in every cycle, which input is the right one: the forwarding unit.

Deriving the forwarding unit

We build the logic step by step from questions - for ALU input A (rs1). Input B (rs2) works the same way.

  1. Does the instruction in MEM write a register at all? ⇒ EX/MEM.RegWrite
    (sw and branches do not - their "rd" bits are something else)

  2. Is that register x0? ⇒ EX/MEM.rd != 0
    (x0 is always 0, even if an instruction "writes" it - forwarding a value would be wrong)

  3. Is it the register the instruction in EX reads? ⇒ EX/MEM.rd == ID/EX.rs1

If all three answers are yes, we have a "hit M": the current value of rs1 is in EX/MEM. The same three questions for the instruction in WB give a "hit W".

  1. What if BOTH hit? Example: add x1, …​ ; add x1, …​ ; add x5, x1, x1
    Both older instructions write x1 - the newer one (in MEM) holds the current value ⇒ M before W.

The result as pseudocode:

if   EX/MEM.RegWrite and EX/MEM.rd != 0 and EX/MEM.rd == ID/EX.rs1   => ForwardA = 10
elif MEM/WB.RegWrite and MEM/WB.rd != 0 and MEM/WB.rd == ID/EX.rs1   => ForwardA = 01
else                                                               => ForwardA = 00

The same as a circuit - pure combinational logic, only comparators and AND gates (combinational logic); the priority works like the priority encoder:

Inside the forwarding unit: comparators, AND gates and the priority

A walk through the figure:

  • top: questions 1 and 2 (mem_writes, wb_writes)

  • middle: question 3 (the comparators =)

  • &: all three answers are yes (hit M / hit W)

  • right: question 4 (the priority)

In Verilog, the pseudocode becomes one always @(*) block with if / else if / else - the order of the branches IS the priority:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Forwarding unit (chapter 34): pure combinational logic in the EX stage.
//
// The instruction in EX needs the registers rs1 and rs2. If one of the two older
// instructions in front of it (in MEM or in WB) writes exactly that register, the register
// file still holds the OLD value - but the new one already exists in a pipeline register.
// The forwarding unit finds out where, and sets the multiplexers in front of the ALU:
//
//   forward = 00: value from the register file (ID/EX), no hazard
//   forward = 10: value from EX/MEM  (result of the instruction directly before)
//   forward = 01: value from MEM/WB  (result of the instruction two before, or a loaded value)
//
// Three instructions before is already handled by the write-through of the register file.
module forwarding_unit (
    input  wire [4:0] id_ex_rs1,          // registers read by the instruction in EX
    input  wire [4:0] id_ex_rs2,
    input  wire       ex_mem_reg_write,   // instruction in MEM: writes a register? which one?
    input  wire [4:0] ex_mem_rd,
    input  wire       mem_wb_reg_write,   // instruction in WB: writes a register? which one?
    input  wire [4:0] mem_wb_rd,
    output reg  [1:0] forward_a,          // multiplexer in front of ALU input A (rs1)
    output reg  [1:0] forward_b           // multiplexer in front of ALU input B and store data (rs2)
);
    // x0 is always 0, even if an instruction "writes" it: never forward to x0
    wire mem_writes = ex_mem_reg_write && (ex_mem_rd != 0);
    wire wb_writes  = mem_wb_reg_write && (mem_wb_rd != 0);

    // The order matters: if BOTH older instructions write the same register,
    // the newer one (in MEM) wins - its value is the current one.
    always @(*) begin
        if      (mem_writes && ex_mem_rd == id_ex_rs1) forward_a = 2'b10;
        else if (wb_writes  && mem_wb_rd == id_ex_rs1) forward_a = 2'b01;
        else                                           forward_a = 2'b00;

        if      (mem_writes && ex_mem_rd == id_ex_rs2) forward_b = 2'b10;
        else if (wb_writes  && mem_wb_rd == id_ex_rs2) forward_b = 2'b01;
        else                                           forward_b = 2'b00;
    end
endmodule

The forwarding unit in the CPU

The forwarding unit and the two new multiplexers in the pipeline

  • Where the unit sits: in EX, below the ALU. Its inputs come from three pipeline registers: rs1/rs2 from ID/EX, rd and RegWrite from EX/MEM and from MEM/WB (orange, like the rd line in chapter 33).

  • Its outputs ForwardA/ForwardB control the two new multiplexers in front of the ALU.

  • The green paths: the ALU result in EX/MEM (M) and the output of the WB multiplexer (W) go back to the multiplexers.

  • New in the pipeline registers: ID/EX must carry rs1 and rs2, so EX knows which registers the instruction reads. rs2 only for instructions that really read it (R-type, sw, branches) - for addi and lw these bits belong to the immediate.

  • Do not forget sw: the store data must also come out of the ForwardB multiplexer, not straight from ID/EX (add x1 …​ followed by sw x1, 4(x0) is exactly our counter program).

  • The figure is a simplified excerpt (ID/EX to WB); compare it with cpu_pipelined.svg from chapter 33.

The testbench output (00-forwarding/cpu_tb.v) shows all cases in three cycles:

cycle   6   ... EX add  0c ...   fwd A -- B  W     add x1,x1,x2 gets x2 from MEM/WB (addi x2 two before)
cycle   7   ... EX sw   10 ...   fwd A -- B  M     sw gets x1 from EX/MEM (add directly before)
cycle   8   ... EX bne  14 ...   fwd A  W B --     bne gets x1 from MEM/WB (add two before)

The limit of forwarding: the load-use hazard

lw x4, 4(x0) directly followed by add x5, x3, x4: the loaded value exists only at the END of MEM, but add needs it at the START of its EX - at the same moment. Forwarding cannot send a value back in time.

Load-use hazard without and with one stall cycle

The solution: stall for one cycle (interlock).

  • The hazard detection unit in ID checks: ID/EX.MemRead and (ID/EX.rd == IF/ID.rs1 or ID/EX.rd == IF/ID.rs2)

  • If so, PC and IF/ID keep their values (write enable = 0) - IF and ID repeat the same instructions - and ID/EX gets all control signals 0: a bubble (a nop created by the hardware).

  • One cycle later, the value comes from MEM/WB via forwarding.

What happens WITHOUT the stall (00-forwarding/load_tb.v, FAILED on purpose)? The forwarding unit sees "lw writes x4" and forwards what is in EX/MEM - but for a load, that is the ADDRESS, not the data. Result: memory[12] = 3 + 4 (the address!) = 7 instead of 8, memory[16] = 12 + 12 = 24 instead of 16.

The compiler can help: if it puts an independent instruction between lw and its use (instruction scheduling), the stall disappears.

Verilog

00-forwarding: what changes in cpu.v

Compared with the pipeline of chapter 33, cpu.v changes in only four places (marked NEW in the code):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
     reg [4:0]  id_ex_rd;
+    reg [4:0]  id_ex_rs1, id_ex_rs2;                            // NEW: for the forwarding unit
 ...
             id_ex_rd         <= if_id_inst[11:7];
+            id_ex_rs1        <= rs1;                         // NEW
+            id_ex_rs2        <= (!alu_src || mem_write) ? rs2 : 5'd0;
 ...
+    // NEW: forwarding - where is the current value of rs1 and rs2?
+    wire [1:0] forward_a, forward_b;
+
+    forwarding_unit fwd (
+        .id_ex_rs1(id_ex_rs1), .id_ex_rs2(id_ex_rs2),
+        .ex_mem_reg_write(ex_mem_reg_write), .ex_mem_rd(ex_mem_rd),
+        .mem_wb_reg_write(mem_wb_reg_write), .mem_wb_rd(mem_wb_rd),
+        .forward_a(forward_a), .forward_b(forward_b)
+    );
+
+    // NEW: one 3-input multiplexer in front of each ALU input
+    wire [31:0] fwd_a = (forward_a == 2'b10) ? ex_mem_alu_result :   // from EX/MEM
+                        (forward_a == 2'b01) ? wb_data           :   // from MEM/WB
+                                               id_ex_rd1;            // from the register file
+    wire [31:0] fwd_b = (forward_b == 2'b10) ? ex_mem_alu_result :
+                        (forward_b == 2'b01) ? wb_data           :
+                                               id_ex_rd2;
+
-    wire [31:0] alu_b = id_ex_alu_src ? id_ex_imm : id_ex_rd2;
+    wire [31:0] alu_b = id_ex_alu_src ? id_ex_imm : fwd_b;
 ...
-        .a(id_ex_rd1), .b(alu_b), .ctrl(alu_ctrl),
+        .a(fwd_a), .b(alu_b), .ctrl(alu_ctrl),
 ...
-            ex_mem_rd2           <= id_ex_rd2;      // the value sw stores
+            ex_mem_rd2           <= fwd_b;          // the value sw stores, forwarded as well
  1. ID/EX carries rs1 and rs2 - rs2 only if the instruction really reads it.

  2. The forwarding unit is instantiated in EX.

  3. Two multiplexers choose between register file, EX/MEM and MEM/WB. The 3-input multiplexer is written as a chain of ? : - exactly like the 2-input multiplexers before.

  4. The ALU and the store data of sw get their operands from these multiplexers instead of directly from ID/EX.

The complete cpu.v
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// Pipelined RISC-V CPU with forwarding (chapter 34): the pipeline from chapter 33,
// extended by a forwarding unit and two multiplexers in front of the ALU.
//
//    IF  --IF/ID-->  ID  --ID/EX-->  EX  --EX/MEM-->  MEM  --MEM/WB-->  WB
//                                     ^                 |                 |
//                                     +---- forwarding -+-----------------+
//
// New compared to chapter 33 (marked with "NEW" below):
//   - ID/EX also carries rs1 and rs2, so EX knows which registers its instruction reads
//   - forwarding_unit.v decides where the current value of rs1 and rs2 is
//   - a 3-input multiplexer in front of each ALU input takes it from there
//   - the store data of sw also comes out of the multiplexer for rs2
//
// Data hazards between ALU instructions are now handled by the hardware: the program no
// longer needs nops between writing and reading a register. Still NOT handled:
//   - a loaded value that is used by the very next instruction (load-use, see 01-load-use)
//   - the 3 instructions behind a taken branch are still executed (chapter 35)
//
// The registers *_pc and *_inst are carried along only so the testbench can show which
// instruction is in which stage.
module cpu #(
    parameter PROGRAM = "program_fwd.hex"
) (
    input  wire clk,
    input  wire rst
);
    // =========================================================================
    // IF: instruction fetch
    // =========================================================================
    reg  [31:0] pc;
    wire [31:0] inst;
    wire [31:0] pc_plus4 = pc + 4;

    instr_mem #(.PROGRAM(PROGRAM)) imem (.addr(pc), .inst(inst));

    // the branch decision comes back from the MEM stage (see below)
    wire        pc_src;
    wire [31:0] branch_target_mem;
    wire [31:0] pc_next = pc_src ? branch_target_mem : pc_plus4;

    always @(posedge clk)
        if (rst) pc <= 0;
        else     pc <= pc_next;

    // ---- pipeline register IF/ID ---------------------------------------------
    reg [31:0] if_id_pc, if_id_inst;

    always @(posedge clk)
        if (rst) begin
            if_id_pc   <= 0;
            if_id_inst <= 0;               // 0 = empty stage ("bubble"), every control signal is 0
        end else begin
            if_id_pc   <= pc;
            if_id_inst <= inst;
        end

    // =========================================================================
    // ID: decode and read registers
    // =========================================================================
    wire [6:0] opcode = if_id_inst[6:0];
    wire [4:0] rs1    = if_id_inst[19:15];
    wire [4:0] rs2    = if_id_inst[24:20];

    wire       reg_write, alu_src, mem_to_reg, mem_read, mem_write, branch;
    wire [1:0] alu_op;

    control ctl (
        .opcode(opcode), .reg_write(reg_write), .alu_src(alu_src),
        .mem_to_reg(mem_to_reg), .mem_read(mem_read), .mem_write(mem_write),
        .branch(branch), .alu_op(alu_op)
    );

    wire [31:0] rd1, rd2, imm;

    // the write port is driven by the WB stage: a DIFFERENT, older instruction
    wire        wb_reg_write;
    wire [4:0]  wb_rd;
    wire [31:0] wb_data;

    regfile rf (
        .clk(clk), .rs1(rs1), .rs2(rs2), .rd1(rd1), .rd2(rd2),
        .we(wb_reg_write), .rd(wb_rd), .wd(wb_data)
    );
    imm_gen ig (.inst(if_id_inst), .imm(imm));

    // ---- pipeline register ID/EX ---------------------------------------------
    // control signals for the later stages
    reg        id_ex_reg_write, id_ex_mem_to_reg;                 // for WB
    reg        id_ex_mem_read, id_ex_mem_write, id_ex_branch;     // for MEM
    reg        id_ex_alu_src;  reg [1:0] id_ex_alu_op;            // for EX
    // data
    reg [31:0] id_ex_pc, id_ex_rd1, id_ex_rd2, id_ex_imm, id_ex_inst;
    reg [4:0]  id_ex_rd;
    reg [4:0]  id_ex_rs1, id_ex_rs2;                            // NEW: for the forwarding unit
    reg [2:0]  id_ex_funct3;
    reg        id_ex_funct7_5;

    always @(posedge clk)
        if (rst) begin
            {id_ex_reg_write, id_ex_mem_to_reg, id_ex_mem_read, id_ex_mem_write,
             id_ex_branch, id_ex_alu_src, id_ex_alu_op} <= 0;
            id_ex_inst <= 0;  id_ex_pc <= 0;
        end else begin
            id_ex_reg_write  <= reg_write;
            id_ex_mem_to_reg <= mem_to_reg;
            id_ex_mem_read   <= mem_read;
            id_ex_mem_write  <= mem_write;
            id_ex_branch     <= branch;
            id_ex_alu_src    <= alu_src;
            id_ex_alu_op     <= alu_op;
            id_ex_pc         <= if_id_pc;
            id_ex_rd1        <= rd1;
            id_ex_rd2        <= rd2;
            id_ex_imm        <= imm;
            id_ex_rd         <= if_id_inst[11:7];
            id_ex_rs1        <= rs1;                         // NEW
            // NEW: rs2 only if the instruction really reads it (R-type, sw, branches). For addi and lw
            // these bits are part of the immediate - forwarding them would be harmless, but confusing.
            id_ex_rs2        <= (!alu_src || mem_write) ? rs2 : 5'd0;
            id_ex_funct3     <= if_id_inst[14:12];
            id_ex_funct7_5   <= if_id_inst[30];
            id_ex_inst       <= if_id_inst;
        end

    // =========================================================================
    // EX: execute (ALU) and compute the branch target
    // =========================================================================
    // NEW: forwarding - where is the current value of rs1 and rs2?
    wire [1:0] forward_a, forward_b;

    forwarding_unit fwd (
        .id_ex_rs1(id_ex_rs1), .id_ex_rs2(id_ex_rs2),
        .ex_mem_reg_write(ex_mem_reg_write), .ex_mem_rd(ex_mem_rd),
        .mem_wb_reg_write(mem_wb_reg_write), .mem_wb_rd(mem_wb_rd),
        .forward_a(forward_a), .forward_b(forward_b)
    );

    // NEW: one 3-input multiplexer in front of each ALU input
    wire [31:0] fwd_a = (forward_a == 2'b10) ? ex_mem_alu_result :   // from EX/MEM
                        (forward_a == 2'b01) ? wb_data           :   // from MEM/WB
                                               id_ex_rd1;            // from the register file
    wire [31:0] fwd_b = (forward_b == 2'b10) ? ex_mem_alu_result :
                        (forward_b == 2'b01) ? wb_data           :
                                               id_ex_rd2;

    wire [3:0]  alu_ctrl;
    wire [31:0] alu_b = id_ex_alu_src ? id_ex_imm : fwd_b;      // CHANGED: fwd_b instead of id_ex_rd2
    wire [31:0] alu_result;
    wire        zero, overflow;

    alu_control actl (.alu_op(id_ex_alu_op), .funct7_5(id_ex_funct7_5),
                      .funct3(id_ex_funct3), .alu_ctrl(alu_ctrl));

    alu #(.N(32)) alu (
        .a(fwd_a), .b(alu_b), .ctrl(alu_ctrl),
        .result(alu_result), .zero(zero), .overflow(overflow)
    );

    wire [31:0] branch_target = id_ex_pc + id_ex_imm;
    wire        branch_taken  = zero ^ id_ex_funct3[0];          // funct3[0] = 1 for bne

    // ---- pipeline register EX/MEM --------------------------------------------
    reg        ex_mem_reg_write, ex_mem_mem_to_reg;
    reg        ex_mem_mem_read, ex_mem_mem_write, ex_mem_branch;
    reg [31:0] ex_mem_branch_target, ex_mem_alu_result, ex_mem_rd2, ex_mem_pc, ex_mem_inst;
    reg        ex_mem_taken;
    reg [4:0]  ex_mem_rd;

    always @(posedge clk)
        if (rst) begin
            {ex_mem_reg_write, ex_mem_mem_to_reg, ex_mem_mem_read,
             ex_mem_mem_write, ex_mem_branch} <= 0;
            ex_mem_inst <= 0; ex_mem_pc <= 0;
        end else begin
            ex_mem_reg_write     <= id_ex_reg_write;
            ex_mem_mem_to_reg    <= id_ex_mem_to_reg;
            ex_mem_mem_read      <= id_ex_mem_read;
            ex_mem_mem_write     <= id_ex_mem_write;
            ex_mem_branch        <= id_ex_branch;
            ex_mem_branch_target <= branch_target;
            ex_mem_taken         <= branch_taken;
            ex_mem_alu_result    <= alu_result;
            ex_mem_rd2           <= fwd_b;          // CHANGED: the value sw stores, forwarded as well
            ex_mem_rd            <= id_ex_rd;
            ex_mem_pc            <= id_ex_pc;
            ex_mem_inst          <= id_ex_inst;
        end

    // =========================================================================
    // MEM: data memory access and branch decision
    // =========================================================================
    wire [31:0] mem_data;

    data_mem dmem (
        .clk(clk), .addr(ex_mem_alu_result), .mem_read(ex_mem_mem_read),
        .mem_write(ex_mem_mem_write), .wd(ex_mem_rd2), .rd(mem_data)
    );

    // back to the PC: by now, 3 more instructions have been fetched behind the branch
    assign pc_src            = ex_mem_branch & ex_mem_taken;
    assign branch_target_mem = ex_mem_branch_target;

    // ---- pipeline register MEM/WB --------------------------------------------
    reg        mem_wb_reg_write, mem_wb_mem_to_reg;
    reg [31:0] mem_wb_mem_data, mem_wb_alu_result, mem_wb_pc, mem_wb_inst;
    reg [4:0]  mem_wb_rd;

    always @(posedge clk)
        if (rst) begin
            {mem_wb_reg_write, mem_wb_mem_to_reg} <= 0;
            mem_wb_inst <= 0; mem_wb_pc <= 0;
        end else begin
            mem_wb_reg_write  <= ex_mem_reg_write;
            mem_wb_mem_to_reg <= ex_mem_mem_to_reg;
            mem_wb_mem_data   <= mem_data;
            mem_wb_alu_result <= ex_mem_alu_result;
            mem_wb_rd         <= ex_mem_rd;
            mem_wb_pc         <= ex_mem_pc;
            mem_wb_inst       <= ex_mem_inst;
        end

    // =========================================================================
    // WB: write back (into the register file in the ID stage, see above)
    // =========================================================================
    assign wb_reg_write = mem_wb_reg_write;
    assign wb_rd        = mem_wb_rd;
    assign wb_data      = mem_wb_mem_to_reg ? mem_wb_mem_data : mem_wb_alu_result;
endmodule

00-forwarding: program and testbench

The program is the counter program WITHOUT the data-hazard nops - add, sw and bne now follow each other directly. Only the 3 nops behind bne stay, until chapter 35.

The testbench cpu_tb.v prints the pipeline diagram plus the forwarding signals of the instruction in EX (-- no forwarding, M from EX/MEM, W from MEM/WB) - cycles 6-8 were shown above. At the end:

33 useful instructions + 27 nops in 64 cycles
  CPI (useful instructions only) = 1.94
  CPU time with 200 ps per cycle: 64 x 200 ps = 12.8 ns
  for comparison: single-cycle 26.4 ns, multi-cycle 24.4 ns, pipeline with nops 17.0 ns,
                  ideal pipeline 37 x 200 ps = 7.4 ns
PASSED: counted to 10, 33 useful instructions in 64 cycles

01-load-use: the stall

The load-use stall adds three more changes to cpu.v (marked STALL in the code):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
+    // STALL: load-use hazard?
+    wire stall;
+
+    hazard_unit hz (
+        .id_ex_mem_read(id_ex_mem_read), .id_ex_rd(id_ex_rd),
+        .if_id_rs1(rs1), .if_id_rs2(uses_rs2 ? rs2 : 5'd0),
+        .stall(stall)
+    );
 ...
-        if (rst) pc <= 0;
-        else     pc <= pc_next;
+        if (rst)         pc <= 0;
+        else if (!stall) pc <= pc_next;           // STALL: keep the PC
 ...
-        end else begin
+        end else if (!stall) begin               // STALL: keep the instruction in ID
             if_id_pc   <= pc;
             if_id_inst <= inst;
 ...
-        if (rst) begin
+        if (rst || stall) begin                  // STALL: a bubble instead of the instruction
             {id_ex_reg_write, id_ex_mem_to_reg, id_ex_mem_read, id_ex_mem_write,
              id_ex_branch, id_ex_alu_src, id_ex_alu_op} <= 0;
  1. The hazard unit sits in ID and produces one signal: stall.

  2. stall holds the PC and IF/ID - IF and ID repeat their instructions.

  3. stall turns the next ID/EX entry into a bubble, using the same branch as the reset: a bubble is nothing else than "all control signals 0".

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Hazard detection unit (chapter 34): pure combinational logic in the ID stage.
//
// Load-use hazard: the instruction in EX is a load (lw), and the instruction in ID needs
// its destination register. The loaded value exists only at the end of the MEM stage -
// too late even for forwarding. The only way out is to wait one cycle:
//
//   stall = 1:  - PC and IF/ID keep their values: IF and ID repeat the same instructions
//               - ID/EX gets all control signals 0: a bubble moves on instead of the instruction
//
// One cycle later, the load is in WB and its value comes to the ALU via forwarding (MEM/WB).
module hazard_unit (
    input  wire       id_ex_mem_read,   // instruction in EX is a load?
    input  wire [4:0] id_ex_rd,         // ... and loads into which register?
    input  wire [4:0] if_id_rs1,        // registers read by the instruction in ID
    input  wire [4:0] if_id_rs2,        // (0 if the instruction does not read rs2)
    output wire       stall
);
    assign stall = id_ex_mem_read && (id_ex_rd != 0) &&
                   (id_ex_rd == if_id_rs1 || id_ex_rd == if_id_rs2);
endmodule

The testbench load_tb.v runs program_load.hex and marks the stall (bub = bubble):

cycle  7   IF add  18   ID lw   14   EX lw   10   MEM sw   0c   WB sw   08   fwd A -- B --
cycle  8   IF sw   1c   ID add  18   EX lw   14   MEM lw   10   WB sw   0c   fwd A -- B --   STALL
cycle  9   IF sw   1c   ID add  18   EX bub  00   MEM lw   14   WB lw   10   fwd A -- B --
cycle 10   IF lw   20   ID sw   1c   EX add  18   MEM bub  00   WB lw   14   fwd A -- B  W
...
11 instructions + 2 stall cycles in 17 cycles
  = 11 instructions + 4 cycles to fill the pipeline + 2 stalls
  CPI = 1.55

In cycle 8, add is in ID and needs x4, which lw in EX is just loading: STALL. In cycle 9, IF and ID repeat sw and add, and a bubble moves into EX - exactly the figure above. In cycle 10, add is in EX and gets x4 from MEM/WB (B W).

Performance: was it worth it?

  • Counter program (measured with 00-forwarding/cpu_tb.v): 3 + 10 × 3 instructions + 9 × 3 branch nops = 60 instructions ⇒ 60 + 4 = 64 cycles, 64 × 200 ps = 12.8 ns

CPUcyclesCPU timespeedup

single-cycle

33

26.4 ns

1.0

multi-cycle

122

24.4 ns

1.08

pipeline with nops (ch. 33)

85

17.0 ns

1.55

pipeline with forwarding

64

12.8 ns

2.06

ideal pipeline

37

7.4 ns

3.6

  • All data-hazard nops are gone; what remains are the 27 branch nops ⇒ chapter 35.

  • Load-use program (01-load-use/load_tb.v): 11 instructions + 4 fill cycles + 2 stalls = 17 cycles, CPI 1.55.

  • The price: the forwarding multiplexers sit on the critical path of EX (chapter 31) - in a real design T grows a little. Forwarding still pays off by far.

Forwarding in real processors

  • Every pipelined processor forwards - it is not optional.

  • Historical: MIPS = "Microprocessor without Interlocked Pipeline Stages" - the R2000 (MIPS I) had no load-use stall; instead the instruction after a load could not use its result (load delay slot), the compiler had to fill it. From MIPS II on (first implemented in the R6000, 1989) the load delay slot was gone and the hardware stalls by itself; the widespread R4000 (1991) works the same way.

Try it yourself

  • Swap the priority in the forwarding unit (MEM/WB before EX/MEM): which three-instruction program fails?

  • Remove the forwarding for the store data: which instruction of the counter program stores the wrong value?

  • Remove the write-through from regfile.v: is a third forwarding path needed, or does it still work? Why?

  • Write a small program with two loads and two uses; reorder it so that no stall remains.

  • Branches compare in EX: does bne get its operand by forwarding as well? Check in the testbench.

Summary

  • Data hazards (RAW): an instruction needs a result that is not in the register file yet.

  • Forwarding takes the result from EX/MEM or MEM/WB directly to the ALU - no lost cycle.

  • Load-use: the loaded value comes too late even for forwarding ⇒ one stall cycle (bubble), detected in ID.

  • The program no longer needs data-hazard nops: 85 ⇒ 64 cycles for the counter program.

  • Outlook: chapter 35 tackles the branch nops (control hazards).