S SmartDocs
시리즈: RISC V Hardware verilog 45 줄 · 업데이트 2026-07-04

imm_gen.v

RISC_V_Hardware/verilog/rtl/imm_gen.v

// ============================================================
// imm_gen.v -- immediate generator for the 6 RV32I formats
// Sign bit is always instr[31] (by ISA design).
// ============================================================
`timescale 1ns/1ps

module imm_gen (
    input  wire [31:0] instr,
    output reg  [31:0] imm
);
    wire [6:0] opcode = instr[6:0];

    localparam OP_IMM  = 7'b0010011;
    localparam OP_LOAD = 7'b0000011;
    localparam OP_JALR = 7'b1100111;
    localparam OP_STORE= 7'b0100011;
    localparam OP_BR   = 7'b1100011;
    localparam OP_LUI  = 7'b0110111;
    localparam OP_AUIPC= 7'b0010111;
    localparam OP_JAL  = 7'b1101111;

    always @(*) begin
        case (opcode)
            // I-type: imm[11:0] = instr[31:20]
            OP_IMM, OP_LOAD, OP_JALR:
                imm = {{20{instr[31]}}, instr[31:20]};
            // S-type: imm[11:5|4:0] = instr[31:25|11:7]
            OP_STORE:
                imm = {{20{instr[31]}}, instr[31:25], instr[11:7]};
            // B-type: imm[12|10:5|4:1|11] = instr[31|30:25|11:8|7], imm[0]=0
            OP_BR:
                imm = {{19{instr[31]}}, instr[31], instr[7],
                       instr[30:25], instr[11:8], 1'b0};
            // U-type: imm[31:12] = instr[31:12]
            OP_LUI, OP_AUIPC:
                imm = {instr[31:12], 12'b0};
            // J-type: imm[20|10:1|11|19:12] = instr[31|30:21|20|19:12]
            OP_JAL:
                imm = {{11{instr[31]}}, instr[31], instr[19:12],
                       instr[20], instr[30:21], 1'b0};
            default:
                imm = 32'b0;
        endcase
    end
endmodule

관련 글