Don't-Cares and Illegal Instructions

The control table of the last lesson has entries that nothing uses. And it has no row for most of the words a memory can hold. This page deals with both, and with the bug that hides between them.

You Will Be Able To

  • Find the entries of a control table that the datapath never uses, and say why leaving them open saves logic.
  • Explain why an enable must never be left open.
  • Say what a decoder must do with a word that is not an instruction.
Lesson
S2.22
Time
28 min
Runs on
Icarus service
Check
6 questions

The last lab ended with a puzzle: an entry you could change, and no test failed. Some such entries are free gifts. Others are bugs that wait. The difference is one question, and this page asks it of every entry.

Before You Start

You need the control table of S2.5: six rows, seven columns, and the lab that tests it with three programs.

You need to know that a simulator shows an unknown value as x.

Five questions this page answers
Question
1What is a don't-care entry of the control table?
2Why do designers leave such entries open?
3Which control signals must never be left open?
4What does a simulator do with an x on a write enable?
5What must a core do with a word that is not an instruction?

The Idea: Ask What Reads the Signal

Take one entry of the control table: the result_select of a store. A store writes no register. So during a store, nothing takes the output of the result select. Whatever that entry says, the core does the same.

Such an entry is a don't-care. It may be 0 or 1, and no program can tell. Designers mark it with an x and let the tools choose. A table with free entries needs less logic than a table where every entry is fixed.

Now take another entry: the reg_write of a store. A store has no rd, so this looks free as well. It is not. If reg_write is 1, a register takes a value at the clock edge. Which register? The one that bits 11 to 7 of the word happen to name.

So the question for each entry is: does anything act on this signal for this row? For a select, sometimes nothing does. For an enable, something always does.

The same question has a larger form. A memory can hold any pattern of 32 bits. A word that is not an instruction of the core is an illegal instruction. The decoder must give such a word a row too: one that changes nothing, and reports the word.

New Words

New words on this page
WordMeaning
Don't-careAn entry of a table whose value has no effect. It is written x.
xIn a table: either value will do. In a simulator: a value that is not known.
Synthesis toolThe program that turns a description of logic into gates.
Illegal instructionA word that is not an instruction of this core.
Processor trapThe core stops the normal order of the program and jumps to a handler. Called a trap for short. S2.13 covers it.
Trap causeA number that the core records with a trap. It says why the trap was taken.
Trap valueA value that the core keeps about a trap, in a register named mtval. For an illegal instruction: the word itself.

One Picture: Which Entries Are Free

Three Kinds of Entry, and One More RowStep through the picture. It sorts the entries of the control table by what a mistake in them would cost.
  • Memory
  • Control / FSM
  • Processor
  • Debug
Three Kinds of Entry, and One More RowStep through the picture. It sorts the entries of the control table by what a mistake in them would cost. component Any 32-bit word an instruction, ordata, or an erasedmemory component Decoder the control table, anda check of the fields component Enables reg_write, mem_read,mem_write, branch,jump: never left open component Selects may be left openwhere nothing usesthe output component State the registers, thememory and the PC component illegal the word fits no row:take a trap, changenothing instralways 0 or 10, 1 or do not carea 1 here changesstateno row fitsforces every enableoff
  1. component Decoderthe control table, and a check of the fields
    • always 0 or 1 → Enables
    • 0, 1 or do not care → Selects
    • no row fits → illegal
  2. component Selectsmay be left open where nothing uses the output
  3. component Enablesreg_write, mem_read, mem_write, branch, jump: never left open
    • a 1 here changes state → State
  4. component Statethe registers, the memory and the PC
  5. component Any 32-bit wordan instruction, or data, or an erased memory
    • instr → Decoder
  6. component illegalthe word fits no row: take a trap, change nothing
    • forces every enable off → Enables
  1. A select that nothing uses

    A store writes no register. So nothing reads the output of the result select during a store. Its select may be 0, 1 or 2: the result is the same.

  2. An enable is never free

    An enable decides whether state changes. A wrong 1 destroys a register, a memory word or the path of the program. Every enable has a fixed value in every row.

  3. A word that fits no row

    The memory can hold any 32 bits. Most patterns are not instructions. The decoder must notice, raise illegal, and keep every enable at 0.

