The Full Datapath: Loads, Stores, Branches and Jumps

The datapath of the last lesson can add. It cannot reach memory, and its PC can only count. This page adds four kinds of instruction, one at a time, and each brings one new box.

You Will Be Able To

  • Follow a load and a store from the ALU to the data memory and back.
  • Say how a branch and a jump change the PC, and what a jump writes to its register.
  • Point to the place where a new kind of instruction would join the datapath.
Lesson
S2.21
Time
32 min
Runs on
Icarus service
Check
6 questions

A loop that sums three numbers needs four things the last datapath lacks. It must load its count, go back to its start, store its sum and jump to the end. Each of the four is a few wires and one small block.

Before You Start

You need the datapath of S2.4: the PC, the register file, the operand select and the ALU.

You need the offsets of branches and jumps from S2.18. A target is the PC plus the immediate.

Five questions this page answers
Question
1What does the ALU compute for a load or a store?
2Which path does the stored value take to the memory?
3Which block decides whether a branch is taken?
4Which two values does a jal write, and where?
5Which three values can the result select send to rd?

The Idea: One New Box for Each Kind of Instruction

An arithmetic instruction starts at the registers and ends at the registers. The other kinds of instruction start or end somewhere else.

A load ends at a register, but its value comes from memory. So the datapath gets a second memory behind the ALU: the data memory of the core. The ALU works out the address.

A store ends in the memory. It needs one new wire: from the second read port to the data input of the memory.

A branch ends at the PC. It needs a block that tests two registers, and an adder that works out where to go. That place is called the target.

A jump ends at the PC and at a register. It goes to its target, and it writes the address after itself into rd. That saved address is the link value.

Now a register can get its value from three places. One multiplexer, the result select, chooses among them. That is the whole page.

New Words

New words on this page
WordMeaning
Data memory of the coreThe memory that loads read and stores write. In the lab it starts at address 8000_0000.
Byte laneOne of the four bytes of a 32-bit data word. Lane 0 is bits 7 to 0, lane 3 is bits 31 to 24.
Load unitThe block after the data memory. It picks the byte, half or word that a load asked for.
Result selectThe multiplexer that chooses the value for rd: the ALU result, the loaded value or the PC plus 4.
Branch compare blockThe block that tests two register values for a branch. Its output is named condition. Called the branch compare for short.
Target of a jumpThe address that a taken branch or a jump goes to. Called the target for short.
Target adderThe adder that adds the immediate to the PC. Its sum is the target.
Next-PC selectThe multiplexer that chooses the next PC: the PC plus 4, or the target.
Link valueThe address after a jump, which the jump writes to rd. It is the return address of S2.3.
mem_readA control signal: 1 when the instruction is a load.
mem_writeA control signal: 1 when the instruction is a store.
result_selectA control signal of 2 bits: it steers the result select.
RedirectThe PC takes the target, not the PC plus 4. The wire redirect is 1 when that happens.

One Picture: Four Kinds of Instruction

The Full Datapath, One Kind of Instruction at a TimeStep through the picture. Each step lights the boxes that one kind of instruction uses.
  • Processor
  • Memory
  • Control / FSM
The Full Datapath, One Kind of Instruction at a TimeStep through the picture. Each step lights the boxes that one kind of instruction uses. component PC and fetch the PC, its adder forthe PC plus 4, andthe instructionmemory component Register file rs1_data andrs2_data out, resultin component ALU for a load or store:the address component Data memory andload unit one word in, orload_data out, in thesame cycle component Next-PC select pc_next: the PC plus4, or the target component Target adder target: the PC plusthe immediate component Branch compare condition: is the testof the branch true? component Result select result: one of threevalues for rd instrrs1_data, andrs2_data or immdmem_addrdmem_wdata:rs2_dataload_dataalu_resultpc_plus_4resultrs1_data, rs2_dataconditionpc_q, and immtargetpc_plus_4pc_next
  1. component PC and fetchthe PC, its adder for the PC plus 4, and the instruction memory
    • instr → Register file
    • pc_plus_4 → Result select
    • pc_q, and imm → Target adder
    • pc_plus_4 → Next-PC select
  2. component Register filers1_data and rs2_data out, result in
    • rs1_data, and rs2_data or imm → ALU
    • dmem_wdata: rs2_data → Data memory and load unit
    • rs1_data, rs2_data → Branch compare
  3. component ALUfor a load or store: the address
    • dmem_addr → Data memory and load unit
    • alu_result → Result select
  4. component Data memory and load unitone word in, or load_data out, in the same cycle
    • load_data → Result select
  5. component Result selectresult: one of three values for rd
    • result → Register file
  6. component Branch comparecondition: is the test of the branch true?
    • condition → Next-PC select
  7. component Target addertarget: the PC plus the immediate
    • target → Next-PC select
  8. component Next-PC selectpc_next: the PC plus 4, or the target
    • pc_next → PC and fetch
  1. A load: lw x5, 0(x10)

    The ALU adds rs1_data and the immediate. The sum is an address. The data memory returns the word there. It goes through the load unit and the result select into x5.

  2. A store: sw x6, 4(x10)

    The address comes from the ALU in the same way. The value of rs2 goes round the ALU, straight to the memory. No register is written.

  3. A branch: bne x5, x0, 0x10

    The branch compare tests the two register values. The target adder adds the immediate to the PC. If the test is true, the PC takes the target.

  4. A jump: jal x1, 0x28

    The PC always takes the target. And the address of the next word, the PC plus 4, goes through the result select into x1.

  5. An arithmetic instruction

    The path of the last lesson is still here. The ALU result goes through the result select into rd, and the PC takes the PC plus 4.

