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
Destination rd: register receiving the operation result.
Source rs1: register holding the first operand.
Source rs2: register holding the second operand.
RV32IArithmetic

Instruction Encoding

31..25
funct7
24..20
rs2
19..15
rs1
14..12
funct3
11..7
rd
6..0
opcode

SUB uses opcode 0110011 (0x33), funct3 000, funct7 0100000. The rs1 and rs2 fields select the two source registers, and rd selects the destination register.

Format: R-type
opcode: 0110011 (0x33)
funct3: 000 (0x0)
funct7: 0100000 (0x20)

Instruction Behavior

SUB (R-type) subtracts rs2 from rs1 (overflow ignored), writing to rd. funct7=0100000, funct3=000. Bit30=1 in funct7 distinguishes SUB from ADD (same funct3/opcode). There is no SUBI; use ADDI with a negated immediate instead.

Quick Understanding & Search Notes

SUB subtracts rs2 from rs1 and writes rd. It is register subtraction; the base integer ISA has no immediate subtract, so subtracting a small constant is normally ADDI with a negative immediate.

SUB shares opcode/funct3 with ADD and is distinguished by funct7=0100000.
Integer subtraction overflow does not raise an exception.

Common Usage Scenarios

Address & Pointer

Understand this scenario with real code like «sub x5, x6, x7 # x5 = x6 - x7».

Basic Arithmetic

Understand this scenario with real code like «sub x5, x6, x7 # x5 = x6 - x7».

Numerical Computing

Understand this scenario with real code like «sub x5, x6, x7 # x5 = x6 - x7».

Pre-Use Checklist

Syntax Check
  • Confirm the current instruction format is R-type.
  • Confirm the operand order matches the example.
Semantic Check
  • Ensure the destination register usage is compatible with the calling convention.
  • Confirm this is not the lower-level form of a pseudo-instruction expansion.

Pitfalls / Common Confusions

Overflow silently ignored
No immediate subtraction; use ADDI with negated immediate
funct7 bit30=1 distinguishes SUB from ADD; wrong funct7 changes operation

FAQ

How is SUB encoded differently from ADD?

They share opcode and funct3. SUB uses funct7=0100000, while ADD uses funct7=0000000.

How do I subtract an immediate?

Use ADDI with a negative immediate, for example addi rd, rs1, -8 to subtract 8.