Control: The Main Decoder and the ALU Decoder

The last two pages were handed their control signals. This page makes them. All of control turns out to be one small table, and a second, smaller one for the ALU.

You Will Be Able To

  • Read the control table: one row for each opcode, one column for each control signal.
  • Say what the main decoder and the ALU decoder each look at, and why there are two.
  • Predict what breaks when one entry of the table is wrong.
Lesson
S2.5
Time
30 min
Runs on
Icarus service
Check
6 questions

The datapath can do six kinds of thing, and it does none of them by itself. Eight wires tell it what this instruction needs. Get one of those wires wrong for one kind of instruction, and one kind of program fails while the others still pass.

Before You Start

You need the full datapath of S2.21, and its eight control signals.

You need the fields of a word from S2.2: the opcode, funct3 and funct7. The opcode is in bits 6 to 0, funct3 in bits 14 to 12, and funct7 in bits 31 to 25.

Five questions this page answers
Question
1What does one row of the control table stand for, and one column?
2Which bits of the word does the main decoder look at?
3Which bits does the ALU decoder look at?
4What does the ALU do for a load, a store or a branch?
5When does bit 30 of the word choose the ALU operation?

The Idea: Control Is a Table

Take every kind of instruction, and write down what it needs from the datapath. A load needs the memory read and the loaded value sent to rd. A store needs the memory written. Do that for each kind, and you have a table.

That is the control table. It has one row for each opcode, and one column for each control signal. An entry says what that signal must be for that kind of instruction.

The main decoder is this table built as logic. The opcode goes in. One row comes out, as seven wires. It has no clock and no memory.

One signal is not in that table: alu_operation. An add and a sub have the same opcode. They differ in funct3, and in one bit of funct7: bit 30 of the word. A second block, the ALU decoder, reads those bits.

Why two blocks? The core has 11 opcodes but 48 instructions. A table of 48 rows would repeat itself: all ten kinds of arithmetic on two registers need the same seven wires. Only the ALU operation differs among them.

New Words

New words on this page
WordMeaning
Control tableA table with one row for each opcode and one column for each control signal.
Main decoderThe logic that turns the opcode into the control signals of one row.
ALU decoderThe logic that picks the ALU operation from funct3 and bit 30.
Enable signalA control signal that lets something change: a register, a memory word or the PC. Called an enable for short. Here: reg_write, mem_read, mem_write, branch and jump.
Select signalA control signal that steers a multiplexer. Called a select for short. Here: alu_b_select and result_select.
OPThe opcode 0110011: arithmetic on two registers.
OP_IMMThe opcode 0010011: arithmetic with an immediate.
LOAD, STORE, BRANCH, JALThe opcodes 0000011, 0100011, 1100011 and 1101111.

One Picture: The Table and What It Steers

Two Decoders Steer the DatapathStep through the picture. Each step lights one row of the control table and the boxes that the row switches on.
  • Memory
  • Control / FSM
  • Processor
Two Decoders Steer the DatapathStep through the picture. Each step lights one row of the control table and the boxes that the row switches on. component Instruction word instr: 32 bits fromthe instructionmemory component Main decoder the control table: theopcode picks a row component ALU decoder picks one of ten ALUoperations component Register file obeys reg_write component ALU and operandselect obey alu_operationand alu_b_select component Data memory obeys mem_read andmem_write component Result select obeys result_select component Next-PC select obeys branch andjump opcode: bits 6 to 0funct3, and bit 30the opcode againreg_writealu_b_selectalu_operationmem_read, mem_writeresult_selectbranch, jump
  1. component Instruction wordinstr: 32 bits from the instruction memory
    • opcode: bits 6 to 0 → Main decoder
    • funct3, and bit 30 → ALU decoder
  2. component Main decoderthe control table: the opcode picks a row
    • the opcode again → ALU decoder
    • reg_write → Register file
    • alu_b_select → ALU and operand select
    • mem_read, mem_write → Data memory
    • result_select → Result select
    • branch, jump → Next-PC select
  3. component ALU decoderpicks one of ten ALU operations
    • alu_operation → ALU and operand select
  4. component Register fileobeys reg_write
  5. component ALU and operand selectobey alu_operation and alu_b_select
  6. component Result selectobeys result_select
  7. component Data memoryobeys mem_read and mem_write
  8. component Next-PC selectobeys branch and jump
  1. The row OP: add x7, x5, x6

    The opcode is 0110011. The row says: write rd, take rs2_data as the second operand, and send the ALU result to rd. The ALU decoder reads funct3 and bit 30, and says add.

  2. The row LOAD: lw x5, 0(x10)

    The opcode is 0000011. The row says: take the immediate, read the memory, send the loaded value to rd, and write rd. The ALU decoder says add, as for every load.

  3. The row STORE: sw x6, 4(x10)

    The opcode is 0100011. The row says: take the immediate and write the memory. The enable reg_write is 0, so no register changes.

  4. The row BRANCH: bne x5, x0, 0x10

    The opcode is 1100011. The row has one 1: branch. The next-PC select may now take the target. Nothing is written anywhere.

  5. The row JAL: jal x1, 0x28

    The opcode is 1101111. The row says: jump, send the PC plus 4 to rd, and write rd.

Read the diagram as text
  • Instruction word: instr: 32 bits from the instruction memory
  • Main decoder: the control table: the opcode picks a row
  • ALU decoder: picks one of ten ALU operations
  • Register file: obeys reg_write
  • ALU and operand select: obey alu_operation and alu_b_select
  • Data memory: obeys mem_read and mem_write
  • Result select: obeys result_select
  • Next-PC select: obeys branch and jump
  • Instruction word → Main decoder: opcode: bits 6 to 0
  • Instruction word → ALU decoder: funct3, and bit 30
  • Main decoder → ALU decoder: the opcode again
  • Main decoder → Register file: reg_write
  • Main decoder → ALU and operand select: alu_b_select
  • ALU decoder → ALU and operand select: alu_operation
  • Main decoder → Data memory: mem_read, mem_write
  • Main decoder → Result select: result_select
  • Main decoder → Next-PC select: branch, jump

The main decoder sees seven bits of the word. The ALU decoder sees four more.

The control table of this page
Row (opcode)reg_writealu_b_selectresult_selectmem_readmem_writebranchjump
OP10: rs2_data0: ALU0000
OP_IMM11: immediate0: ALU0000
LOAD11: immediate1: memory1000
STORE01: immediate00100
BRANCH0100010
JAL112: PC plus 40001

Six of the 11 opcodes of ap_rv32. Some entries are never used by the datapath: the next lesson is about those.

The Smallest Example, Worked by Hand

Decode one word by hand: 00052283. It is lw x5, 0(x10).

From the word to the wires
StepWhat you readWhat you get
1Bits 6 to 0 are 0000011the row LOAD
2The row LOADreg_write 1, alu_b_select 1, result_select 1, mem_read 1, the rest 0
3The opcode is not OP and not OP_IMMthe ALU decoder says add

The funct3 of this word is 010. The ALU decoder does not look at it for a load.

Now 405303b3. It is sub x7, x6, x5. Bits 6 to 0 are 0110011: the row OP. For this row the ALU decoder does look. Its funct3 is 000 and its bit 30 is 1. Together they say sub.

The Rules

  1. Rule 1: The opcode alone picks the row of the control table.

    The main decoder looks at bits 6 to 0 and at nothing else.

  2. Rule 2: An enable is 1 only in the rows that need it.

    Every enable that is 1 by mistake changes a register, a memory word or the PC.

  3. Rule 3: For every row except OP and OP_IMM, the ALU adds.

    A load and a store add for the address. In a branch or a jal the ALU result is not used.

  4. Rule 4: For OP, the ALU operation is bit 30 and funct3 together.

    Bit 30 tells add from sub, and srl from sra.

  5. Rule 5: For OP_IMM, it is funct3. Bit 30 counts only for a shift right.

    In every other word with an immediate, bit 30 is a bit of the immediate.

  6. Rule 6: Both decoders work beside the register read.

    They need only the word. So they cost no extra time.

Rule 4 is built into the constants of the core. Read the comment, then the ten values.

