SUB

RISC-V SUB Instruction Details

Instruction ManualR-type

Subtract rs2 from rs1, place result in rd

Instruction Syntax

sub rd, rs1, rs2
Operand Breakdown
rd: receives the low XLEN-bit difference; writes to x0 are discarded.
rs1: minuend; rs2: subtrahend, giving rs1-rs2.
Sources are read before writeback; RV32I/RV64I use 32/64 bits respectively.
RV32IRV64IArithmetic

Instruction Behavior

SUB uses a 32-bit R-type encoding (opcode=0110011, funct3=000, funct7=0100000). It computes rs1-rs2 and writes the low XLEN bits to rd, without an arithmetic-overflow exception. XLEN is 32 in RV32I and 64 in RV64I. Writes to x0 are discarded. The base integer ISA has no SUBI; ADDI can subtract a constant only if its negation is encodable from -2048 through 2047.

SUB Decode And Execute Animation

RV32I/RV64I; XLEN-bit subtraction

sub rd, rs1, rs2

Execution Context

Assume successful instruction fetch, no asynchronous interrupt or extra extension checks; one initial value per register.

32-bit encoding0x40C58533
funct7 [31..25]
0100000
rs2 [24..20]
01100 → x12
rs1 [19..15]
01011 → x11
funct3 [14..12]
000
rd [11..7]
01010 → x10
opcode [6..0]
0110011
x11=0x00000014; x12=0x00000009
Not computed

Fetch

Decode the current instruction fields and read sources before writeback; no result has been committed.

x10=0x00000007; PC=0x00002000
Current architectural state (before commit)

These are teaching steps for architectural effects, not processor pipeline stages or cycles.

Quick Understanding & Search Notes

Subtract rs2 from rs1, place result in rd

Read rs1 and rs2 before writing rd; overlapping register names read the same old value.
RV32I/RV64I retain the low 32/64 bits of the difference.

Common Usage Scenarios

Register difference

RV32I/RV64I, x6=20 and x7=7: sub x5, x6, x7 gives x5=13, retaining only low XLEN bits.

Negation

RV32I/RV64I, x7=7: sub x5, x0, x7 writes XLEN-bit -7 to x5, equivalent to neg x5, x7.

Pre-Use Checklist

Syntax Check
  • Register fields select x0–x31 or their ABI names.
  • SUB uses rd, rs1 and rs2, with no immediate.
Semantic Check
  • Compute rs1-rs2, retaining only the low XLEN bits.
  • Arithmetic overflow raises no exception; x0 writes are discarded, and overlapping registers are read before writeback.

Pitfalls / Common Confusions

Operand order is rs1-rs2.
Only low XLEN bits are retained; arithmetic overflow raises no exception.
To subtract a constant with ADDI, its negation must fit -2048 through 2047.

FAQ

How is SUB encoded differently from ADD?

Both use opcode=0110011 and funct3=000; SUB has funct7=0100000 and ADD has 0000000.

How can I subtract immediate 8?

Use addi rd, rs1, -8. ADDI requires a signed 12-bit immediate from -2048 through 2047; one ADDI cannot encode every constant subtraction.