Decoding is the step where a 32-bit instruction word becomes something the datapath can act on: register numbers, a constant, and a set of control signals that steer the multiplexers, choose the ALU operation and enable the writes. In this core, decoding is split between two modules: the immediate generator, which pulls the constant out of the instruction and sign-extends it, and the decoder, which produces the register numbers and control signals. This article specifies both, for exercises E04 and E05, works through five real instruction words from compiled programs, and points out the one bit that trips up most first decoders.

15 min read | Beginner to Intermediate

What You'll Learn

  • Extract the register fields of any RV32I instruction and explain why they never move
  • Assemble the I, S, B, U and J immediates from their scattered bits and sign-extend them
  • Derive every control signal of the decoder for each kind of instruction, including which ones do not matter
  • Explain how bit 30 selects SUB and SRA, and why it must be ignored for addi

Before You Start

You need Verilog's concatenation and replication operators ({a, b} and {20{x}}) and case statements; the Verilog Tutorial covers both.

This article relies on RISC-V Instruction Formats and Encoding, which explains the six instruction formats and how to encode an instruction by hand, and on The Datapath: ALU, Multiplexers and Control, which introduces control signals. The ALU operation codes come from The ALU; you can write these two modules before or after the ALU exercises.

What Decoding Produces

Every instruction tells the datapath three kinds of thing. Which registers: up to two sources and one destination. Which constant, if any: the immediate. And what to do: which ALU operation, which operands, whether to read or write memory, whether to write a register and with what, whether to jump. The first two are fields of the instruction; the third has to be worked out from the opcode and the function fields.

The register fields are the easy part, because RISC-V keeps them in the same place in every format: rs1 is always bits 19 to 15, rs2 bits 24 to 20, rd bits 11 to 7, and funct3 bits 14 to 12. The decoder passes them through unchanged. An instruction that has no rs2, such as addi, still has bits 24 to 20; they are part of its immediate, and the register file reads some register that nothing uses. That is harmless, and it is the reason the fields can be fixed: the register file can start reading before the decoder has decided what the instruction is.

The Immediate Generator

The immediate generator takes the instruction and returns its constant as a 32-bit value:

module cvr32_imm (
    input  logic [31:0] instr,   // the instruction
    output logic [31:0] imm      // its immediate, sign-extended to 32 bits
);

It chooses the format from the opcode, bits 6 to 0. I-type immediates belong to the register-immediate ALU instructions, the loads and jalr; S-type to the stores; B-type to the branches; U-type to lui and auipc; J-type to jal. Register-register instructions have no immediate, and for them and every unknown opcode the output is 0.

Five rows show how the 32-bit immediate is built for each format: I-type from instruction bits 31 to 20, S-type from bits 31 to 25 and 11 to 7, B-type from bit 31, bit 7, bits 30 to 25, bits 11 to 8 and a zero, U-type from bits 31 to 12 and twelve zeros, J-type from bit 31, bits 19 to 12, bit 20, bits 30 to 21 and a zero, with sign-extension bits copied from instruction bit 31.

Three rules make the picture easier to remember. First, the sign of every immediate is instruction bit 31, in every format, so sign extension always copies bit 31. Second, the bits that are not in the register fields are reused as immediate bits, which is why the S, B and J immediates are scattered: the encoding moves the immediate around the fixed register fields, not the other way round. Third, branch and jump offsets are always even, because instructions are at least 2 bytes apart in RISC-V, so their bit 0 is not stored and is always 0. The B-type immediate covers -4,096 to +4,094 bytes, the J-type -1 MB to almost +1 MB.

In Verilog, each format is one concatenation: the sign-extension bits made with the replication operator, then the instruction bits in the order of the picture. The generator then picks one of the five with a case on the opcode, with 0 as the default.

Five Real Examples

These words come from the listings of programs the exercises run:

WordInstructionFormatImmediate bitsimm
0x0B428293addi t0, t0, 180Iinstr[31:20] = 0000_1011_0100180
0x00812C23sw s0, 24(sp)Sinstr[31:25] = 0000000, instr[11:7] = 1100024
0xFE071AE3bnez a4, back 12 bytesBbit 31 = 1, bit 7 = 1, instr[30:25] = 111111, instr[11:8] = 1010, then 0-12 (0xFFFF_FFF4)
0xF00006B7lui a3, 0xf0000Uinstr[31:12] = 0xF0000, then twelve zeros0xF000_0000
0xFEDFF06Fj, back 20 bytesJbit 31 = 1, instr[19:12] = 1111_1111, bit 20 = 1, instr[30:21] = 1111110110, then 0-20 (0xFFFF_FFEC)

The branch is the print loop of the lab's template program, at address 0x90: -12 takes it back to 0x84, the top of the loop. The jump is from the start-up code, at 0x38, back to 0x24. The sw saves a register 24 bytes above the stack pointer in the linked-list program, and the lui builds the CONSOLE address. In each case, the immediate generator's only job is to put those bits in the right places; the datapath adds them to the PC or a register.