From ap_rv32_pkg.sv. The low three bits of each value are the funct3 of that instruction.
// ---- alu_operation: bit 3 is instruction bit 30, bits 2:0 are funct3
localparam logic [3:0] ALU_ADD  = 4'b0000;
localparam logic [3:0] ALU_SUB  = 4'b1000;
localparam logic [3:0] ALU_SLL  = 4'b0001;
localparam logic [3:0] ALU_SLT  = 4'b0010;
localparam logic [3:0] ALU_SLTU = 4'b0011;
localparam logic [3:0] ALU_XOR  = 4'b0100;
localparam logic [3:0] ALU_SRL  = 4'b0101;
localparam logic [3:0] ALU_SRA  = 4'b1101;
localparam logic [3:0] ALU_OR   = 4'b0110;
localparam logic [3:0] ALU_AND  = 4'b0111;

So for the row OP, the ALU decoder is four wires and no gates. The designer chose the ten numbers to make that true.

The decoder of the real core is not printed on this page. The practice problem asks you to write it.

Sources for These Rules

The split into a main decoder and an ALU decoder is described here as textbooks commonly describe it. The plan of this track points to Patterson and Hennessy, section 4.4, and to Harris and Harris, section 7.3. Those places are not checked. The places of the opcode, funct3 and bit 30 in a word are as in S2.2. They are not checked against the RISC-V specifications, which are not in the reference library. Every signal name, every table entry and every printed row was compared with the decoder inside ap_rv32_sc.

Now Run It

The lab at the end of this page holds the table as a function of the opcode. It prints the six rows. Then it runs three test programs and compares one or two values of each with the right ones.

Printed by the lab on Icarus. The six rows equal the outputs of the decoder inside the real ap_rv32_sc. The three programs end in the same state there.
OP     | reg_write=1 alu_b_select=0 result_select=00 mem_read=0 mem_write=0 branch=0 jump=0
OP_IMM | reg_write=1 alu_b_select=1 result_select=00 mem_read=0 mem_write=0 branch=0 jump=0
LOAD   | reg_write=1 alu_b_select=1 result_select=01 mem_read=1 mem_write=0 branch=0 jump=0
STORE  | reg_write=0 alu_b_select=1 result_select=00 mem_read=0 mem_write=1 branch=0 jump=0
BRANCH | reg_write=0 alu_b_select=1 result_select=00 mem_read=0 mem_write=0 branch=1 jump=0
JAL    | reg_write=1 alu_b_select=1 result_select=10 mem_read=0 mem_write=0 branch=0 jump=1
arithmetic | x8 = 00000007, should be 00000007 | pass
memory | x9 = 0000003a, should be 0000003a | mem[80000008] = 00000012, should be 00000012 | pass
loop | x6 = 00000006, should be 00000006 | pass

Rule 2 at work: read the column reg_write downward. It is 0 in two rows: STORE and BRANCH.

Rule 1 at work: the programs hold 18 instructions, and the table has six rows. Every addi, slli and other word of the opcode OP_IMM uses the same row.

The lab is still given its ALU operation. Here is the real ALU decoder at work. Each row shows one word of a program, and the operation that the decoder inside the real core chose.

Recorded inside the real ap_rv32_sc on Icarus. The decoder itself is not shown.
00100513 | addi x10, x0, 1 | funct3 000, bit 30 is 0 | ALU_ADD
01f51513 | slli x10, x10, 31 | funct3 001, bit 30 is 0 | ALU_SLL
40000293 | addi x5, x0, 1024 | funct3 000, bit 30 is 1 | ALU_ADD
00528333 | add x6, x5, x5 | funct3 000, bit 30 is 0 | ALU_ADD
405303b3 | sub x7, x6, x5 | funct3 000, bit 30 is 1 | ALU_SUB
4002c413 | xori x8, x5, 1024 | funct3 100, bit 30 is 1 | ALU_XOR
0022d493 | srli x9, x5, 2 | funct3 101, bit 30 is 0 | ALU_SRL
40455593 | srai x11, x10, 4 | funct3 101, bit 30 is 1 | ALU_SRA
4012a613 | slti x12, x5, 1025 | funct3 010, bit 30 is 1 | ALU_SLT
005376b3 | and x13, x6, x5 | funct3 111, bit 30 is 0 | ALU_AND
00052703 | lw x14, 0(x10) | funct3 010, bit 30 is 0 | ALU_ADD
00e52223 | sw x14, 4(x10) | funct3 010, bit 30 is 0 | ALU_ADD
fc5298e3 | bne x5, x5, 0x0 | funct3 001, bit 30 is 1 | ALU_ADD

Rule 4 at work: rows 4 and 5. An add and a sub have the same funct3. Bit 30 tells them apart.

Rule 5 at work: row 3. This addi has the immediate 1024, and that sets bit 30 of the word. The ALU still adds. Rows 6 and 9 are the same case.

Rule 5 again: rows 7 and 8, srli and srai. Here bit 30 does count, as in rule 4.

Rule 3 at work: the last three rows. The lw has funct3 010, which would say slt in the row OP. The decoder ignores it and says add.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
Two decodersOne table with a row for each of 48 instructions11 rows in place of 48. Two blocks to keep in step.
The opcode alone picks the rowThe main decoder also reads funct3Each column is logic of only seven inputs. The instruction set had to be laid out for that.
alu_operation is bit 30 and funct3A free numbering of the ten operationsThe ALU decoder for OP is wires. The ALU must use these numbers.
A table built as fixed logicA small memory that holds the tableFast, and small for a simple instruction set. Changing it means changing the chip.
Enables are 0 unless a row sets themEvery row lists every signalA new row cannot write by accident. The reader must know the starting values.

The Trap: The Load That Returned Its Address

A designer adds the row LOAD. A load looks much like an addi: both add rs1_data and an immediate, and both write rd. So the designer copies the row OP_IMM and sets mem_read to 1.

One entry is forgotten. In the copied row, result_select still says 0: the ALU result. Here is the lab with that table.

The same lab with one changed entry. The real core gives the same values when its decoder has the same change.
OP     | reg_write=1 alu_b_select=0 result_select=00 mem_read=0 mem_write=0 branch=0 jump=0
OP_IMM | reg_write=1 alu_b_select=1 result_select=00 mem_read=0 mem_write=0 branch=0 jump=0
LOAD   | reg_write=1 alu_b_select=1 result_select=00 mem_read=1 mem_write=0 branch=0 jump=0
STORE  | reg_write=0 alu_b_select=1 result_select=00 mem_read=0 mem_write=1 branch=0 jump=0
BRANCH | reg_write=0 alu_b_select=1 result_select=00 mem_read=0 mem_write=0 branch=1 jump=0
JAL    | reg_write=1 alu_b_select=1 result_select=10 mem_read=0 mem_write=0 branch=0 jump=1
arithmetic | x8 = 00000007, should be 00000007 | pass
memory | x9 = 80000029, should be 0000003a | mem[80000008] = 80000001, should be 00000012 | FAIL
loop | x6 = 00000006, should be 00000006 | pass

Read the row LOAD. It differs from the right table in one place: result_select is 00, not 01.

Now read the three programs. Two still pass. They hold no load, so they never use the bad row.

The memory program fails in both its values. Its lw must bring 17 from address 8000_0000. With this table, rd takes the ALU result, and for a load that is the address. So x5 holds 8000_0000, not 17.

The rest follows. The program adds 1 and stores the sum: the memory holds 8000_0001. Then it adds 40: x9 holds 8000_0029.

One wrong entry breaks one kind of instruction. A set of tests finds it only if some test uses that row and looks at what the row changes.

At Scale

This page6 rows, 7 columns and the ALU operation
ap_rv32_decode11 opcodes, 24 outputs

This section looks ahead. The table of this page has six rows and seven columns. The real one is larger in both directions.

  1. More rows

    The instructions jalr, lui and auipc need rows of their own, and two more select signals. The practice problem adds them.

  2. Words that are not instructions

    A real decoder must also say when a word fits no row. The next lesson covers that.

  3. Control that travels

    In a pipeline, an instruction takes five cycles. Its control signals must travel with it from stage to stage: S2.7.

  4. Larger instruction sets

    Some processors have thousands of instruction forms. Their decoders need a whole clock cycle or more: S2.15.

Try It

Run the lab. Then change one entry of one row. Before you run again, say which of the three programs will fail.

Set mem_write to 1 in the row LOAD. Which value of the memory program changes, and why not the other?

Find an entry that you can change without any program failing. The next lesson explains what you found.

