main: int a, b, c; c = sum(a, b); |
int sum(int x, int y) { x = x + 1; y = y + 1; return ( x*x + y*y ); } |
main: move.l a, -(a7) * Pass a on stack move.l b, -(a7) * Pass b on stack bsr sum * Call subroutine sum adda.l #8, a7 * remove a and b from stack move.l d0, c * put return value in c |
+---------------+ | free space | +---------------+ <----- a7 (stack pointer) 0(a7) | return address| +---------------+ 4(a7) | b | parameter y (has the value b) +---------------+ 8(a7) | a | parameter x (has the value a) +---------------+ | ..... | |
The subroutine returns the value in register D0.
sum: move.l 8(a7), d0 * puts first parameter x in d0 add.l #1, d0 move.l d0, 8(a7) * puts x+1 back into the param var x move.l 4(a7), d0 * puts 2nd parameter y in d0 add.l #1, d0 move.l d0, 4(a7) * puts y+1 back into the param var y move.l 8(a7), d0 * puts first parameter x in d0 muls d0, d0 * now d0 = x*x move.l 4(a7), d1 * puts second parameter y in d1 muls d1, d1 * now d1 = y*y add.l d1, d0 * now d0 = x*x + y*y, in agreed return location rts |
NOTE:
That's why we need:
main: move.l a, -(a7) move.l b, -(a7) bsr sum adda.l #8, a7 * remove (pop) a and b from stack move.l d0, c * put return value in variable c |