bnez
pseudolyszt.net covers bnez and other RISC-V instructions in more detail.
Description
bnez branches when a register holds a value other than zero. The name means branch if not equal to zero. The form below jumps to the label when rs is non-zero.
bnez rs, label
The assembler expands this pseudo-instruction into the instruction below, which compares against the register that always holds zero.
bne rs, zero, label
For the zero test see beqz, and for branches in general see beq.
beqz frequently guards exits, while bnez frequently keeps a loop running. While characters remain to be read, the loop keeps scanning. While the counter has not run out, it keeps going. A common short loop ending decrements a register and loops while the value is non-zero. It subtracts one, then jumps back to the top with bnez.
bnez also acts on true or false values computed earlier. Set instructions such as slt leave a 1 or 0 in a register, and a following bnez branches on that result. A register holding a yes or no value can be tested with bnez.
The RISC-V manual gives one reason its branches compare two registers rather than comparing one register against zero. A comparison against zero needs a non-trivial circuit delay, so it costs almost as much as an arithmetic magnitude comparison. bnez is therefore a pseudo-instruction that uses bne with zero.
Another frequent use checks results. When a function returns 0 for success and non-zero for failure, the caller follows the call with the line below to jump to error handling whenever something went wrong. This is the assembly form of checking a return code.
bnez a0, error
Expands to
bne rs, zero, label
The assembler replaces this pseudo-instruction with the real instruction or instructions listed above.
Example
li t0, 5 bnez t0, done # t0 != 0, so jump to 'done'