RUNIcarus Verilog · simulator service
Edit the code, then run it
Expected: OP | reg_write=1 alu_b_select=0 result_select=00 mem_read=0 mem_write=0 branch=0 jump=0 OP_IMM | reg_write=1 alu_b_select=1 result_select=00 mem_read=0 mem_write=0 branch=0 jump=0 LOAD | reg_write=1 alu_b_select=1 result_select=01 mem_read=1 mem_write=0 branch=0 jump=0 STORE | reg_write=0 alu_b_select=1 result_select=00 mem_read=0 mem_write=1 branch=0 jump=0 BRANCH | reg_write=0 alu_b_select=1 result_select=00 mem_read=0 mem_write=0 branch=1 jump=0 JAL | reg_write=1 alu_b_select=1 result_select=10 mem_read=0 mem_write=0 branch=0 jump=1 arithmetic | x8 = 00000007, should be 00000007 | pass memory | x9 = 0000003a, should be 0000003a | mem[80000008] = 00000012, should be 00000012 | pass loop | x6 = 00000006, should be 00000006 | pass
Read included file: ap_rv32_pkg.sv
// ap_rv32_pkg: the named constants of the ap_rv32 core.
// Opcodes, function fields, control-signal values, trap causes and CSR addresses.
// Used by both builds (ap_rv32_sc and ap_rv32). Taught in S2.2 and S2.5.
// Blueprint: docs/soc/ap_rv32-blueprint.md sections 4 (instructions), 5 (CSRs) and 7 (traps).
package ap_rv32_pkg;

  // ---- Opcodes: instruction bits 6:0
  localparam logic [6:0] OPCODE_LUI      = 7'b0110111;
  localparam logic [6:0] OPCODE_AUIPC    = 7'b0010111;
  localparam logic [6:0] OPCODE_JAL      = 7'b1101111;
  localparam logic [6:0] OPCODE_JALR     = 7'b1100111;
  localparam logic [6:0] OPCODE_BRANCH   = 7'b1100011;
  localparam logic [6:0] OPCODE_LOAD     = 7'b0000011;
  localparam logic [6:0] OPCODE_STORE    = 7'b0100011;
  localparam logic [6:0] OPCODE_OP_IMM   = 7'b0010011;
  localparam logic [6:0] OPCODE_OP       = 7'b0110011;
  localparam logic [6:0] OPCODE_MISC_MEM = 7'b0001111;
  localparam logic [6:0] OPCODE_SYSTEM   = 7'b1110011;

  // ---- funct3 (instruction bits 14:12) of the branches
  localparam logic [2:0] FUNCT3_BEQ  = 3'b000;
  localparam logic [2:0] FUNCT3_BNE  = 3'b001;
  localparam logic [2:0] FUNCT3_BLT  = 3'b100;
  localparam logic [2:0] FUNCT3_BGE  = 3'b101;
  localparam logic [2:0] FUNCT3_BLTU = 3'b110;
  localparam logic [2:0] FUNCT3_BGEU = 3'b111;

  // ---- funct3 of the arithmetic instructions (OP and OP_IMM) that the decoder must tell apart.
  // All eight values are the low three bits of alu_operation, below.
  localparam logic [2:0] FUNCT3_ADD_SUB = 3'b000;
  localparam logic [2:0] FUNCT3_SLL     = 3'b001;
  localparam logic [2:0] FUNCT3_SRL_SRA = 3'b101;

  // ---- funct3 of JALR and FENCE. Loads and stores: bits 1:0 are mem_size, bit 2 is unsigned.
  // SYSTEM: 000 is ecall, ebreak, mret, wfi; else bits 1:0 are csr_operation, bit 2 is immediate.
  localparam logic [2:0] FUNCT3_JALR  = 3'b000;
  localparam logic [2:0] FUNCT3_FENCE = 3'b000;

  // ---- funct7 (instruction bits 31:25)
  localparam logic [6:0] FUNCT7_BASE = 7'b0000000;
  localparam logic [6:0] FUNCT7_ALT  = 7'b0100000; // sub, sra, srai

  // ---- Instructions matched on all 32 bits
  localparam logic [31:0] INSTR_ECALL  = 32'h0000_0073;
  localparam logic [31:0] INSTR_EBREAK = 32'h0010_0073;
  localparam logic [31:0] INSTR_MRET   = 32'h3020_0073;
  localparam logic [31:0] INSTR_WFI    = 32'h1050_0073;

  // ---- imm_select: which immediate format the instruction carries
  localparam logic [2:0] IMM_I = 3'd0;
  localparam logic [2:0] IMM_S = 3'd1;
  localparam logic [2:0] IMM_B = 3'd2;
  localparam logic [2:0] IMM_U = 3'd3;
  localparam logic [2:0] IMM_J = 3'd4;

  // ---- alu_operation: bit 3 is instruction bit 30, bits 2:0 are funct3
  localparam logic [3:0] ALU_ADD  = 4'b0000;
  localparam logic [3:0] ALU_SUB  = 4'b1000;
  localparam logic [3:0] ALU_SLL  = 4'b0001;
  localparam logic [3:0] ALU_SLT  = 4'b0010;
  localparam logic [3:0] ALU_SLTU = 4'b0011;
  localparam logic [3:0] ALU_XOR  = 4'b0100;
  localparam logic [3:0] ALU_SRL  = 4'b0101;
  localparam logic [3:0] ALU_SRA  = 4'b1101;
  localparam logic [3:0] ALU_OR   = 4'b0110;
  localparam logic [3:0] ALU_AND  = 4'b0111;

  // ---- alu_a_select and alu_b_select: the two ALU operands
  localparam logic [1:0] ALU_A_RS1  = 2'd0;
  localparam logic [1:0] ALU_A_PC   = 2'd1;
  localparam logic [1:0] ALU_A_ZERO = 2'd2;
  localparam logic       ALU_B_RS2  = 1'b0;
  localparam logic       ALU_B_IMM  = 1'b1;

  // ---- result_select: the value written to rd
  localparam logic [1:0] RESULT_ALU       = 2'd0;
  localparam logic [1:0] RESULT_MEM       = 2'd1;
  localparam logic [1:0] RESULT_PC_PLUS_4 = 2'd2;
  localparam logic [1:0] RESULT_CSR       = 2'd3;

  // ---- mem_size: bytes moved by a load or store (as AHB hsize)
  localparam logic [1:0] SIZE_BYTE = 2'd0;
  localparam logic [1:0] SIZE_HALF = 2'd1;
  localparam logic [1:0] SIZE_WORD = 2'd2;

  // ---- csr_operation: what a CSR instruction does with its operand
  localparam logic [1:0] CSR_OPERATION_NONE  = 2'd0; // not a CSR instruction
  localparam logic [1:0] CSR_OPERATION_WRITE = 2'd1;
  localparam logic [1:0] CSR_OPERATION_SET   = 2'd2;
  localparam logic [1:0] CSR_OPERATION_CLEAR = 2'd3;

  // ---- Trap causes: the value written to mcause (bit 31 marks an interrupt)
  localparam logic [31:0] CAUSE_INSTR_ADDR_MISALIGNED = 32'd0;
  localparam logic [31:0] CAUSE_INSTR_ACCESS_FAULT    = 32'd1;
  localparam logic [31:0] CAUSE_ILLEGAL_INSTRUCTION   = 32'd2;
  localparam logic [31:0] CAUSE_BREAKPOINT            = 32'd3;
  localparam logic [31:0] CAUSE_LOAD_ADDR_MISALIGNED  = 32'd4;
  localparam logic [31:0] CAUSE_LOAD_ACCESS_FAULT     = 32'd5;
  localparam logic [31:0] CAUSE_STORE_ADDR_MISALIGNED = 32'd6;
  localparam logic [31:0] CAUSE_STORE_ACCESS_FAULT    = 32'd7;
  localparam logic [31:0] CAUSE_ECALL_FROM_M          = 32'd11;
  localparam logic [31:0] CAUSE_IRQ_SOFTWARE          = 32'h8000_0003;
  localparam logic [31:0] CAUSE_IRQ_TIMER             = 32'h8000_0007;
  localparam logic [31:0] CAUSE_IRQ_EXTERNAL          = 32'h8000_000b;

  // ---- Bit positions in mstatus, and in mie and mip
  localparam int MSTATUS_MIE_BIT  = 3;
  localparam int MSTATUS_MPIE_BIT = 7;
  localparam int IRQ_SOFTWARE_BIT = 3;
  localparam int IRQ_TIMER_BIT    = 7;
  localparam int IRQ_EXTERNAL_BIT = 11;

  // ---- CSR addresses (blueprint 5.1)
  localparam logic [11:0] CSR_MSTATUS    = 12'h300;
  localparam logic [11:0] CSR_MISA       = 12'h301;
  localparam logic [11:0] CSR_MIE        = 12'h304;
  localparam logic [11:0] CSR_MTVEC      = 12'h305;
  localparam logic [11:0] CSR_MSTATUSH   = 12'h310;
  localparam logic [11:0] CSR_MSCRATCH   = 12'h340;
  localparam logic [11:0] CSR_MEPC       = 12'h341;
  localparam logic [11:0] CSR_MCAUSE     = 12'h342;
  localparam logic [11:0] CSR_MTVAL      = 12'h343;
  localparam logic [11:0] CSR_MIP        = 12'h344;
  localparam logic [11:0] CSR_MCYCLE     = 12'hb00;
  localparam logic [11:0] CSR_MINSTRET   = 12'hb02;
  localparam logic [11:0] CSR_MCYCLEH    = 12'hb80;
  localparam logic [11:0] CSR_MINSTRETH  = 12'hb82;
  localparam logic [11:0] CSR_MVENDORID  = 12'hf11;
  localparam logic [11:0] CSR_MARCHID    = 12'hf12;
  localparam logic [11:0] CSR_MIMPID     = 12'hf13;
  localparam logic [11:0] CSR_MHARTID    = 12'hf14;
  localparam logic [11:0] CSR_MCONFIGPTR = 12'hf15;
  // Performance monitors 3 to 31 exist and read 0: first and last address of each range
  localparam logic [11:0] CSR_MHPMEVENT3      = 12'h323;
  localparam logic [11:0] CSR_MHPMEVENT31     = 12'h33f;
  localparam logic [11:0] CSR_MHPMCOUNTER3    = 12'hb03;
  localparam logic [11:0] CSR_MHPMCOUNTER31   = 12'hb1f;
  localparam logic [11:0] CSR_MHPMCOUNTER3H   = 12'hb83;
  localparam logic [11:0] CSR_MHPMCOUNTER31H  = 12'hb9f;
  // Address bits 11:10 of a read-only CSR
  localparam logic [1:0]  CSR_READ_ONLY = 2'b11;

  // ---- CSR values and write masks (a 1 marks a bit that software can change)
  localparam logic [31:0] MSTATUS_RESET      = 32'h0000_1800; // MPP = 11: machine mode only
  localparam logic [31:0] MSTATUS_WRITE_MASK = 32'h0000_0088; // MIE and MPIE
  localparam logic [31:0] MISA_VALUE         = 32'h4000_0100; // 32 bits, extension I
  localparam logic [31:0] MIMPID_VALUE       = 32'h0001_0000; // ap_rv32 version 1.0
  localparam logic [31:0] MIE_WRITE_MASK     = 32'h0000_0888; // MSIE, MTIE and MEIE
  localparam logic [31:0] MTVEC_WRITE_MASK   = 32'hffff_fffd; // BASE and MODE bit 0
  localparam logic [31:0] MEPC_WRITE_MASK    = 32'hffff_fffc; // instructions are 4-byte aligned
  localparam logic [31:0] ALL_BITS           = 32'hffff_ffff;

  // ---- Data bits that a byte and a half cover, from bit 0
  localparam logic [31:0] BYTE_BITS = 32'h0000_00ff;
  localparam logic [31:0] HALF_BITS = 32'h0000_ffff;

  // ---- Other
  localparam logic [1:0] PRIV_MACHINE   = 2'b11; // the only privilege level in v1.0
  localparam int         REGISTER_COUNT = 32;

