MIPS Assembly/Control Flow Instructions

Jump Instruction
The jump instructions load a new value into the PC register, which stores the value of the instruction being executed. This causes the next instruction read from memory to be retrieved from a new location.

The j instruction loads an immediate value into the PC register. This immediate value is either a numeric offset or a label (and the assembler converts the label into an offset).

The jr instruction loads the PC register with a value stored in a register. As such, the jr instruction can be called as such:

jr $t0

assuming the target jump location is located in $t0.

Jump and Link
Jump and Link instructions are similar to the jump instructions, except that they store the address of the next instruction (the one immediately after the jump) in the return address ($ra; $31) register. This allows a subroutine to return to the main body routine after completion.

Like the j instruction, except that the return address is loaded into the $ra register.

The same as the jr instruction, except that the return address is loaded into a specified register (or $ra if not specified)

Example
Let's say that we have a subroutine that starts with the label MySub. We can call the subroutine using the following line:

jal MySub ...

And we can define MySub as follows to return to the main body of the parent routine:

jr $ra

Branch Instructions
Instead of using rt as a destination operand, rs and rt are both used as source operands and the immediate is sign extended and added to the PC to calculate the address of the instruction to jump to if the branch is taken.

Branch if rs and rt are equal. If rs = rt, PC ← PC + 4 + imm.

Branch if rs and rt are not equal. If rs ≠ rt, PC ← PC + 4 + imm.

Branch if rs is greater than or equal to zero. If rs ≥ 0, PC ← PC + 4 + imm.

Branch if rs is less than or equal to zero. If rs ≤ 0, PC ← PC + 4 + imm.

Branch if rs is greater than zero. If rs > 0, PC ← PC + 4 + imm.

Branch if rs is less than zero. If rs < 0, PC ← PC + 4 + imm.

Set Instructions
These instructions set rd to 1 if their condition is true. They can be used in combination with beq and bne and $zero to branch based on the comparison of two registers.

If rs < rt, rd ← 1, else 0.

If rs < imm, rd ← 1, else 0. The immediate is sign extended.

If rs < rt, rd ← 1, else 0. Treat rs and rt as unsigned integers.

If rs < imm, rd ← 1, else 0. The immediate is sign extended, but both rs and the extended immediate are treated as unsigned integers. The sign extension allows the immediate to represent both very large and very small unsigned integers.