HazardHandling.v 1.96 KB
// Data Hazard Handling
module Stall(clk, in_ex_regwrite, in_mem_regwrite, in_wb_regwrite, 
	in_readreg_num1, in_readreg_num2, in_ex_writereg_num, in_mem_writereg_num, in_wb_writereg_num, 
	out_stallsignal);
input clk;
input in_ex_regwrite, in_mem_regwrite, in_wb_regwrite;
input[4:0] in_readreg_num1, in_readreg_num2, in_ex_writereg_num, in_mem_writereg_num, in_wb_writereg_num;
output reg out_stallsignal;

initial out_stallsignal = 1'b0;

always @(negedge clk) begin
	if((in_ex_regwrite==1'b1 && in_ex_writereg_num!=5'b00000) && (in_ex_writereg_num==in_readreg_num1 || in_ex_writereg_num==in_readreg_num2)) begin
		out_stallsignal = 1'b1;
	end else if((in_mem_regwrite==1'b1 && in_mem_writereg_num!=5'b00000) && (in_mem_writereg_num==in_readreg_num1 || in_mem_writereg_num==in_readreg_num2)) begin
		out_stallsignal = 1'b1;
	end else if((in_wb_regwrite==1'b1 && in_wb_writereg_num!=5'b00000) && (in_wb_writereg_num==in_readreg_num1 || in_wb_writereg_num==in_readreg_num2)) begin
		out_stallsignal = 1'b1;	
	end else out_stallsignal = 1'b0;
end

endmodule


// Control Hazard Handling
module Flush(clk, ctrl_jump, ctrl_jumpreg, ctrl_branch, ex_branchsignal, pc_jump, pc_jumpreg, ex_pc_branch, 
	out_flush_jump, out_flush_branch, out_pc);
input clk;

input ctrl_jump, ctrl_jumpreg, ex_branchsignal;
input[2:0] ctrl_branch;
input[31:0] pc_jump, pc_jumpreg, ex_pc_branch;

output reg out_flush_jump, out_flush_branch;
output reg[31:0] out_pc;

reg isbranch;

initial begin
	isbranch = 1'b0;
	out_flush_jump = 1'b0;
	out_flush_branch = 1'b0;
	out_pc = 32'h00000000;
end

always @(negedge clk) begin
	if(isbranch == 1'b1) begin
		if(ex_branchsignal == 1'b1) begin
			out_pc = ex_pc_branch;
			out_flush_branch = 1'b1;
		end
		isbranch = 1'b0;
	end else begin
		out_flush_branch = 1'b0;

		if(ctrl_jump == 1'b1) begin
			out_flush_jump = 1'b1;
			out_pc = (ctrl_jumpreg == 1'b0) ? pc_jump : pc_jumpreg;
		end else if(ctrl_branch != 3'b000) isbranch = 1'b1;
		else out_flush_jump = 1'b0;
	end
end
endmodule