endpackage
Read included file: ap_rv32_regfile.sv
// ap_rv32_regfile: the register file.
// 31 registers, x1 to x31, and x0 which always reads 0. Two read ports, one write port.
// A read is combinational; a write happens at the clock edge. All registers reset to 0.
// Used by both builds. Taught in S2.4. Blueprint: sections 2.3 and 6.
module ap_rv32_regfile (
  input  logic        clk,          // clock
  input  logic        rst_n,        // reset, active low
  input  logic [4:0]  rs1_addr,     // first register to read
  output logic [31:0] rs1_data,     // its value
  input  logic [4:0]  rs2_addr,     // second register to read
  output logic [31:0] rs2_data,     // its value
  input  logic        write_enable, // write rd at this clock edge
  input  logic [4:0]  rd_addr,      // register to write; a write to x0 is discarded
  input  logic [31:0] rd_data       // value to write
);
  import ap_rv32_pkg::*;

  logic [31:0] registers_q [1:REGISTER_COUNT-1]; // x1 to x31; x0 has no storage

  always_ff @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
      for (int i = 1; i < REGISTER_COUNT; i++) registers_q[i] <= '0;
    end else if (write_enable && rd_addr != '0) begin
      registers_q[rd_addr] <= rd_data;
    end
  end

  assign rs1_data = (rs1_addr == '0) ? '0 : registers_q[rs1_addr];
  assign rs2_data = (rs2_addr == '0) ? '0 : registers_q[rs2_addr];

endmodule
Read included file: ap_rv32_alu.sv
// ap_rv32_alu: the arithmetic and logic unit.
// Add, subtract, shifts, compares and bitwise logic on two 32-bit operands.
// Used by both builds. Taught in S2.4. Blueprint: section 2.3.
module ap_rv32_alu (
  input  logic [3:0]  alu_operation, // operation: one of the ALU_* constants
  input  logic [31:0] operand_a,     // first operand
  input  logic [31:0] operand_b,     // second operand; shifts use only its bits 4:0
  output logic [31:0] result         // result of the operation
);
  import ap_rv32_pkg::*;

  logic [4:0] shift_amount; // number of bit positions to shift by

  assign shift_amount = operand_b[4:0];

  always_comb begin
    result = '0;
    unique case (alu_operation)
      ALU_ADD:  result = operand_a + operand_b;
      ALU_SUB:  result = operand_a - operand_b;
      ALU_SLL:  result = operand_a << shift_amount;
      ALU_SLT:  result = {31'b0, $signed(operand_a) < $signed(operand_b)};
      ALU_SLTU: result = {31'b0, operand_a < operand_b};
      ALU_XOR:  result = operand_a ^ operand_b;
      ALU_SRL:  result = operand_a >> shift_amount;
      ALU_SRA:  result = $signed(operand_a) >>> shift_amount;
      ALU_OR:   result = operand_a | operand_b;
      ALU_AND:  result = operand_a & operand_b;
      default:  result = '0;
    endcase
  end

endmodule
Read included file: ap_rv32_branch.sv
// ap_rv32_branch: the branch compare.
// Decides whether the condition of a branch instruction is true.
// Used by both builds. Taught in S2.4 and S2.10. Blueprint: section 2.3.
module ap_rv32_branch (
  input  logic [2:0]  funct3,    // funct3 of the branch instruction: which condition
  input  logic [31:0] rs1_data,  // first value compared
  input  logic [31:0] rs2_data,  // second value compared
  output logic        condition  // the condition is true: the branch is taken
);
  import ap_rv32_pkg::*;

  always_comb begin
    condition = 1'b0;
    unique case (funct3)
      FUNCT3_BEQ:  condition = (rs1_data == rs2_data);
      FUNCT3_BNE:  condition = (rs1_data != rs2_data);
      FUNCT3_BLT:  condition = ($signed(rs1_data) < $signed(rs2_data));
      FUNCT3_BGE:  condition = ($signed(rs1_data) >= $signed(rs2_data));
      FUNCT3_BLTU: condition = (rs1_data < rs2_data);
      FUNCT3_BGEU: condition = (rs1_data >= rs2_data);
      default:     condition = 1'b0;
    endcase
  end

endmodule
Read included file: ap_rv32_load_unit.sv
// ap_rv32_load_unit: the load unit.
// Picks the addressed byte or half out of the word that the memory returned, and extends it to
// 32 bits with the sign bit (lb, lh) or with zeros (lbu, lhu).
// Used by both builds. Taught in S2.4. Blueprint: section 2.3; misalignment rule in section 7.1.
module ap_rv32_load_unit (
  input  logic [31:0] mem_rdata,     // word from the memory, every byte on its own lane
  input  logic [1:0]  addr_low,      // bits 1:0 of the load address: the lane of the first byte
  input  logic [1:0]  mem_size,      // SIZE_BYTE, SIZE_HALF or SIZE_WORD
  input  logic        load_unsigned, // 1: extend with zeros; 0: extend with the sign bit
  output logic [31:0] load_data,     // value for rd
  output logic        misaligned     // the address is not a multiple of the access size
);
  import ap_rv32_pkg::*;

  logic [7:0]  byte_data; // the addressed byte
  logic [15:0] half_data; // the addressed half
  logic        sign;      // bit that fills the upper part of load_data

  assign byte_data = mem_rdata[{addr_low, 3'b000} +: 8];
  assign half_data = addr_low[1] ? mem_rdata[31:16] : mem_rdata[15:0];

  always_comb begin
    load_data  = mem_rdata;
    sign       = 1'b0;
    misaligned = 1'b0;
    unique case (mem_size)
      SIZE_BYTE: begin
        sign      = byte_data[7] & ~load_unsigned;
        load_data = {{24{sign}}, byte_data};
      end
      SIZE_HALF: begin
        sign       = half_data[15] & ~load_unsigned;
        load_data  = {{16{sign}}, half_data};
        misaligned = addr_low[0];
      end
      default: begin
        misaligned = (addr_low != '0);
      end
    endcase
  end

endmodule

Check Yourself

Predict the outputIn this table, the entry jump of the row JAL is 0. Every other entry is right. The three programs run. What does the last line say?
// One entry of the table is wrong. Which program fails?
// The main decoder is the table in the bench: one row for each opcode. Change a row and run again.
// The ALU operation and the immediate are still given with each program row.
// The files ap_rv32_pkg.sv, ap_rv32_regfile.sv, ap_rv32_alu.sv, ap_rv32_branch.sv, ap_rv32_load_unit.sv are the files of the real core.
module lab_datapath (
  input  logic        clk,            // clock
  input  logic        rst_n,          // reset, active low
  output logic [31:0] imem_addr,      // instruction memory: the PC
  input  logic [31:0] imem_rdata,     // the instruction at the PC, in the same cycle
  input  logic [31:0] imm,            // given: the immediate of this instruction
  input  logic        alu_b_select,   // given: second ALU operand, rs2 or the immediate
  input  logic [3:0]  alu_operation,  // given: what the ALU does
  input  logic [1:0]  result_select,  // given: which value goes to rd
  input  logic        reg_write,      // given: this instruction writes rd
  input  logic        mem_read,       // given: this is a load
  input  logic        mem_write,      // given: this is a store
  input  logic        branch,         // given: this is a conditional branch
  input  logic        jump,           // given: this is a jal
  output logic        dmem_req,       // data memory: a load or store happens this cycle
  output logic        dmem_write,     // 1: store; 0: load
  output logic [31:0] dmem_addr,      // address of the load or store
  output logic [31:0] dmem_wdata,     // the word to store
  input  logic [31:0] dmem_rdata      // the word that the memory returns, in the same cycle
);
  import ap_rv32_pkg::*;

  logic [31:0] pc_q;           // address of the instruction executing this cycle
  logic [31:0] instr;          // the instruction word
  logic [31:0] rs1_data;       // value of register rs1
  logic [31:0] rs2_data;       // value of register rs2
  logic [31:0] alu_operand_b;  // second ALU operand
  logic [31:0] alu_result;     // ALU result; the address of a load or store
  logic [31:0] result;         // value for rd
  logic [31:0] pc_plus_4;      // address of the next instruction in memory
  logic [31:0] pc_next;        // address of the instruction that executes next
  logic [31:0] load_data;      // loaded value
  logic        misaligned;     // load unit: the address does not fit the size (not used in this lab)
  logic        condition;      // the branch condition is true
  logic        redirect;       // a jump, or a branch that is taken
  logic [31:0] target;         // address a jump or taken branch goes to

  // ---- Fetch: the PC addresses the instruction memory.
  assign imem_addr = pc_q;
  assign instr     = imem_rdata;

  // ---- Read two registers. The write port is at the bottom of the picture: it takes the result.
  ap_rv32_regfile u_regfile (
    .clk(clk), .rst_n(rst_n),
    .rs1_addr(instr[19:15]), .rs1_data(rs1_data),
    .rs2_addr(instr[24:20]), .rs2_data(rs2_data),
    .write_enable(reg_write), .rd_addr(instr[11:7]), .rd_data(result)
  );

  // ---- Execute: the ALU.
  assign alu_operand_b = (alu_b_select == ALU_B_IMM) ? imm : rs2_data;

  ap_rv32_alu u_alu (
    .alu_operation(alu_operation), .operand_a(rs1_data), .operand_b(alu_operand_b),
    .result(alu_result)
  );

  ap_rv32_branch u_branch (
    .funct3(instr[14:12]), .rs1_data(rs1_data), .rs2_data(rs2_data), .condition(condition)
  );

  // The target adder: jal and the branches add the immediate to the PC.
  assign target    = pc_q + imm;
  assign redirect  = jump || (branch && condition);

  // ---- Memory access: the ALU result is the address. This lab stores whole words only.
  assign dmem_req   = mem_read || mem_write;
  assign dmem_write = mem_write;
  assign dmem_addr  = alu_result;
  assign dmem_wdata = rs2_data;

  ap_rv32_load_unit u_load_unit (
    .mem_rdata(dmem_rdata), .addr_low(alu_result[1:0]), .mem_size(instr[13:12]),
    .load_unsigned(instr[14]), .load_data(load_data), .misaligned(misaligned)
  );

  // ---- The result select: one of three values goes to rd.
  always_comb begin
    result = alu_result;
    if (result_select == RESULT_MEM) result = load_data;
    if (result_select == RESULT_PC_PLUS_4) result = pc_plus_4;
  end

  // ---- Next PC.
  assign pc_plus_4 = pc_q + 32'd4;
  assign pc_next   = redirect ? target : pc_plus_4;

  always_ff @(posedge clk or negedge rst_n) begin
    if (!rst_n) pc_q <= '0;
    else pc_q <= pc_next;
  end
endmodule

module tb;
  import ap_rv32_pkg::*;
  logic        clk = 0, rst_n = 1;
  logic [31:0] imem_addr, imem_rdata, imm;
  logic        alu_b_select, reg_write;
  logic [3:0]  alu_operation;
  logic [1:0]  result_select;
  logic        mem_read, mem_write, branch, jump, dmem_req, dmem_write;
  logic [31:0] dmem_addr, dmem_wdata, dmem_rdata;

  lab_datapath dp (.*);

  // ---- The main decoder as a table. One row for each opcode that this lab knows.
  function automatic logic [7:0] main_decoder(input logic [6:0] opcode);
    case (opcode)
      //                      reg_write, alu_b_select, result_select,    mem_read, mem_write, branch, jump
      OPCODE_OP:      return {1'b1,      ALU_B_RS2,    RESULT_ALU,       1'b0,     1'b0,      1'b0,   1'b0};
      OPCODE_OP_IMM:  return {1'b1,      ALU_B_IMM,    RESULT_ALU,       1'b0,     1'b0,      1'b0,   1'b0};
      OPCODE_LOAD:    return {1'b1,      ALU_B_IMM,    RESULT_MEM,       1'b1,     1'b0,      1'b0,   1'b0};
      OPCODE_STORE:   return {1'b0,      ALU_B_IMM,    RESULT_ALU,       1'b0,     1'b1,      1'b0,   1'b0};
      OPCODE_BRANCH:  return {1'b0,      ALU_B_IMM,    RESULT_ALU,       1'b0,     1'b0,      1'b1,   1'b0};
      OPCODE_JAL:     return {1'b1,      ALU_B_IMM,    RESULT_PC_PLUS_4, 1'b0,     1'b0,      1'b0,   1'b0};
      default:        return {1'b0,      ALU_B_IMM,    RESULT_ALU,        1'b0,     1'b0,      1'b0,   1'b0};   // any other word: change nothing
    endcase
  endfunction
  function automatic bit known(input logic [31:0] word);   // is this a word that the lab can run?
    case (word[6:0])
      OPCODE_OP, OPCODE_OP_IMM, OPCODE_LOAD, OPCODE_STORE, OPCODE_BRANCH, OPCODE_JAL: return 1;
      default: return 0;
    endcase
  endfunction

  // ---- The memories of the bench.
  logic [31:0] rom [0:63];          // instruction memory, from address 0
  logic [3:0]  operation [0:63];    // the ALU operation of each row
  logic [31:0] immediate [0:63];    // the immediate of each row
  string       text [0:63];         // the assembly of each row
  logic [31:0] ram [0:255];         // data memory, 1 KiB from address 8000_0000
  int rows, cycles;
  task automatic row(input logic [31:0] word, input logic [3:0] alu, input logic [31:0] immediate_value, input string assembly);
    rom[rows] = word;  operation[rows] = alu;  immediate[rows] = immediate_value;  text[rows] = assembly;  rows++;
  endtask
  task automatic clear();
    rows = 0;
    for (int n = 0; n < 64; n++) rom[n] = 32'h0010_0073;   // an ebreak everywhere
    for (int n = 0; n < 256; n++) ram[n] = 0;
  endtask

  // ---- The programs.
  task automatic program_1();   // arithmetic
    clear();
    //  word          ALU      immediate    assembly
    row(32'h0070_0293, ALU_ADD, 32'd7,      "addi x5, x0, 7");   // 00
    row(32'h0050_0313, ALU_ADD, 32'd5,      "addi x6, x0, 5");   // 04
    row(32'h0062_83b3, ALU_ADD, 32'd0,      "add x7, x5, x6");   // 08
    row(32'h4063_8433, ALU_SUB, 32'd0,      "sub x8, x7, x6");   // 0c
    row(32'h0010_0073, ALU_ADD, 32'd0,      "ebreak");   // 10
  endtask
  task automatic program_2();   // memory
    clear();
    //  word          ALU      immediate    assembly
    row(32'h0010_0513, ALU_ADD, 32'd1,      "addi x10, x0, 1");   // 00
    row(32'h01f5_1513, ALU_SLL, 32'd31,     "slli x10, x10, 31");   // 04
    row(32'h0280_0413, ALU_ADD, 32'd40,     "addi x8, x0, 40");   // 08
    row(32'h0005_2283, ALU_ADD, 32'd0,      "lw x5, 0(x10)");   // 0c
    row(32'h0012_8293, ALU_ADD, 32'd1,      "addi x5, x5, 1");   // 10
    row(32'h0055_2423, ALU_ADD, 32'd8,      "sw x5, 8(x10)");   // 14
    row(32'h0054_04b3, ALU_ADD, 32'd0,      "add x9, x8, x5");   // 18
    row(32'h0010_0073, ALU_ADD, 32'd0,      "ebreak");   // 1c
    ram[0] = 32'h0000_0011;   // the word at 80000000
  endtask
  task automatic program_3();   // loop
    clear();
    //  word          ALU      immediate    assembly
    row(32'h0030_0293, ALU_ADD, 32'd3,      "addi x5, x0, 3");   // 00
    row(32'h0000_0313, ALU_ADD, 32'd0,      "addi x6, x0, 0");   // 04
    row(32'h0053_0333, ALU_ADD, 32'd0,      "add x6, x6, x5");   // 08
    row(32'hfff2_8293, ALU_ADD, -32'sd1,    "addi x5, x5, -1");   // 0c
    row(32'hfe02_9ce3, ALU_ADD, -32'sd8,    "bne x5, x0, 0x8");   // 10
    row(32'h0080_00ef, ALU_ADD, 32'd8,      "jal x1, 0x1c");   // 14
    row(32'h0643_0313, ALU_ADD, 32'd100,    "addi x6, x6, 100");   // 18
    row(32'h0010_0073, ALU_ADD, 32'd0,      "ebreak");   // 1c
  endtask

  always #5 clk = ~clk;

  // ---- The wires between the bench and the datapath.
  assign imem_rdata    = rom[imem_addr[7:2]];
  assign imm           = immediate[imem_addr[7:2]];
  assign alu_operation = operation[imem_addr[7:2]];
  assign {reg_write, alu_b_select, result_select, mem_read, mem_write, branch, jump} = main_decoder(imem_rdata[6:0]);
  assign dmem_rdata    = ram[dmem_addr[9:2]];
  always @(posedge clk) if (rst_n && dmem_req && dmem_write) ram[dmem_addr[9:2]] <= dmem_wdata;

  function automatic logic [31:0] register(input int n);   // the value of register n, read from inside the register file
    return (n == 0) ? 32'd0 : dp.u_regfile.registers_q[n];
  endfunction

  // ---- Run one program from reset to its ebreak. show: print one line for each instruction.
  string effect;
  bit    stop;
  task automatic run(input bit show);
    #1 rst_n = 0;   // a real falling edge: the reset is asynchronous
    #1 rst_n = 1;
    cycles = 0;  stop = 0;
    while (!stop) begin
      @(posedge clk);   // the edge that ends a cycle: the wires still show the instruction of that cycle
      if (imem_rdata == 32'h0010_0073 || cycles >= 100) stop = 1;
      else if (!known(imem_rdata)) begin
        $display("%08h | word %08h | not an instruction: the lab stops here", imem_addr, imem_rdata);
        stop = 1;
      end
      else begin
        cycles++;
        effect = "";
        if (reg_write === 1'b1) effect = $sformatf("x%0d = %08h", imem_rdata[11:7], (imem_rdata[11:7] == 0) ? 32'd0 : dp.result);
        if (mem_read) effect = {effect, $sformatf(" from mem[%08h]", dmem_addr)};
        if (mem_write) effect = $sformatf("mem[%08h] = %08h", dmem_addr, dmem_wdata);
        if (branch && dp.redirect) effect = $sformatf("taken: next is %08h", dp.pc_next);
        if (branch && !dp.redirect) effect = "not taken";
        if (jump) effect = {effect, $sformatf(", next is %08h", dp.pc_next)};
        if (show) $display("%08h | %s | %s", imem_addr, text[imem_addr[7:2]], effect);
      end
    end
  endtask
  task automatic check_register(input string name, input int n, input logic [31:0] want);
    $display("%s | x%0d = %08h, should be %08h | %s", name, n, register(n), want, (register(n) === want) ? "pass" : "FAIL");
  endtask
  task automatic check_both(input string name, input int n, input logic [31:0] want, input logic [31:0] address, input logic [31:0] want_word);
    $display("%s | x%0d = %08h, should be %08h | mem[%08h] = %08h, should be %08h | %s", name, n, register(n), want, address, ram[address[9:2]], want_word,
      (register(n) === want && ram[address[9:2]] === want_word) ? "pass" : "FAIL");
  endtask
  task automatic print_row(input string name, input logic [6:0] opcode);
    logic [7:0] c;
    c = main_decoder(opcode);
    $display("%s | reg_write=%b alu_b_select=%b result_select=%b mem_read=%b mem_write=%b branch=%b jump=%b", name, c[7], c[6], c[5:4], c[3], c[2], c[1], c[0]);
  endtask

  initial begin
    print_row("OP    ", OPCODE_OP);
    print_row("OP_IMM", OPCODE_OP_IMM);
    print_row("LOAD  ", OPCODE_LOAD);
    print_row("STORE ", OPCODE_STORE);
    print_row("BRANCH", OPCODE_BRANCH);
    print_row("JAL   ", OPCODE_JAL);
    program_1();  run(0);
    check_register("arithmetic", 8, 32'h0000_0007);
    program_2();  run(0);
    check_both("memory", 9, 32'h0000_003a, 32'h8000_0008, 32'h0000_0012);
    program_3();  run(0);
    check_register("loop", 6, 32'h0000_0006);
    $finish;
  end
endmodule
Read included file: ap_rv32_pkg.sv
// ap_rv32_pkg: the named constants of the ap_rv32 core.
// Opcodes, function fields, control-signal values, trap causes and CSR addresses.
// Used by both builds (ap_rv32_sc and ap_rv32). Taught in S2.2 and S2.5.
// Blueprint: docs/soc/ap_rv32-blueprint.md sections 4 (instructions), 5 (CSRs) and 7 (traps).
package ap_rv32_pkg;

  // ---- Opcodes: instruction bits 6:0
  localparam logic [6:0] OPCODE_LUI      = 7'b0110111;
  localparam logic [6:0] OPCODE_AUIPC    = 7'b0010111;
  localparam logic [6:0] OPCODE_JAL      = 7'b1101111;
  localparam logic [6:0] OPCODE_JALR     = 7'b1100111;
  localparam logic [6:0] OPCODE_BRANCH   = 7'b1100011;
  localparam logic [6:0] OPCODE_LOAD     = 7'b0000011;
  localparam logic [6:0] OPCODE_STORE    = 7'b0100011;
  localparam logic [6:0] OPCODE_OP_IMM   = 7'b0010011;
  localparam logic [6:0] OPCODE_OP       = 7'b0110011;
  localparam logic [6:0] OPCODE_MISC_MEM = 7'b0001111;
  localparam logic [6:0] OPCODE_SYSTEM   = 7'b1110011;

  // ---- funct3 (instruction bits 14:12) of the branches
  localparam logic [2:0] FUNCT3_BEQ  = 3'b000;
  localparam logic [2:0] FUNCT3_BNE  = 3'b001;
  localparam logic [2:0] FUNCT3_BLT  = 3'b100;
  localparam logic [2:0] FUNCT3_BGE  = 3'b101;
  localparam logic [2:0] FUNCT3_BLTU = 3'b110;
  localparam logic [2:0] FUNCT3_BGEU = 3'b111;

  // ---- funct3 of the arithmetic instructions (OP and OP_IMM) that the decoder must tell apart.
  // All eight values are the low three bits of alu_operation, below.
  localparam logic [2:0] FUNCT3_ADD_SUB = 3'b000;
  localparam logic [2:0] FUNCT3_SLL     = 3'b001;
  localparam logic [2:0] FUNCT3_SRL_SRA = 3'b101;

  // ---- funct3 of JALR and FENCE. Loads and stores: bits 1:0 are mem_size, bit 2 is unsigned.
  // SYSTEM: 000 is ecall, ebreak, mret, wfi; else bits 1:0 are csr_operation, bit 2 is immediate.
  localparam logic [2:0] FUNCT3_JALR  = 3'b000;
  localparam logic [2:0] FUNCT3_FENCE = 3'b000;

  // ---- funct7 (instruction bits 31:25)
  localparam logic [6:0] FUNCT7_BASE = 7'b0000000;
  localparam logic [6:0] FUNCT7_ALT  = 7'b0100000; // sub, sra, srai

  // ---- Instructions matched on all 32 bits
  localparam logic [31:0] INSTR_ECALL  = 32'h0000_0073;
  localparam logic [31:0] INSTR_EBREAK = 32'h0010_0073;
  localparam logic [31:0] INSTR_MRET   = 32'h3020_0073;
  localparam logic [31:0] INSTR_WFI    = 32'h1050_0073;

  // ---- imm_select: which immediate format the instruction carries
  localparam logic [2:0] IMM_I = 3'd0;
  localparam logic [2:0] IMM_S = 3'd1;
  localparam logic [2:0] IMM_B = 3'd2;
  localparam logic [2:0] IMM_U = 3'd3;
  localparam logic [2:0] IMM_J = 3'd4;

  // ---- alu_operation: bit 3 is instruction bit 30, bits 2:0 are funct3
  localparam logic [3:0] ALU_ADD  = 4'b0000;
  localparam logic [3:0] ALU_SUB  = 4'b1000;
  localparam logic [3:0] ALU_SLL  = 4'b0001;
  localparam logic [3:0] ALU_SLT  = 4'b0010;
  localparam logic [3:0] ALU_SLTU = 4'b0011;
  localparam logic [3:0] ALU_XOR  = 4'b0100;
  localparam logic [3:0] ALU_SRL  = 4'b0101;
  localparam logic [3:0] ALU_SRA  = 4'b1101;
  localparam logic [3:0] ALU_OR   = 4'b0110;
  localparam logic [3:0] ALU_AND  = 4'b0111;

  // ---- alu_a_select and alu_b_select: the two ALU operands
  localparam logic [1:0] ALU_A_RS1  = 2'd0;
  localparam logic [1:0] ALU_A_PC   = 2'd1;
  localparam logic [1:0] ALU_A_ZERO = 2'd2;
  localparam logic       ALU_B_RS2  = 1'b0;
  localparam logic       ALU_B_IMM  = 1'b1;

  // ---- result_select: the value written to rd
  localparam logic [1:0] RESULT_ALU       = 2'd0;
  localparam logic [1:0] RESULT_MEM       = 2'd1;
  localparam logic [1:0] RESULT_PC_PLUS_4 = 2'd2;
  localparam logic [1:0] RESULT_CSR       = 2'd3;

  // ---- mem_size: bytes moved by a load or store (as AHB hsize)
  localparam logic [1:0] SIZE_BYTE = 2'd0;
  localparam logic [1:0] SIZE_HALF = 2'd1;
  localparam logic [1:0] SIZE_WORD = 2'd2;

  // ---- csr_operation: what a CSR instruction does with its operand
  localparam logic [1:0] CSR_OPERATION_NONE  = 2'd0; // not a CSR instruction
  localparam logic [1:0] CSR_OPERATION_WRITE = 2'd1;
  localparam logic [1:0] CSR_OPERATION_SET   = 2'd2;
  localparam logic [1:0] CSR_OPERATION_CLEAR = 2'd3;

  // ---- Trap causes: the value written to mcause (bit 31 marks an interrupt)
  localparam logic [31:0] CAUSE_INSTR_ADDR_MISALIGNED = 32'd0;
  localparam logic [31:0] CAUSE_INSTR_ACCESS_FAULT    = 32'd1;
  localparam logic [31:0] CAUSE_ILLEGAL_INSTRUCTION   = 32'd2;
  localparam logic [31:0] CAUSE_BREAKPOINT            = 32'd3;
  localparam logic [31:0] CAUSE_LOAD_ADDR_MISALIGNED  = 32'd4;
  localparam logic [31:0] CAUSE_LOAD_ACCESS_FAULT     = 32'd5;
  localparam logic [31:0] CAUSE_STORE_ADDR_MISALIGNED = 32'd6;
  localparam logic [31:0] CAUSE_STORE_ACCESS_FAULT    = 32'd7;
  localparam logic [31:0] CAUSE_ECALL_FROM_M          = 32'd11;
  localparam logic [31:0] CAUSE_IRQ_SOFTWARE          = 32'h8000_0003;
  localparam logic [31:0] CAUSE_IRQ_TIMER             = 32'h8000_0007;
  localparam logic [31:0] CAUSE_IRQ_EXTERNAL          = 32'h8000_000b;

  // ---- Bit positions in mstatus, and in mie and mip
  localparam int MSTATUS_MIE_BIT  = 3;
  localparam int MSTATUS_MPIE_BIT = 7;
  localparam int IRQ_SOFTWARE_BIT = 3;
  localparam int IRQ_TIMER_BIT    = 7;
  localparam int IRQ_EXTERNAL_BIT = 11;

  // ---- CSR addresses (blueprint 5.1)
  localparam logic [11:0] CSR_MSTATUS    = 12'h300;
  localparam logic [11:0] CSR_MISA       = 12'h301;
  localparam logic [11:0] CSR_MIE        = 12'h304;
  localparam logic [11:0] CSR_MTVEC      = 12'h305;
  localparam logic [11:0] CSR_MSTATUSH   = 12'h310;
  localparam logic [11:0] CSR_MSCRATCH   = 12'h340;
  localparam logic [11:0] CSR_MEPC       = 12'h341;
  localparam logic [11:0] CSR_MCAUSE     = 12'h342;
  localparam logic [11:0] CSR_MTVAL      = 12'h343;
  localparam logic [11:0] CSR_MIP        = 12'h344;
  localparam logic [11:0] CSR_MCYCLE     = 12'hb00;
  localparam logic [11:0] CSR_MINSTRET   = 12'hb02;
  localparam logic [11:0] CSR_MCYCLEH    = 12'hb80;
  localparam logic [11:0] CSR_MINSTRETH  = 12'hb82;
  localparam logic [11:0] CSR_MVENDORID  = 12'hf11;
  localparam logic [11:0] CSR_MARCHID    = 12'hf12;
  localparam logic [11:0] CSR_MIMPID     = 12'hf13;
  localparam logic [11:0] CSR_MHARTID    = 12'hf14;
  localparam logic [11:0] CSR_MCONFIGPTR = 12'hf15;
  // Performance monitors 3 to 31 exist and read 0: first and last address of each range
  localparam logic [11:0] CSR_MHPMEVENT3      = 12'h323;
  localparam logic [11:0] CSR_MHPMEVENT31     = 12'h33f;
  localparam logic [11:0] CSR_MHPMCOUNTER3    = 12'hb03;
  localparam logic [11:0] CSR_MHPMCOUNTER31   = 12'hb1f;
  localparam logic [11:0] CSR_MHPMCOUNTER3H   = 12'hb83;
  localparam logic [11:0] CSR_MHPMCOUNTER31H  = 12'hb9f;
  // Address bits 11:10 of a read-only CSR
  localparam logic [1:0]  CSR_READ_ONLY = 2'b11;

  // ---- CSR values and write masks (a 1 marks a bit that software can change)
  localparam logic [31:0] MSTATUS_RESET      = 32'h0000_1800; // MPP = 11: machine mode only
  localparam logic [31:0] MSTATUS_WRITE_MASK = 32'h0000_0088; // MIE and MPIE
  localparam logic [31:0] MISA_VALUE         = 32'h4000_0100; // 32 bits, extension I
  localparam logic [31:0] MIMPID_VALUE       = 32'h0001_0000; // ap_rv32 version 1.0
  localparam logic [31:0] MIE_WRITE_MASK     = 32'h0000_0888; // MSIE, MTIE and MEIE
  localparam logic [31:0] MTVEC_WRITE_MASK   = 32'hffff_fffd; // BASE and MODE bit 0
  localparam logic [31:0] MEPC_WRITE_MASK    = 32'hffff_fffc; // instructions are 4-byte aligned
  localparam logic [31:0] ALL_BITS           = 32'hffff_ffff;

  // ---- Data bits that a byte and a half cover, from bit 0
  localparam logic [31:0] BYTE_BITS = 32'h0000_00ff;
  localparam logic [31:0] HALF_BITS = 32'h0000_ffff;

  // ---- Other
  localparam logic [1:0] PRIV_MACHINE   = 2'b11; // the only privilege level in v1.0
  localparam int         REGISTER_COUNT = 32;

endpackage
Read included file: ap_rv32_regfile.sv
// ap_rv32_regfile: the register file.
// 31 registers, x1 to x31, and x0 which always reads 0. Two read ports, one write port.
// A read is combinational; a write happens at the clock edge. All registers reset to 0.
// Used by both builds. Taught in S2.4. Blueprint: sections 2.3 and 6.
module ap_rv32_regfile (
  input  logic        clk,          // clock
  input  logic        rst_n,        // reset, active low
  input  logic [4:0]  rs1_addr,     // first register to read
  output logic [31:0] rs1_data,     // its value
  input  logic [4:0]  rs2_addr,     // second register to read
  output logic [31:0] rs2_data,     // its value
  input  logic        write_enable, // write rd at this clock edge
  input  logic [4:0]  rd_addr,      // register to write; a write to x0 is discarded
  input  logic [31:0] rd_data       // value to write
);
  import ap_rv32_pkg::*;

  logic [31:0] registers_q [1:REGISTER_COUNT-1]; // x1 to x31; x0 has no storage

  always_ff @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
      for (int i = 1; i < REGISTER_COUNT; i++) registers_q[i] <= '0;
    end else if (write_enable && rd_addr != '0) begin
      registers_q[rd_addr] <= rd_data;
    end
  end

  assign rs1_data = (rs1_addr == '0) ? '0 : registers_q[rs1_addr];
  assign rs2_data = (rs2_addr == '0) ? '0 : registers_q[rs2_addr];

endmodule
Read included file: ap_rv32_alu.sv
// ap_rv32_alu: the arithmetic and logic unit.
// Add, subtract, shifts, compares and bitwise logic on two 32-bit operands.
// Used by both builds. Taught in S2.4. Blueprint: section 2.3.
module ap_rv32_alu (
  input  logic [3:0]  alu_operation, // operation: one of the ALU_* constants
  input  logic [31:0] operand_a,     // first operand
  input  logic [31:0] operand_b,     // second operand; shifts use only its bits 4:0
  output logic [31:0] result         // result of the operation
);
  import ap_rv32_pkg::*;

  logic [4:0] shift_amount; // number of bit positions to shift by

  assign shift_amount = operand_b[4:0];

  always_comb begin
    result = '0;
    unique case (alu_operation)
      ALU_ADD:  result = operand_a + operand_b;
      ALU_SUB:  result = operand_a - operand_b;
      ALU_SLL:  result = operand_a << shift_amount;
      ALU_SLT:  result = {31'b0, $signed(operand_a) < $signed(operand_b)};
      ALU_SLTU: result = {31'b0, operand_a < operand_b};
      ALU_XOR:  result = operand_a ^ operand_b;
      ALU_SRL:  result = operand_a >> shift_amount;
      ALU_SRA:  result = $signed(operand_a) >>> shift_amount;
      ALU_OR:   result = operand_a | operand_b;
      ALU_AND:  result = operand_a & operand_b;
      default:  result = '0;
    endcase
  end

endmodule
Read included file: ap_rv32_branch.sv
// ap_rv32_branch: the branch compare.
// Decides whether the condition of a branch instruction is true.
// Used by both builds. Taught in S2.4 and S2.10. Blueprint: section 2.3.
module ap_rv32_branch (
  input  logic [2:0]  funct3,    // funct3 of the branch instruction: which condition
  input  logic [31:0] rs1_data,  // first value compared
  input  logic [31:0] rs2_data,  // second value compared
  output logic        condition  // the condition is true: the branch is taken
);
  import ap_rv32_pkg::*;

  always_comb begin
    condition = 1'b0;
    unique case (funct3)
      FUNCT3_BEQ:  condition = (rs1_data == rs2_data);
      FUNCT3_BNE:  condition = (rs1_data != rs2_data);
      FUNCT3_BLT:  condition = ($signed(rs1_data) < $signed(rs2_data));
      FUNCT3_BGE:  condition = ($signed(rs1_data) >= $signed(rs2_data));
      FUNCT3_BLTU: condition = (rs1_data < rs2_data);
      FUNCT3_BGEU: condition = (rs1_data >= rs2_data);
      default:     condition = 1'b0;
    endcase
  end

endmodule
Read included file: ap_rv32_load_unit.sv
// ap_rv32_load_unit: the load unit.
// Picks the addressed byte or half out of the word that the memory returned, and extends it to
// 32 bits with the sign bit (lb, lh) or with zeros (lbu, lhu).
// Used by both builds. Taught in S2.4. Blueprint: section 2.3; misalignment rule in section 7.1.
module ap_rv32_load_unit (
  input  logic [31:0] mem_rdata,     // word from the memory, every byte on its own lane
  input  logic [1:0]  addr_low,      // bits 1:0 of the load address: the lane of the first byte
  input  logic [1:0]  mem_size,      // SIZE_BYTE, SIZE_HALF or SIZE_WORD
  input  logic        load_unsigned, // 1: extend with zeros; 0: extend with the sign bit
  output logic [31:0] load_data,     // value for rd
  output logic        misaligned     // the address is not a multiple of the access size
);
  import ap_rv32_pkg::*;

  logic [7:0]  byte_data; // the addressed byte
  logic [15:0] half_data; // the addressed half
  logic        sign;      // bit that fills the upper part of load_data

  assign byte_data = mem_rdata[{addr_low, 3'b000} +: 8];
  assign half_data = addr_low[1] ? mem_rdata[31:16] : mem_rdata[15:0];

  always_comb begin
    load_data  = mem_rdata;
    sign       = 1'b0;
    misaligned = 1'b0;
    unique case (mem_size)
      SIZE_BYTE: begin
        sign      = byte_data[7] & ~load_unsigned;
        load_data = {{24{sign}}, byte_data};
      end
      SIZE_HALF: begin
        sign       = half_data[15] & ~load_unsigned;
        load_data  = {{16{sign}}, half_data};
        misaligned = addr_low[0];
      end
      default: begin
        misaligned = (addr_low != '0);
      end
    endcase
  end

endmodule
ConceptIn the control table, what is one row and what is one column?
ConceptWhich bits of the word does the main decoder look at?
ConceptWhich bits does the ALU decoder look at, besides the opcode?
ConceptWhat does the ALU do for a load?
ConceptFor which of these words does bit 30 choose the ALU operation?

Common Mistakes

Wrong Let funct3 choose the ALU operation for every instruction.

The funct3 of a load or a store names a size. Read as an operation, 010 would mean slt.

Fix Add for every opcode except OP and OP_IMM.

Wrong Let bit 30 choose sub for an addi.

In an addi, bit 30 is bit 10 of the immediate. An addi of 1024 would then subtract.

Fix For OP_IMM, use bit 30 only when the instruction is a shift right.

Wrong Copy a row and change only what is new.

An entry that was right for the old kind stays, and is wrong for the new kind.

Fix Go through every column of a new row and decide each entry.

Remember

  • Control is a table: one row for each opcode, one column for each control signal. The main decoder is that table as logic.
  • The ALU decoder picks the operation from funct3 and bit 30, and only for OP and OP_IMM. Every other row adds.
  • In a word with an immediate, bit 30 counts only for a shift right.
  • One wrong entry breaks one kind of instruction. Only a test that uses that row can find it.

Practice

Report a problem with this page