neg
pseudolyszt.net covers neg and other RISC-V instructions in more detail.
Description
neg reverses the sign of a number: 5 becomes -5, and -5 becomes 5. The name shortens negate. The form below places the negation of source register rs into destination register rd.
neg rd, rs
neg is a pseudo-instruction. An assembler rewrites a pseudo-instruction, which is a readable name, into one or more real instructions before the processor encounters it. neg becomes the instruction below, which subtracts the number from zero, the special register that always holds 0.
sub rd, zero, rs
0 minus x equals -x, so this produces the negation. RISC-V keeps its set of real instructions small by reusing subtraction and the zero register this way.
The range of negative numbers extends one step past the positive range. It reaches about -2.1 billion and only about +2.1 billion. The most negative number has no positive counterpart, so negating it wraps around and yields the same number. Code that computes absolute values must account for this case.
The RISC-V manual defines sub as the subtraction of rs2 from rs1 and describes register x0, called zero here, as hardwired to a value whose bits are all 0. Subtracting a value from x0 produces its negative, which is the form neg becomes.
The example negates 5 into -5. Combined with a branch that skips neg when the number is already positive, it produces the usual two-instruction absolute value.
Expands to
sub rd, zero, rs
The assembler replaces this pseudo-instruction with the real instruction or instructions listed above.
Example
li t0, 5 neg t1, t0 # t1 = -5
References
- [1]RISC-V International. The RISC-V Instruction Set Manual, Volume I: Unprivileged Architecture. Version 20260120. Section 2.4.2, Integer Register-Register Instructions, page 29.
- [2]RISC-V International. The RISC-V Instruction Set Manual, Volume I: Unprivileged Architecture. Version 20260120. Section 2.1, Programmers' Model for Base Integer ISA, page 23.
