slt
lyszt.net covers slt and other RISC-V instructions in more detail.
Encoding format
Description
slt compares two numbers and stores the result as 1 or 0. The name stands for set less than. The form below tests whether rs1 is less than rs2. If the test succeeds, the instruction writes 1 to destination register rd. If it fails, it writes 0.
slt rd, rs1, rs2
A comparison can be used in two ways. A branch instruction jumps based on it. Alternatively, the yes or no answer can be stored as a number, 1 for true and 0 for false, and used later. slt does the storing. Assembly represents true and false with the stored 1 or 0, and that value can be added, masked or combined like any other number.
The comparison treats the values as signed, so they may be negative, and -1 counts as less than 0. The related instruction sltu treats them as unsigned, which changes the answer for large values and for values that look negative.
The RISC-V manual describes slt and sltu as the signed and unsigned compares that write 1 to rd if rs1 is less than rs2 and 0 otherwise. It also uses slt in an overflow check for general signed addition. After the add, the second line below records whether the second operand is negative, the third line records whether the sum is less than the first operand, and the last line jumps when the two answers differ.
add t0, t1, t2 slti t3, t2, 0 slt t4, t0, t1 bne t3, t4, overflow
The reasoning is that the sum should be less than one operand only when the other operand is negative.
No set greater than instruction exists. To test whether a is greater than b, swap the operands and ask whether b is less than a. The example compares 3 and 9. Since 3 is less than 9, t2 is set to 1.
Example
li t0, 3 li t1, 9 slt t2, t0, t1 # t2 = 1
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.4, Integer Computational Instructions, page 27.
