Day 90: Branch handling: flush and static prediction
Branch handling: flush and static prediction
Finish pipeline control with branch handling (Stage 1, Day 46). ChipX predicts not-taken and speculatively fetches the fall-through. When a branch resolves taken (in EX), the instructions already fetched behind it are wrong, so flush them (convert IF/ID and ID/EX to bubbles) and redirect the PC to the branch target. Predict-not-taken costs a flush only on taken branches.
// branch resolved in EX
wire take_branch = idex.branch && alu_zero_for_beq; // (or the right condition)
// flush the two younger instructions and redirect
assign flush = take_branch;
always @(posedge clk) begin
if (flush) begin
ifid.instr <= NOP; // squash fetched instruction
idex.ctrl <= '0; // squash decoded instruction
end
if (take_branch) pc <= idex.pc + idex.imm; // redirect to target
endThe pipeline is now complete
With forwarding (most data hazards), one-cycle stall (load-use), and flush (taken branches), ChipX's control is the *full* real-pipeline story you drew on paper in Stage 1. Resolving branches earlier (moving the compare to ID) would shrink the penalty — a documented trade you can mention — but predict-not-taken keeps the frozen scope and is honest.
Progress for Day 90
With predict-not-taken, what must happen when a branch resolves as taken?