Read the diagram as text
  • Any 32-bit word: an instruction, or data, or an erased memory
  • Decoder: the control table, and a check of the fields
  • Enables: reg_write, mem_read, mem_write, branch, jump: never left open
  • Selects: may be left open where nothing uses the output
  • State: the registers, the memory and the PC
  • illegal: the word fits no row: take a trap, change nothing
  • Any 32-bit word → Decoder: instr
  • Decoder → Enables: always 0 or 1
  • Decoder → Selects: 0, 1 or do not care
  • Enables → State: a 1 here changes state
  • Decoder → illegal: no row fits
  • illegal → Enables: forces every enable off

The rule of thumb: a select may be left open, an enable may not.

The control table with its don't-cares
Rowreg_writealu_b_selectresult_selectmem_readmem_writebranchjump
OP1000000
OP_IMM1100000
LOAD1111000
STORE01x0100
BRANCH0xx0010
JAL1x20001

Four entries are free, and all four are selects. The five columns of enables have no x.

The Smallest Example, Worked by Hand

Go through the row BRANCH, entry by entry, and ask the question each time.

The row BRANCH
EntryDoes anything act on it?So it is
reg_writeYes: the register file writes when it is 10
alu_b_selectNo: a branch does not use the ALU resultx
result_selectNo: reg_write is 0, so the result goes nowherex
mem_read, mem_writeYes: the memory acts on them0 and 0
branchYes: the next-PC select needs it1
jumpYes: a 1 would take the target always0

A free entry is free only as long as the entries beside it stay as they are.

The last line of the caption matters. The result_select of a branch is free because reg_write is 0. Set reg_write to 1, and that select is no longer free.

The Rules

  1. Rule 1: An entry is a don't-care when nothing acts on the signal in that row.

    Check what reads the signal, and what the other entries of the row switch off.

  2. Rule 2: Only a select can be a don't-care.

    A select is free when the output of its multiplexer goes nowhere.

  3. Rule 3: An enable is never a don't-care.

    A register, a memory or the PC always acts on it. Give it 0 or 1 in every row.

  4. Rule 4: A simulator is no proof that an x is harmless.

    An x on a write enable counts as "no write" in simulation. A tool may build a 1.

  5. Rule 5: A word that fits no row is illegal.

    For such a word every enable is 0, and the core takes a trap.

  6. Rule 6: The opcode alone does not make a word legal.

    The other fixed fields, funct3 and funct7, must name an instruction too.

Sources for These Rules

Two things on this page are common practice and not checked against a source. The first is what a synthesis tool does with an entry marked x. It may build a 0 or a 1, whichever gives less logic. No tool was run on such a table here. The second is the encoding of the words. The word 026283b3 is mul x7, x5, x6 as the M extension is commonly encoded. The trap cause 2 is "illegal instruction" as commonly numbered. The RISC-V specifications are not in the reference library. The plan of this track points to Patterson and Hennessy, section 4.4 and appendix C, which are not checked. What the real core does with each word was measured: it is on this page.

Now Run It

The lab at the end of this page is the lab of the last lesson. Its four free entries now hold an x. It prints its table and runs the same three programs.

Printed by the lab on Icarus. Every entry that is not x equals 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=xx mem_read=0 mem_write=1 branch=0 jump=0
BRANCH | reg_write=0 alu_b_select=x result_select=xx mem_read=0 mem_write=0 branch=1 jump=0
JAL    | reg_write=1 alu_b_select=x 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 1 at work: all three programs pass, with four entries unknown. No program can see those entries.

The real core fills them in. Its decoder gives 1 to alu_b_select in the rows BRANCH and JAL, and 00 to result_select in the rows STORE and BRANCH. Those are its starting values, and no row changes them.

Now the second half of the page: words that fit no row. Each row below is the first word of a program on the real core.

