bgtpseudo

bgt

pseudo
RISC-V Assembly Reference

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

Description

bgt is a branch that fires when one value is greater than another. Its name stands for branch if greater than. The instruction below jumps to the label when rs1 is strictly greater than rs2, comparing them as signed values.

bgt rs1, rs2, label

None of the six core RISC-V branches tests for greater-than. Whether a is greater than b is the same question as whether b is less than a with the operands exchanged. bgt is a pseudo-instruction, and the assembler rewrites it as blt with the operands reversed. The hardware stays simpler and the comparison can still be written in the direction that reads naturally. The underlying less-than branch is described under blt.

Reach for bgt when the condition reads naturally in that direction, for instance branching away once a value exceeds a maximum, once a length is larger than the space set aside for it, or when picking the larger of two paths.

The RISC-V manual states that bgt, bgtu, ble and bleu can be synthesized by reversing the operands to blt, bltu, bge and bgeu.

Strictly is the load-bearing word. bgt does not branch when the two values are equal. To count equal values as well, use bge, which branches on greater than or equal. Off-by-one errors in loops and checks usually come from this distinction. The comparison is signed. For unsigned data the same swap applies to bltu.

Expands to

blt rs2, rs1, label

The assembler replaces this pseudo-instruction with the real instruction or instructions listed above.

Example

li t0, 5
li t1, 2
bgt t0, t1, done   # 5 > 2, so jump to 'done'