Read the diagram as text
  • PC and fetch: the PC, its adder for the PC plus 4, and the instruction memory
  • Register file: rs1_data and rs2_data out, result in
  • ALU: for a load or store: the address
  • Data memory and load unit: one word in, or load_data out, in the same cycle
  • Next-PC select: pc_next: the PC plus 4, or the target
  • Target adder: target: the PC plus the immediate
  • Branch compare: condition: is the test of the branch true?
  • Result select: result: one of three values for rd
  • PC and fetch → Register file: instr
  • Register file → ALU: rs1_data, and rs2_data or imm
  • ALU → Data memory and load unit: dmem_addr
  • Register file → Data memory and load unit: dmem_wdata: rs2_data
  • Data memory and load unit → Result select: load_data
  • ALU → Result select: alu_result
  • PC and fetch → Result select: pc_plus_4
  • Result select → Register file: result
  • Register file → Branch compare: rs1_data, rs2_data
  • Branch compare → Next-PC select: condition
  • PC and fetch → Target adder: pc_q, and imm
  • Target adder → Next-PC select: target
  • PC and fetch → Next-PC select: pc_plus_4
  • Next-PC select → PC and fetch: pc_next

Three multiplexers choose: the operand select in front of the ALU, the result select and the next-PC select. A control signal steers each.

The control signals that this page adds
SignalWidthWhat it decides
result_select2 bits0: rd takes the ALU result. 1: the loaded value. 2: the PC plus 4.
mem_read1 bit1: the instruction reads the data memory.
mem_write1 bit1: the instruction writes the data memory.
branch1 bit1: the PC takes the target if the condition is true.
jump1 bit1: the PC takes the target always.

With the three signals of the last lesson, that makes eight. They are still given on this page.

The Smallest Example, Worked by Hand

Take the load lw x5, 0(x10). Register x10 holds 8000_0000, and the memory word at that address holds 3.

One load, wire by wire
WireValueWhy
rs1_data8000_0000the value of x10
alu_operand_b0the immediate: alu_b_select is 1
alu_result8000_0000the sum: this is the address
dmem_addr8000_0000the ALU result goes to the memory
dmem_rdata3the word at that address
load_data3an lw takes the whole word
result3result_select is 1: take load_data

At the clock edge, x5 takes the 3.

Now a branch. The instruction bne x5, x0, 0x10 sits at address 18 in hex, and x5 holds 2. Its immediate is -8.

One branch, wire by wire
WireValueWhy
rs1_data, rs2_data2 and 0the values of x5 and x0
condition1bne asks: are they different? Yes
target1018 minus 8, in hex
redirect1a branch, and its condition is true
pc_next10the next-PC select takes the target

With 0 in x5, the condition is 0 and pc_next is 1c, the PC plus 4.

The Rules

  1. Rule 1: For a load or a store, the ALU result is the address.

    It is rs1_data plus the immediate. The ALU does an add.

  2. Rule 2: A loaded value goes through the load unit, then through the result select, into rd.

    For a load, result_select is 1.

  3. Rule 3: A store sends rs2_data to the memory, and writes no register.

    For a store, mem_write is 1 and reg_write is 0.

  4. Rule 4: The memory acts only when mem_read or mem_write is 1.

    On every other instruction the ALU result still reaches the memory, and nothing happens.

  5. Rule 5: A branch goes to its target only when its condition is true.

    The branch compare gives the condition. The target adder gives the target.

  6. Rule 6: A jal always goes to its target, and writes the PC plus 4 to rd.

    For a jal, result_select is 2.

