# Writing a method using MIPS code

I am trying to understand how convert C code to MIPS code and I have having trouble understanding why the stack pointer( $sp ) needs to be manipulated before and after the procedural code.Isn't the program supposed to automatically increment the stack pointer after every instruction? C CODE : int myMethod (int g, h, i, j) { int f; f = (g + h) - (i + j); return f; }  If we let g, h, i, j =$a0, $a1,$a2, $a3 and f =$s0 and result = $v0 then, MIPS CODE : addi$sp, $sp, -4 sw$s0, 0($sp) add$t0, $a0,$a1
add  $t1,$a2, $a3 sub$s0, $t0,$t1         #SUB STATEMENT
add  $v0,$s0, $zero lw$s0, 0($sp) addi$sp, $sp, 4 jr$ra


I don't really know why the stack pointer is decremented by 1 word size and then it's value loaded into the f variable, if you look at the subtraction statement you will notice that the value of f is then overwritten by the result of the subtraction so what was the use?

Isn't the program supposed to automatically increment the stack pointer after every instruction?

No. You're confusing the stack pointer with the program counter. The PC is incremented after every instruction.

I don't really know why the stack pointer is decremented by 1 word size

To make room on the stack for the local variable f.

and then its value loaded into the f variable, if you look at the subtraction statement you will notice that the value of f is then overwritten by the result of the subtraction so what was the use?

None. It's redundant. An optimization flag would probably have removed that.

• So we increased the stack by one word and then moved the contents of the register $s0 to the first position of the stack so we could use the register to store the local variable f during the method execution process, and then we restored$s0 at the end right? If we didn't need the contents of $s0 to be stored would we need to increase the stack? We could just use$s0 and we would not care what final value would be left in there right? – KillaKem Mar 26 '13 at 15:32
• That's all correct. If you wrote a more complex method you would see the register \$s0 spill into the stack slot in the generated code. – user207421 Mar 26 '13 at 21:44