Quick Check

Q: A B-type immediate is built from bit 31, bit 7, bits 30 to 25 and bits 11 to 8. Where in the immediate does instruction bit 7 go, and what is the largest forward branch offset?

Show Answer

Instruction bit 7 becomes immediate bit 11. The immediate has 13 significant bits (12 down to 1, plus the implied 0) and is signed, so the largest positive value is 0 followed by twelve 1s: 4,094 bytes.

The Decoder

The decoder's ports are the register fields and the control signals:

module cvr32_decode (
    input  logic [31:0] instr,
    output logic [4:0]  rs1,
    output logic [4:0]  rs2,
    output logic [4:0]  rd,
    output logic [2:0]  funct3,     // load/store size or branch condition
    output logic [3:0]  alu_op,     // ALU operation code (the same codes as cvr32_alu)
    output logic [1:0]  a_sel,      // ALU operand A: 0 = rs1, 1 = PC, 2 = zero
    output logic        b_imm,      // ALU operand B: 1 = immediate, 0 = rs2
    output logic        reg_write,
    output logic [1:0]  wb_sel,     // value written to rd: 0 = ALU, 1 = load data, 2 = PC + 4
    output logic        mem_read,
    output logic        mem_write,
    output logic        is_branch,
    output logic        is_jal,
    output logic        is_jalr
);

Like the ALU and the immediate generator, it is combinational. Its control signals for each kind of instruction follow from what the instruction does. Every 1-bit output not listed is 0; an output marked "any" is not used for that instruction, so its value does not matter and is not checked:

KindOpcodeControl signals
lui0110111alu_op ADD, a_sel 2 (zero), b_imm 1, reg_write 1, wb_sel 0
auipc0010111alu_op ADD, a_sel 1 (PC), b_imm 1, reg_write 1, wb_sel 0
jal1101111is_jal 1, reg_write 1, wb_sel 2; alu_op, a_sel, b_imm any
jalr1100111is_jalr 1, alu_op ADD, a_sel 0, b_imm 1, reg_write 1, wb_sel 2
branches1100011is_branch 1; alu_op, a_sel, b_imm, wb_sel any
loads0000011mem_read 1, alu_op ADD, a_sel 0, b_imm 1, reg_write 1, wb_sel 1
stores0100011mem_write 1, alu_op ADD, a_sel 0, b_imm 1; wb_sel any
register-immediate0010011alu_op from funct3, a_sel 0, b_imm 1, reg_write 1, wb_sel 0
register-register0110011alu_op from funct3 and bit 30, a_sel 0, b_imm 0, reg_write 1, wb_sel 0
anything elseall 1-bit outputs 0; alu_op, a_sel, b_imm, wb_sel any

Read each line as a sentence about the datapath. A load adds rs1 and the immediate in the ALU, reads memory at that address, and writes what it read into rd. jal writes PC + 4 into rd (the return address) and tells the PC logic to jump; the jump target, PC + immediate, is computed outside the ALU, so the ALU's settings do not matter. A branch writes nothing. "Anything else" covers fence, ecall, ebreak and opcodes that do not exist: with every enable at 0, they change nothing, which is how this core treats instructions it does not implement.

The "any" entries are a real design freedom. A decoder that sets b_imm to 1 for branches is exactly as correct as one that sets it to 0, because nothing uses the ALU result of a branch. Real decoders use such don't-care values to make their logic smaller.

The ALU Operation and Bit 30

For the two arithmetic opcodes, the ALU operation comes from funct3:

funct3000001010011100101110111
OperationADD (or SUB)SLLSLTSLTUXORSRL (or SRA)ORAND

Eight values of funct3 are not enough for ten operations, so two of them share a funct3 and are told apart by instruction bit 30, the second-highest bit of the funct7 field. With funct3 101, bit 30 = 1 means SRA and 0 means SRL, for both the register and the immediate forms: in srai, the immediate's upper seven bits are 0100000, and only its low 5 bits are the shift amount. Compare two words from the ALU test program: 0x01F8D913 is srli s2, a7, 31 and 0x41F8D993 is srai s3, a7, 31; they differ only in bit 30.

With funct3 000, bit 30 = 1 means SUB, but only for the register-register opcode. There is no "subtract immediate" in RISC-V, because adding a negative immediate does the same. For addi, bit 30 is simply bit 10 of the immediate. Take li sp, -1, which the assembler encodes as addi sp, zero, -1: 0xFFF00113. Its immediate is all ones, so bit 30 is 1. A decoder that turns funct3 000 with bit 30 set into SUB for every opcode computes 0 - (-1) = 1 instead of -1, and the first program that loads a negative constant goes wrong.

Quick Check