Here are rules 5 and 6 in the real core: four lines of ap_rv32_sc.

From ap_rv32_sc.sv. The real core also has jalr, which adds the immediate to rs1_data. The lab leaves jalr out.
// jalr adds the immediate to rs1 and clears bit 0; jal and the branches add it to the PC.
always_comb begin
  target    = (jump_register ? rs1_data : pc_q) + imm;
  target[0] = 1'b0;
end

assign redirect  = jump || (branch && condition);
assign pc_plus_4 = pc_q + 32'd4;

The condition comes from the branch compare. Its six lines are the six branch instructions.

From ap_rv32_branch.sv. The field funct3 of the word says which test to make.
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

And here is the real load unit. Read the two assign lines first: they pick a byte or a half out of the word.

From ap_rv32_load_unit.sv. The two low bits of the address name the byte lane. The name addr_low stands for those two bits.
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
Sources for These Rules

The parts of the datapath are described here as textbooks commonly describe them. The plan of this track points to Patterson and Hennessy, sections 4.1 to 4.3, and to Harris and Harris, section 7.3. Those places are not checked. The word 026283b3 is mul x7, x5, x6 as the M extension is commonly encoded. That encoding is not checked either: the RISC-V specifications are not in the reference library. Every signal name, every line of code and every printed row comes from the RTL of ap_rv32_sc in this repository.

Now Run It

The lab at the end of this page runs a program of ten instructions. It loads a count of 3, adds 3, 2 and 1 in a loop, stores the sum, and jumps over one instruction.

Printed by the lab on Icarus. The real core ap_rv32_sc and the instruction-level model of this track gave the same rows.
00000000 | addi x10, x0, 1 | a=0 b=1 alu=1 | x10 = 00000001
00000004 | slli x10, x10, 31 | a=1 b=1f alu=80000000 | x10 = 80000000
00000008 | lw x5, 0(x10) | a=80000000 b=0 alu=80000000 | x5 = 00000003 from mem[80000000]
0000000c | addi x6, x0, 0 | a=0 b=0 alu=0 | x6 = 00000000
00000010 | add x6, x6, x5 | a=0 b=3 alu=3 | x6 = 00000003
00000014 | addi x5, x5, -1 | a=3 b=ffffffff alu=2 | x5 = 00000002
00000018 | bne x5, x0, 0x10 | a=2 b=fffffff8 alu=fffffffa | taken: next is 00000010
00000010 | add x6, x6, x5 | a=3 b=2 alu=5 | x6 = 00000005
00000014 | addi x5, x5, -1 | a=2 b=ffffffff alu=1 | x5 = 00000001
00000018 | bne x5, x0, 0x10 | a=1 b=fffffff8 alu=fffffff9 | taken: next is 00000010
00000010 | add x6, x6, x5 | a=5 b=1 alu=6 | x6 = 00000006
00000014 | addi x5, x5, -1 | a=1 b=ffffffff alu=0 | x5 = 00000000
00000018 | bne x5, x0, 0x10 | a=0 b=fffffff8 alu=fffffff8 | not taken
0000001c | sw x6, 4(x10) | a=80000000 b=4 alu=80000004 | mem[80000004] = 00000006
00000020 | jal x1, 0x28 | a=0 b=8 alu=8 | x1 = 00000024, next is 00000028
00000028 | ebreak | stop
x6=6 x1=00000024 the word at 80000004 holds 6 cycles=15

Rule 1 at work: rows 3 and 14. In both, alu is an address: 8000_0000, and 8000_0004.

Rule 2 at work: row 3. The word at 8000_0000 holds 3, and x5 takes it.

Rule 5 at work: rows 7, 10 and 13 are the same bne. It is taken twice. The third time x5 is 0, and the PC goes on to 1c.

Look at the wires of those bne rows. The ALU still adds something, and nothing uses its result. A block that is not needed is not switched off. Its output is ignored.

Rule 3 at work: row 14 writes 6 to the memory, and shows no register.

Rule 6 at work: row 15. The jal at 20 writes 24 into x1, and the next row is at 28. The addi at 24 never runs.

