I'm new in MIPS language and I don't understand how the functions (procedures) in the MIPS assembly language work. Here are but I will specify my problem :
What does:
jal
jr
$ra
mean in mips language and the important thing
This describes the conventions used for calling functions, in particular how the stack is managed and parameters are exchanged (there is no hardware stack in MIPS, everything is a matter of software conventions, and the ABI defines those conventions).
Data flow in MIPS — A function can “return” up to two values by placing them in registers $v0-$v1, before returning via jr. These conventions are not enforced by the hardware or assembler, but programmers agree to them so functions written by different people can interface with each other.
Control flow in MIPS The jal saves the return address (the address of the next instruction) in the dedicated register $ra, before jumping to the function. jal is the only MIPS instruction that can access the value of the program counter, so it can store the return address PC+4 in $ra.
Firstly, you might want to check this quick MIPS reference. It really helped me.
Secondly, to explain jal
, jr
and $ra
. What jal <label>
does is jump to the label
label and store the program counter (think of it as the address of the current instruction) in the $ra
register. Now, when you want to return from label
to where you initially were, you just use jr $ra
.
Here's an example:
.text
main:
li $t0, 1
jal procedure # call procedure
li $v0, 10
syscall
procedure:
li $t0, 3
jr $ra # return
You will notice when running this in a SPIM emulator that the value left in $t0
is 3, the one loaded in the so-called procedure.
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With