Q: Give the decoder's outputs for sw s0, 24(sp), word 0x00812C23: rs1, rs2, funct3, alu_op, a_sel, b_imm, reg_write, mem_read and mem_write.

Show Answer

rs1 = 2 (sp, bits 19 to 15), rs2 = 8 (s0, bits 24 to 20), funct3 = 010 (word), alu_op = ADD (0), a_sel = 0, b_imm = 1, reg_write = 0, mem_read = 0, mem_write = 1. The ALU computes sp + 24, and the register file's second port supplies the value to store. The rd field (bits 11 to 7, here 11000) is part of the immediate for a store, and reg_write = 0 makes sure nothing is written.

Writing the Two Modules

Both modules are combinational, so the advice from the ALU applies: write them with continuous assignments or combinational blocks, and make sure every output gets a value on every path. For the decoder, the simplest structure is a block that first sets every output to a safe default (all enables 0, ALU ADD, and so on) and then, in a case on the opcode, changes only the outputs that differ for that kind of instruction. That structure cannot produce a latch, and it reads almost exactly like the table above. Decode the funct3-to-operation mapping once and use it for both arithmetic opcodes, adding the bit 30 rules where they apply.

How It Is Tested

E04 tests the immediate generator with every distinct 32-bit word in the compiled test programs and workloads, 476 of them, including data words whose low 7 bits happen to look like some opcode, and then with 200 random words under each of ten opcodes (the eight with immediates, the register-register one and fence), with the sign bit both set and clear: 2,476 checks in all. Every failure message gives the word, its format, and the expected and actual immediate.

E05 tests the decoder with 256 random instructions under each of twelve opcodes, including fence, system and one that does not exist, with legal funct7 values for the instructions that use them. That is 3,072 instructions, and for each one every output except the "any" ones is compared: 37,888 checks. A message names the instruction word, its kind, the output and both values.

The tests were checked against typical mistakes. For E04: an I immediate that is not sign-extended, an S immediate whose low bits come from the rs2 field, a B immediate with bit 11 taken from instruction bit 31, a J immediate missing its zero bit. For E05: addi with bit 30 decoded as SUB, srai decoded as srli, jalr writing the ALU result instead of PC + 4, loads that do not write rd, and auipc adding to zero instead of the PC. Each one fails.

Where Does This Matter?

The regularity you just used, register fields in fixed places and the sign always in bit 31, is a deliberate design choice of RISC-V, and it pays off in hardware: the register file read and the sign extension can start before the decoder knows what the instruction is. Instruction sets with variable-length instructions, such as x86, need far more complex decoders, which in high-performance cores take several pipeline stages of their own. ISA Design Choices: RISC, CISC and Extensions compares the two approaches.

Common Mistakes

Mistake #1: Treating bit 30 as SUB for every opcode

Bit 30 selects SUB only for register-register instructions with funct3 000. For addi it is an immediate bit, and any negative constant sets it.

Mistake #2: Getting the B and J immediates wrong by one bit

The B and J immediates end with an implied 0: the instruction stores bits 12 to 1 (or 20 to 1), not 11 to 0. Forgetting the zero, or placing instruction bit 7 or bit 20 in the wrong position, makes every branch or jump land in the wrong place, typically by a factor of two or by 2,048 bytes.

Mistake #3: Leaving outputs unassigned for some opcodes

A decoder that sets mem_write only in the store branch of its case has made a latch: after the first store it keeps writing memory. Set every output first, then override it.

Your Turn in the Lab

Both exercises open with a visible test, testbench.v, next to your design: a short list of directed checks that prints ok or FAIL for each. Simulate it as you work and add your own checks to it. When you submit, it runs together with the hidden tests, and your edits to it do not change the grading.

Write the two modules in two exercises:

  1. E04: cvr32_imm. Check your five formats against the table of real words above before you submit.
  2. E05: cvr32_decode, using the control table. The ALU codes are the ones from E01 and E02; the starter declares them.

Keep both in your project. With the ALU and the register file, you then have every block that the first core exercise, E07, needs except the program counter.

Open exercise E04 in ChipVerify Lab Open exercise E05 in ChipVerify Lab

Summary

  • RISC-V keeps rs1, rs2, rd and funct3 at fixed positions in every format, so the decoder passes them through and the register file can read early.
  • The immediate generator picks one of five formats from the opcode; every immediate is sign-extended from bit 31, and B and J immediates have an implied 0 in bit 0.
  • The decoder sets the ALU operation, operand selects, write-back select and enables for each kind of instruction; outputs an instruction does not use are don't-cares.
  • Bit 30 selects SRA over SRL for both shift forms and SUB over ADD only for register-register instructions; for addi it is part of the immediate.
  • Unknown instructions, fence, ecall and ebreak get all enables at 0 and change nothing.
Did you find what you were looking for?

Quiz

No quiz questions available for this article.