bgezpseudo

bgez

pseudo
RISC-V Assembly Reference

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

Description

bgez takes a branch when the value in a register is zero or positive. The name means branch if greater than or equal to zero. The form below jumps to the labeled position when rs is at least zero, and falls through to the next instruction otherwise.

bgez rs, label

The assembler treats it as a pseudo-instruction and rewrites it to the instruction below, which compares the register against zero, the register that always holds 0.

bge rs, zero, label

The comparison is signed, so the 32 bits in the register are read as a number that can be negative. Zero counts as a match, which separates bgez from bgtz. It is the opposite of bltz, so for any value exactly one of the two takes the branch. See bge for the comparison of two registers.

bgez is the natural test for a value that must not be negative, such as a length, a count or an index. A program that subtracts one from a counter and keeps looping while the counter has not gone below zero uses it at the end of the loop.

addi t0, t0, -1
bgez t0, loop

The loop above repeats while t0 is 0 or more after the subtraction, so it runs once more with t0 equal to 0 and stops when t0 reaches -1.

Expands to

bge rs, zero, label

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

Example

li t0, 4
bgez t0, done   # t0 >= 0, so jump to 'done'