Recorded from the real ap_rv32_sc on Icarus. The instruction-level model gave the same rows.
00000000 | word 00000000 | trap, cause 2: illegal instruction, mtval 00000000
00000000 | word ffffffff | trap, cause 2: illegal instruction, mtval ffffffff
00000000 | word 026283b3 | trap, cause 2: illegal instruction, mtval 026283b3
00000000 | word 40629033 | trap, cause 2: illegal instruction, mtval 40629033
00000000 | word 00053283 | trap, cause 2: illegal instruction, mtval 00053283
Why each of the five words is illegal
WordReason
00000000all zeros: no instruction has the opcode 0000000
ffffffffall ones: no instruction of this core has the opcode 1111111
026283b3the opcode of add, with a funct7 that ap_rv32 does not have
40629033the opcode and funct3 of sll, with the funct7 of sub
00053283the opcode of a load, with a funct3 that names no size of RV32I

Rule 5 at work: every row ends in a trap, with cause 2. The register mtval keeps the word, so that a handler can look at it. No register was written.

Rule 6 at work: rows 3, 4 and 5. Their opcodes are real ones: OP twice, and LOAD. Another field has a value that names nothing.

The first two words are worth a second look. A memory that was never written often reads as all zeros, and an erased flash memory as all ones. Both patterns are illegal on purpose. A PC that runs off into empty memory is caught at once.

A Decoder That Reads Only the Opcode

What if a decoder obeys rule 5 and forgets rule 6? The lab can show it. Its table reads only the opcode. The third word of this program is 026283b3. It has the opcode of an add, and a funct7 that ap_rv32 does not have.

The lab with a decoder that reads only the opcode. A changed lab: the real core traps on this word, as shown above.
00000000 | addi x5, x0, 6 | x5 = 00000006
00000004 | addi x6, x0, 7 | x6 = 00000007
00000008 | word 026283b3 | x7 = 0000000d
multiply | x7 = 0000000d, should be: no write, the real core takes a trap

The word is a multiply of the M extension: 6 times 7. This lab runs it as an add, because its funct3 is 000. Register x7 takes 13, and nothing is reported.

A program built for a larger core would run on this one, and compute wrong numbers in silence. Now the lab checks funct7 as well:

The same lab with the check of funct7 switched on.
00000000 | addi x5, x0, 6 | x5 = 00000006
00000004 | addi x6, x0, 7 | x6 = 00000007
00000008 | word 026283b3 | not an instruction: the lab stops here
multiply | x7 = 00000000, should be: no write, the real core takes a trap

The word is refused, and x7 keeps its 0. The lab can only stop. The real core takes a trap, and a handler could even do the multiply in software.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
Free entries are marked xEvery entry gets a 0 or a 1The tool may merge rows and save gates. The table is harder to check by simulation.
Enables start at 0 in every rowEnables are listed row by rowA forgotten row changes nothing. A row that needs a 1 must say so.
Every illegal word takes a trapAn illegal word does nothing and the PC moves onA wrong program stops at its first bad word. Every field of every word must be checked.
All zeros and all ones are illegalOne of them is a no-operationEmpty memory stops the core at once. No short pattern for "do nothing".
The trap keeps the word in mtvalThe trap keeps only the PCThe handler can decode the word and stand in for the instruction. One more register to write.

The Trap: The x on a Write Enable

A designer fills in the row STORE. A store has no rd, so the designer reasons: the write enable of a register that does not exist is free. The entry reg_write becomes x. Here is the lab with that table.

The lab with x on the reg_write of the row STORE.
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=x alu_b_select=1 result_select=xx mem_read=0 mem_write=1 branch=0 jump=0
BRANCH | reg_write=0 alu_b_select=x result_select=xx mem_read=0 mem_write=0 branch=1 jump=0
JAL    | reg_write=1 alu_b_select=x 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

All three programs pass. The memory program holds a store, and it passes too. The designer takes this as proof.

It is no proof. The register file of ap_rv32 writes only if its write enable is 1. In a simulator, x is not 1, so nothing is written. The simulator has quietly chosen 0.