The real core needed 17 cycles for this program. Fifteen are for the instructions, one for the ebreak, and one after reset.

The M Extension as a Box

The core ap_rv32 has no multiply. S2.17 showed that the M extension adds one. Where would it go?

Where a Multiplier Would SitThe box with the broken promise: ap_rv32 has no multiplier. The picture shows where one would join.
  • Memory
  • Processor
  • External
  • Control / FSM
Where a Multiplier Would SitThe box with the broken promise: ap_rv32 has no multiplier. The picture shows where one would join. component Register file gives rs1_data andrs2_data component ALU ten operations, nomultiply component Multiplier the M extension. Notbuilt in ap_rv32 component Result select would get one moreinput two operandsthe same twooperandsalu_resultthe product
  1. component Register filegives rs1_data and rs2_data
    • two operands → ALU
    • the same two operands → Multiplier
  2. component ALUten operations, no multiply
    • alu_result → Result select
  3. component Result selectwould get one more input
  4. component Multiplierthe M extension. Not built in ap_rv32
    • the product → Result select
  1. Today

    The ALU takes two operands, and its result goes to the result select.

  2. With the M extension

    A multiplier takes the same two operands. Its product is one more input of the result select. Nothing else changes.

Read the diagram as text
  • Register file: gives rs1_data and rs2_data
  • ALU: ten operations, no multiply
  • Multiplier: the M extension. Not built in ap_rv32
  • Result select: would get one more input
  • Register file → ALU: two operands
  • Register file → Multiplier: the same two operands
  • ALU → Result select: alu_result
  • Multiplier → Result select: the product

A new kind of instruction joins the datapath at a multiplexer.

A multiplier needs the two values that the ALU already gets. Its product needs a way into rd, and the result select is that way. So M is one box beside the ALU, and one more input on a multiplexer.

The datapath alone is not enough. The decoder must also know the new words. Here is the real core when it meets one:

Recorded from the real ap_rv32_sc on Icarus. The instruction-level model gave the same rows. The lab datapath has no traps and cannot run this.
00000000 | addi x5, x0, 6 | x5 = 00000006
00000004 | addi x6, x0, 7 | x6 = 00000007
00000008 | word 026283b3 | trap, cause 2: illegal instruction, mtval 026283b3

The word at address 8 is a multiply of x5 and x6. The core does not write 42 anywhere. It takes a trap, and reports an illegal instruction. S2.22 shows how the decoder finds such words.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
The ALU works out the addressAn adder of its own for addressesNo extra adder. A load must wait for the ALU and then for the memory.
A target adder beside the ALUThe ALU works out the targetA branch can compare and add at the same time. One more 32-bit adder.
A branch compare of its ownThe ALU subtracts, and a flag is testedThe compare does not wait for the ALU. A second comparer in the core.
The load unit after the memoryThe memory returns single bytesThe memory stays simple: it always returns a word. Every load passes one more block.
One result selectEach source drives rd directlyExactly one value reaches the write port. One more multiplexer on the way to rd.
Unused blocks keep runningSwitch off what an instruction does not needNo logic to switch anything. Wires toggle for nothing, which costs power.

The Trap: The Load That Returned the Whole Word

A designer builds the load path and tests it with lw. Every test passes. The data memory returns a word, and the word goes to rd. The load unit looks like a block that does nothing.

Then a program reads one character from a string with lb. Here is a correct datapath first. The word at 8000_0000 holds 0000_12f0.

The lab datapath with the real load unit. The real core and the model gave the same rows.
00000000 | addi x10, x0, 1 | x10 = 00000001
00000004 | slli x10, x10, 31 | x10 = 80000000
00000008 | lw x5, 0(x10) | x5 = 000012f0 from mem[80000000]
0000000c | lb x6, 0(x10) | x6 = fffffff0 from mem[80000000]
00000010 | lbu x7, 0(x10) | x7 = 000000f0 from mem[80000000]
00000014 | lb x8, 1(x10) | x8 = 00000012 from mem[80000001]
00000018 | ebreak | stop
x5=000012f0 x6=fffffff0 x7=000000f0 x8=00000012

The lb at address c takes only the byte on lane 0, which is f0. Its top bit is 1, so the byte is sign-extended to fffffff0. The lbu fills with zeros. The lb at 14 takes lane 1, the 12.

Now the same program on a datapath without the load unit. The word from the memory goes on as it is.

