caesar
caesar

Reputation: 3135

Mips function declarion

Hi everyone I've just started Mips and I got a procedure(function decleration) I couldn't understand the some part of it.Is there anyone to help me to understand ? Thanks in advance.

transition of mips in to high level language.

int leaf_example (int g, int h, int i, int j) { 
     int f= (g+h)-(i+j); return f;}

Mips code :

    # g,h,i and j corresponds to $a0-$a3 

    # g,h,i and j corresponds to $a0-$a3
    # adjust stack for 3 items # save register $t1,$t0 # and $s0 for # use afterwards
    Sub $sp,$sp,-12 
    sw $t1,8($sp) 
    sw $t0,4($sp) 
    sw $s0,0($sp)

   # Body of procedure

    add $t0,$a0,$a1  # $t0=g+h
    add $t1,$a2,$a3  # $t1=i+j
    sub $s0,$t0,$t1  # $s0=(g+h)-(i+j)

# return the value of f, copy into value register

  add $v0,$s0,$zero #$v0=$s0


# before returning, we need to restore values

lw $s0,0($sp)  # restore register
lw $t0,4($sp)  # $s0,$t0,$t1 for
lw $t1,8($sp)  # caller.
add $sp,$sp,12 # release stack
jr $ra         # jump back to calling routine

Now I wonder why should I do " # adjust stack for 3 items # save register $t1,$t0 # and $s0 for # use afterwards" part. Could I start from body of procedure without doing it ?

secondly, why should I do add $v0,$s0,$zero #$v0=$s0 ? I've already inserted my result into $s0 ?

I'll be greathful if I get some answers.

Upvotes: 0

Views: 174

Answers (1)

Konrad Lindenbach
Konrad Lindenbach

Reputation: 4961

This question all has to do with the MIPS calling procedure.

Essentially, when you write a function in MIPS assembly, you should follow the following conventions:

  • Arguments are taken in $a0 - $a4
  • Return values are returned in $v0 and $v1
  • $s variables are saved and restored (so that they appear not to have changed).

In order to fullfill these points (the third), you need to use the stack to save $s variables. So this is the purpose of expanding the stack in your example is to save variables (although the $t variables are not normally saved by the callee -- the convention dictates that these are caller saved).

Upvotes: 2

Related Questions