A synthesis tool makes no such choice for you. It may build a 0 or a 1 there, whichever needs fewer gates. Here is the lab after the tool has chosen 1:

The row STORE and the three programs with reg_write at 1. The real core gives the same values when its decoder has the same change.
STORE  | reg_write=1 alu_b_select=1 result_select=xx mem_read=0 mem_write=1 branch=0 jump=0
arithmetic | x8 = 00000007, should be 00000007 | pass
memory | x9 = 8000001a, should be 0000003a | mem[80000008] = 00000012, should be 00000012 | FAIL
loop | x6 = 00000006, should be 00000006 | pass

The memory program fails. Its store is sw x5, 8(x10). Bits 11 to 7 of that word hold the low part of the immediate: 8. So the "register that does not exist" is x8.

And x8 takes the ALU result, which is the address 8000_0008. The program had 40 in x8. The memory word is still right, which makes the fault harder to see.

There is a second face of this trap. Give a branch a reg_write of 1, and run the three programs again:

The three programs, and the loop program once more with a look at x25. The real core with the same change gives the same values.
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
loop, looking at x25 | x25 = fffffff8, should be 00000000 | FAIL

All three programs pass again. Yet the branch of the loop writes x25, because the five bits of its offset at that place spell 25. No test fails until some program uses x25.

At Scale

This page42 entries, 4 of them free
A large decoderthousands of entries, most of them free

This section looks ahead. On a real chip, don't-cares and illegal words are both larger matters.

  1. An x that spreads

    In simulation, one x on a select can turn a whole bus into x. Teams run special checks for that, and many forbid x in control tables.

  2. The handler

    A trap needs a place to go, and registers that say what happened. S2.13 builds that part of the core.

  3. Software that fills the gap

    A handler can read mtval, see a multiply, and do it in software. A core without M can then run programs built for M, slowly.

  4. Words as a weapon

    Software from outside may feed a core every possible word. A word that slips through the decoder can break the rules that protect a system: S9.5.

Try It

Run the lab. All three programs pass with four entries at x.

Put an x on the result_select of the row LOAD. Which program fails, and what does its line show?

Put an x on the mem_write of the row OP. The programs still pass. Explain why that proves nothing.

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=xx mem_read=0 mem_write=1 branch=0 jump=0 BRANCH | reg_write=0 alu_b_select=x result_select=xx mem_read=0 mem_write=0 branch=1 jump=0 JAL | reg_write=1 alu_b_select=x 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 reg_write of the row BRANCH is 1. The loop program runs. Its bne at address 10 in hex goes back to 8, and the lab then looks at x25. What does the last line say?
// One enable of the table is wrong. What does the last line say?
// 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'b1,      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'b1};
      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();   // loop, looking at x25
    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("loop, looking at x25", 25, 32'h0000_0000);
    $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
ConceptWhat is a don't-care entry of the control table?
ConceptWhy do designers leave such entries open?
ConceptWhich of these must never be left open?
ConceptThe reg_write of a store is x. What does a simulation of the register file of ap_rv32 do at a store?
ConceptThe word 026283b3 has the opcode of an add and a funct7 that ap_rv32 lacks. What does the real core do?

Common Mistakes

Wrong Mark the write enable of a store as x.

The bits where rd would be still name a register. If the tool builds a 1, that register is destroyed.

Fix Give every enable a 0 or a 1 in every row.

Wrong Trust a passing simulation of a table with x in it.

A simulator treats an x on an enable as "do not write". Real gates will be 0 or 1.

Fix Decide each x by asking what reads the signal.

Wrong Decide that a word is legal from its opcode.

An opcode covers many instructions. A funct3 or funct7 that names none of them is still illegal.

Fix Check every fixed field of the word.

Remember

  • An entry is a don't-care only when nothing acts on the signal in that row. Only a select can be one.
  • An enable is never free: a 1 changes a register, a memory word or the PC.
  • A simulator treats an x on a write enable as "no write". A passing test proves nothing about that x.
  • A word that fits no row is illegal: every enable is 0 and the core takes a trap. All fixed fields count, not only the opcode.

Practice

Report a problem with this page