slt

slt

RISC-V Assembly Reference

lyszt.net covers slt and other RISC-V instructions in more detail.

Encoding format

R
31–25funct7
24–20rs2
19–15rs1
14–12funct3
11–7rd
6–0opcode
I
31–20imm[11:0]
19–15rs1
14–12funct3
11–7rd
6–0opcode
S
31–25imm[11:5]
24–20rs2
19–15rs1
14–12funct3
11–7imm[4:0]
6–0opcode
B
31–25imm[12,10:5]
24–20rs2
19–15rs1
14–12funct3
11–7imm[4:1,11]
6–0opcode
U
31–12imm[31:12]
11–7rd
6–0opcode
J
31–12imm[20,10:1,11,19:12]
11–7rd
6–0opcode

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