My first question is
when adjusting stack space, why was the number 8 chosen? I'm assuming it means 8 bytes, but how was it determined that 8 bytes would be needed to adjust? I know we are supposed to allocate enough space for all the arguments (in this case, one argument) and I'm guessing also for the return address, but how do we know how many bytes each one needs?
I'm trying to read through the code to understand what happens, but I get confused at
beq $t0, $zero, L1.
I know from here we branch to where it says L1, where n is decremented by 1, but then I'm confused. Does
jal fact
mean we immediately return to where it says fact at the top, but this time with the argument being n = 1 instead of n = 2? [assuming n = 2 was our original argument] At what point do we reach the code where it says to multiply $a0 and $v0?
I am honestly having a really hard time wrapping my brain around all of this. If I've understood it, everytime the factorial function is called, a new "stack frame" is added to the stack...each frame allocates 8 bytes into the stack? and each new frame contains a return address to return to the procedure that called it..If I'm understanding that correctly, I'm having difficulty seeing it in code.
Answer 1 is in your code´s comments:
This "8" depends on your code, it is the "n" in the picture.
8 byte because you need place for two values. Each integer value has 4 byte...
The values are one parameter and the return address.
(The caller and the called function have two separate return addresses,
but in the register is only place for one.
So the caller saves his address on the stack temporarily)
About the beq
: Correct. If $t0
and $zero
are equal (ie. $t0
has the value 0) then jump to L1
.
And about the jal
...
Well, to put it in one or two words: It´s a function call, no jump.
If you have no function calls or jumps, your code is processed top-down, each instructon.
Imagine you have something in the computer pointing here you are right now.
So, if the jal is to be processed, it points to the jal instruction.
What the happens there:
You get a another instruction pointer to the first instruction of fact,
hile the first one remains at jal
.
Then, the second pointer will go top-down the function,
while the first one remains where it was.
Until the second pointer reaches his end: jr
.
There, the second pointer is removed again,
and the first one will continue where it stopped before.
...
The "magic" about recursion is, that the second pointer could spawn a third
and wait for him and so on...
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments