testbench
`timescale 1ns / 1ps //仿真时单位时间1ns,精度1ps
module testbench;
reg [3:0] inCode;
reg [31:0] src1;
reg [31:0] src2;
wire [7:0] control;
wire [31:0] result;
decoder decoder_module (
.inCode(inCode),
.outCode(control)
);
alu test(
.alu_control(control),
.alu_src1(src1),
.alu_src2(src2),
.alu_result(result)
);
initial begin
src1 = 0;
src2 = 0;
//等待100ns出结果
#100;
end
always #10 inCode = {$random} % 8;
always #10 src1 = $random; //每过10ns,产生一个随机的 32 位数
always #10 src2 = $random;
endmodule
decoder
`timescale 1ns / 1ps
module decoder(
input [3:0] inCode,
output reg [7:0] outCode
);
always @(inCode)
begin
case(inCode)
4'b0000:outCode<=8'b00000001;
4'b0001:outCode<=8'b00000010;
4'b0010:outCode<=8'b00000100;
4'b0011:outCode<=8'b00001000;
4'b0100:outCode<=8'b00010000;
4'b0101:outCode<=8'b00100000;
4'b0110:outCode<=8'b01000000;
4'b0111:outCode<=8'b10000000;
endcase
end
endmodule
alu
`timescale 1ns / 1ps
module alu(
input [7:0] alu_control,
input [31:0] alu_src1,
input [31:0] alu_src2,
output reg [31:0] alu_result
);
wire alu_add;
assign alu_add = alu_control[4];
wire [31:0] adder_operand1;
wire [31:0] adder_operand2;
wire adder_cin ;
wire [31:0] adder_result ;
wire adder_cout ;
assign adder_operand1 = alu_src1;
assign adder_operand2 = alu_add ? alu_src2 : ~alu_src2;
assign adder_cin = ~alu_add; //减法需要cin
adder adder_module(
.operand1(adder_operand1),
.operand2(adder_operand2),
.cin (adder_cin ),
.result (adder_result ),
.cout (adder_cout )
);
assign add_sub_result = adder_result;
always @(*)
begin
case(alu_control)
8'b00000001:alu_result<=alu_src1&alu_src2;//按位与
8'b00000010:alu_result<=alu_src1|alu_src2;//按位或
8'b00000100:alu_result<=alu_src1^alu_src2;//按位异或
8'b00001000:alu_result<=~alu_src1;//按位非
8'b00010000:alu_result<=adder_result;//加减
8'b00100000:alu_result<=adder_result;
8'b01000000:alu_result<=alu_src1>>>alu_src2;//算术右移
8'b10000000:alu_result<=alu_src1<<alu_src2; // 逻辑左移
endcase
end
endmodule
adder
`timescale 1ns / 1ps
module adder(
input [31:0] operand1,
input [31:0] operand2,
input cin,
output [31:0] result,
output cout
);
assign {cout,result} = operand1 + operand2 + cin;
endmodule