The same lab with the load unit left out, from the first load on. This is a changed lab, not the real core.
00000008 | lw x5, 0(x10) | x5 = 000012f0 from mem[80000000]
0000000c | lb x6, 0(x10) | x6 = 000012f0 from mem[80000000]
00000010 | lbu x7, 0(x10) | x7 = 000012f0 from mem[80000000]
00000014 | lb x8, 1(x10) | x8 = 000012f0 from mem[80000001]
00000018 | ebreak | stop
x5=000012f0 x6=000012f0 x7=000012f0 x8=000012f0

Row 1, the lw, is still right. The other three loads all give the whole word. The test with lw could never find this.

The memory of a core always moves whole words. The size of a load is the business of the load unit. A store has the same duty in the other direction, and the practice problem builds it.

At Scale

This page6 kinds of instruction, 8 control signals
ap_rv32_sc48 instructions, 24 control signals

This section looks ahead. The lab has six kinds of instruction. The real core has more, and each adds little.

  1. Three more instructions, two more multiplexers

    The instructions jalr, lui and auipc need a second source for the target and for the first ALU operand. The real core has both.

  2. Stores of bytes and halves

    An sb must change one byte and leave three alone. The store unit places it on its lane: the practice problem of this page.

  3. Traps

    A load from an address with no memory behind it must not write rd. The real core checks every such case: S2.13.

  4. A memory that takes time

    A real memory answers a cycle later, or many. Then one cycle is not enough, and the core must wait: S2.16.

Try It

Run the lab. Find the three rows of the bne, and say why the third differs.

Change the word at 8000_0000 from 3 to 5. How many rows does the run have now, and what is stored?

Give the row of the sw the class LOAD by mistake. Which register changes, and what does the memory hold at the end?

