5. Functions
Functions! Now we must learn some convections (arguments, return values, flow in/out, contracts) before we start learning functions.
Every program's instructions are in memory, so they have addresses.
The program counter (PC) holds the address of the next instruction to run and is incremented by a word.
With the first image, we just defined some basic terms. Let's see how the functions flow.
MIPS
To call a function, we use jump and link
All jal does is jumps to a new location, and makes a link back to the old one in the ra
(return address) register.
So now let's return back to the main function.
The jump to address in register (ra
) just copies ra into the pc.
Arguments and Return Values
a0-a3 are the argument registers.
v0-v1 are the return value registers.
Danger
USE THESE CONVECTIONS, YOU WILL LOSE POINTS IF YOU DON'T!!!!
ALWAYS pass arguments in a-registers
ALWAYS return arguments in v-registers
Calling a Function
Functions are like black boxes, you only need to know inputs and what it will spit out.
This should output 8.
Writing a Function
Convention
Remember the conventions above about the return and arguments values? Well, you also need to keep in mind that some registers are saved and unsaved.
What a minute, how do we save the saved registers so we do not change them when we need to use them in our function. Use the stack
The Stack
In CS 0445, the stack was one of our data structures that we covered. We imagined it growing upward, however, in memory it grows downward because of the heap.
To push elements, you need to subtract the stack pointer and store the word at that address (or just use the pseudo operation).
And to pop elements, you need to load the word and add to the stack pointer (or just use the pseudo operation).
How to Save the Saved Registers
Below is an example function of spoon
that uses s0
: