5.1.7 · D3Instruction Set Architecture (ISA)

Worked examples — RISC-V base ISA (RV32I - RV64I)

2,711 words12 min readBack to topic

The scenario matrix

Before we compute anything, let's map the territory. Instruction encoding has a small number of independent "axes" that can each flip. A worked example is only useful if, together with the others, it visits every cell.

Axis (what can vary) Cell A Cell B Cell C
Immediate sign positive imm negative imm zero / edge (-2048, +2047)
Format & field layout I-type (contiguous imm) S-type (imm split in two) B/J-type (imm split and scaled ×2)
Fits in one instr? yes (≤12 bits) no → needs lui+addi pair huge → 64-bit RV64I
Branch direction forward (imm > 0) backward (imm < 0) not-taken (fall through)
Degenerate / x0 uses x0=0 nop (all-zero effect) overflow wrap-around
RV32I vs RV64I 32-bit sign-extend 64-bit sign-extend addw 32-bit wrap on 64-bit reg

Below, each example is tagged with the cells it covers. By example 9 every cell above has been visited at least once.


Example 1 — Positive I-type immediate (cells: positive imm · I-type · fits · RV32I)


Example 2 — Negative I-type immediate (cells: negative imm · I-type · sign-extend RV32I)


Example 3 — The immediate boundaries (cells: edge imm -2048/+2047 · degenerate)


Example 4 — S-type: the split immediate (cells: negative imm · S-type split)

Look at

Figure — RISC-V base ISA (RV32I - RV64I)
: the store immediate is torn into a high piece imm[11:5] (7 bits, top of the word) and a low piece imm[4:0] (5 bits, where rd sits in other formats). The teal brackets show which bits go where.


Example 5 — Loading a big constant (cells: doesn't fit · lui+addi · signed-low correction)


Example 6 — When the low part is positive (no rounding) (cells: positive imm · lui+addi)


Example 7 — Backward branch (a loop) (cells: negative imm · B-type split+scaled · backward)

See

Figure — RISC-V base ISA (RV32I - RV64I)
: two instructions on an address line. The bne sits at 0x104; the arrow curves backward to loop at 0x100, so the offset is negative and small.


Example 8 — Forward jump range & the ±1 MiB limit (cells: positive imm · J-type · limiting value · exam twist)


Example 9 — Degenerate & RV64I wrap (cells: nop · overflow wrap · RV64I addw)


Active recall

Recall Which cells are still uncovered after Example 9? (answer)

None — every row of the matrix (sign, format layout, fit, direction, degenerate, RV32I/RV64I) was hit. ✓

Recall Reveal

Why does 0xEEF force a +1 on the lui part but 0x678 does not? ::: 0xEEF has bit 11 set → signed-negative → the addi subtracts, so the upper part is pre-incremented to compensate. 0x678's bit 11 is clear → positive → no correction. A 12-bit signed immediate's range? ::: . Real reach of a jal (J-type)? ::: bytes = MiB (offsets scale by 2). What is addi x0, x0, 0? ::: The canonical nop — the write to x0 is discarded.

Related: RISC vs CISC · Assembler & Pseudo-instructions (the li and nop expansions live there).