RUNIcarus Verilog · simulator service
Edit the code, then run it
Expected: 00000000 | addi x10, x0, 1 | a=0 b=1 alu=1 | x10 = 00000001 00000004 | slli x10, x10, 31 | a=1 b=1f alu=80000000 | x10 = 80000000 00000008 | lw x5, 0(x10) | a=80000000 b=0 alu=80000000 | x5 = 00000003 from mem[80000000] 0000000c | addi x6, x0, 0 | a=0 b=0 alu=0 | x6 = 00000000 00000010 | add x6, x6, x5 | a=0 b=3 alu=3 | x6 = 00000003 00000014 | addi x5, x5, -1 | a=3 b=ffffffff alu=2 | x5 = 00000002 00000018 | bne x5, x0, 0x10 | a=2 b=fffffff8 alu=fffffffa | taken: next is 00000010 00000010 | add x6, x6, x5 | a=3 b=2 alu=5 | x6 = 00000005 00000014 | addi x5, x5, -1 | a=2 b=ffffffff alu=1 | x5 = 00000001 00000018 | bne x5, x0, 0x10 | a=1 b=fffffff8 alu=fffffff9 | taken: next is 00000010 00000010 | add x6, x6, x5 | a=5 b=1 alu=6 | x6 = 00000006 00000014 | addi x5, x5, -1 | a=1 b=ffffffff alu=0 | x5 = 00000000 00000018 | bne x5, x0, 0x10 | a=0 b=fffffff8 alu=fffffff8 | not taken 0000001c | sw x6, 4(x10) | a=80000000 b=4 alu=80000004 | mem[80000004] = 00000006 00000020 | jal x1, 0x28 | a=0 b=8 alu=8 | x1 = 00000024, next is 00000028 00000028 | ebreak | stop x6=6 x1=00000024 the word at 80000004 holds 6 cycles=15
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 outputThe word at 8000_0000 holds 20. This program loads it and jumps over one instruction. A branch then tests x5 against 0, and 2 is added. What does the last row say?
// What do x6 and x1 hold at the end?
// Before the start, the word at 8000_0000 holds 20.
// The bench plays the decoder and the immediate generator: each program row says what they would say.
// 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 (.*);

  // ---- What the decoder says for each class of instruction. S2.5 opens this box.
  //                                reg_write, alu_b_select, result_select, mem_read, mem_write, branch, jump
  localparam logic [7:0] OP_IMM = {1'b1, ALU_B_IMM, RESULT_ALU      , 1'b0, 1'b0, 1'b0, 1'b0};
  localparam logic [7:0] LOAD   = {1'b1, ALU_B_IMM, RESULT_MEM      , 1'b1, 1'b0, 1'b0, 1'b0};
  localparam logic [7:0] JAL    = {1'b1, ALU_B_IMM, RESULT_PC_PLUS_4, 1'b0, 1'b0, 1'b0, 1'b1};
  localparam logic [7:0] BRANCH = {1'b0, ALU_B_IMM, RESULT_ALU      , 1'b0, 1'b0, 1'b1, 1'b0};
  localparam logic [7:0] STOP   = {1'b0, ALU_B_IMM, RESULT_ALU      , 1'b0, 1'b0, 1'b0, 1'b0};

  // ---- The memories of the bench.
  logic [31:0] rom [0:63];          // instruction memory, from address 0
  logic [7:0]  given [0:63];        // the control class of each row
  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, for the printed line
  logic [31:0] ram [0:255];         // data memory, 1 KiB from address 8000_0000
  int rows = 0, cycles = 0;
  task automatic row(input logic [31:0] word, input logic [7:0] control, input logic [3:0] alu, input logic [31:0] immediate_value, input string assembly);
    rom[rows] = word;  given[rows] = control;  operation[rows] = alu;  immediate[rows] = immediate_value;  text[rows] = assembly;  rows++;
  endtask

  // ---- The program.
  initial begin
    //  word          class   ALU      immediate    assembly
    row(32'h0010_0513, OP_IMM, ALU_ADD, 32'd1,      "addi x10, x0, 1");   // 00
    row(32'h01f5_1513, OP_IMM, ALU_SLL, 32'd31,     "slli x10, x10, 31");   // 04
    row(32'h0005_2283, LOAD,   ALU_ADD, 32'd0,      "lw x5, 0(x10)");   // 08
    row(32'h0080_00ef, JAL,    ALU_ADD, 32'd8,      "jal x1, 0x14");   // 0c
    row(32'h0642_8293, OP_IMM, ALU_ADD, 32'd100,    "addi x5, x5, 100");   // 10
    row(32'h0002_8463, BRANCH, ALU_ADD, 32'd8,      "beq x5, x0, 0x1c");   // 14
    row(32'h0022_8313, OP_IMM, ALU_ADD, 32'd2,      "addi x6, x5, 2");   // 18
    row(32'h0010_0073, STOP,   ALU_ADD, 32'd0,      "ebreak");   // 1c
    for (int n = 0; n < 256; n++) ram[n] = 0;
    ram[0] = 32'h0000_0014;   // the word at 80000000
    #1 rst_n = 0;   // a real falling edge: the reset is asynchronous
    #2 rst_n = 1;
  end
  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} = given[imem_addr[7:2]];
  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

  // ---- One printed line for each instruction, at the clock edge that ends its cycle.
  string effect;
  always @(posedge clk) if (rst_n) begin
    cycles++;
    if (imem_rdata == 32'h0010_0073 || cycles > 200) begin
      if (cycles > 200) $display("still running after 200 cycles");
      else $display("%08h | ebreak | stop", imem_addr);
      $display("x6=%0d x1=%08h", register(6), register(1));
      $finish;
    end
    effect = "";
    if (reg_write) 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 && imem_rdata[11:7] == 0) effect = $sformatf("next is %08h", dp.pc_next);
    else if (jump) effect = {effect, $sformatf(", next is %08h", dp.pc_next)};
    $display("%08h | %s | %s", imem_addr, text[imem_addr[7:2]], effect);
  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 does the ALU compute for sw x6, 4(x10)?
ConceptWhich path does the stored value take?
ConceptWhich block decides whether a branch is taken?
ConceptWhat does jal x1, 0x28 at address 20 in hex write, and where?
ConceptWhich three values can the result select of this page send to rd?

Common Mistakes

Wrong Send the stored value through the ALU.

The ALU is busy with the address. A store needs both at once.

Fix Take rs2_data round the ALU, straight to the data input of the memory.

Wrong Count a branch offset from the PC plus 4.

In RISC-V the offset counts from the branch itself.

Fix Add the immediate to the PC of the instruction.

Wrong Pass the word from the memory straight to rd.

That is right for lw only. A load of a byte or a half then gives a wrong value.

Fix Put the load unit between the memory and the result select.

Remember

  • For a load or a store, the ALU result is the address. A store sends rs2_data round the ALU to the memory.
  • A loaded word passes the load unit, which picks the byte, half or word, and then the result select.
  • A branch takes its target when the branch compare says so. A jal always does, and writes the PC plus 4 to rd.
  • A new kind of instruction joins at a multiplexer: the result select or the next-PC select.

Practice

Report a problem with this page