Passing Arguments: MIPS
No need to use lw
which is for extracting words from memory. You can simply use $a0
in the sub-routine.
Take a look at this example of a "print-char" function:
.text
main:
#save $ra on stack
addi $sp $sp -4
sw $fp 0($sp)
move $fp $sp
addi $sp $sp -4
sw $ra -4($fp)
#call sub-routine
addi $a0 $zero 'A'
jal printchar
#restore and shrink stack
lw $ra -4($fp)
lw $fp 0($fp)
addi $sp $sp 8
jr $ra
#prints a char and then a new line
printchar:
#call print-char syscall
addi $v0 $zero 11
syscall
addi $a0 $zero 10
syscall
jr $ra
As demonstrated, you the value of the $a0
register is just used in the sub-routine as it returns the value that it was given before the jal
.
Also demonstrated is proper expansion and shrinking of the stack as is necessary for calling a sub-routing. As you will notice, the sub-routine does not perform this operation as it does not call a sub-routine and there-fore does not need to save the $ra
. Stack manipulations would also be required in the sub-routine if it were to use an $s
register as the MIPS calling convention specifies these as callee saved.
![Victor Brunell](https://i.stack.imgur.com/EzirQ.jpg?s=256&g=1)
Victor Brunell
Updated on March 28, 2021Comments
-
Victor Brunell over 3 years
I'd like to pass a character as an argument to a function in MIPS. Do I do this by storing the character into register $a0, use jal to move to the function, then extract what's in $a0 into a separate register using lw?
If someone could give me an example of passing an argument or two in MIPS, I'd really appreciate it. I've found a lot of info on the MIPS calling conventions, but not any simple and succinct examples.
-
BananaBuisness almost 8 yearsWhy are you doing manipulations on the stack? is it essential?
-
Konrad Lindenbach almost 8 years@AsafFisher You must store the value of the
$ra
somewhere when you call a subroutine asjal
overwrites it.This could be done by using an$s
register, but I was just demonstrating the general method for saving$ra
on the stack with manipulation of$sp
and$fp
. -
BananaBuisness almost 8 yearsOk so why not using only sp? Why are you using also fp?
-
Konrad Lindenbach almost 8 years@AsafFisher Using
$fp
, the frame pointer, allows for dynamic allocation on the stack within the function. I've heard it said that$fp
is rarely used in hand-written assembly, and you're certainly free to leave it out -- it's not necessary in this example. -
john ktejik about 6 yearsWhat about if you have to pass in a lot of parameters?
-
ggorlen over 3 years@KonradLindenbach Stack manipulations would also be required in the sub-routine if it were to use an $s register as the MIPS calling convention specifies these as caller saved. I think you mean callee saved here since the function that was called is required to preserve the
$s
registers. Your other answer correctly says "$s
registers are callee saved." -
ggorlen over 3 years@johnktejik See MIPS function call with moe than four arguments