Function Parameters
Compiler Implementation
COP-3402 COP-3402
What is a function?
How do we implement functions?
With local state that works with recursion?
Components of a stack frame
- Parameters
- Return address
- Caller's base pointer
- Local variables
Local variables
How do we allocate locals?
(Diagram)
function paramtest localvars x inparam params inparam x := inparam return x
Passing parameters
- The caller passes via
- registers (first 6 parameters)
- stack entries (remaining parameters)
- The callee uses these parameters
The use of registers and the stack is part of the System V AMD64 ABI conventions. Other ABIs use only the stack.
If we want interoperability with other C functions from gcc on our system, we need to follow this ABI.
Callee
Takes one parameter called inparam
.
function paramtest localvars x inparam params inparam x := inparam return x
Caller
Passes 7
to paramtest
.
function main localvars argc argv retval params argc argv retval := call paramtest 7 return retval
Stack frame
(Diagram)
retval := call paramtest 7
- What is the behavior of main?
- call paramtest, passing 7
- paramtest assigns inparam to x, i.e., 7
- returns 7
- main stores 7 into retval
- returns 7
- Setup parameters
- Copy to register
- Make the call
- Tear down any changes to the stack
cat << EOT | codegen > paramtest.s function paramtest localvars x inparam params inparam x := inparam return x EOT cat << EOT | codegen > main.s function main localvars argc argv retval param params argc argv param := 7 retval := call paramtest param return retval EOT gcc -o main main.s paramtest.s ./main echo $?
Handling parameters in the callee
- Simple scheme
- Treat all parameters as local variables
- Copy from registers and stack to local variables
Handling return values
Tracing assembly wtih gdb
C Interoperability
libio
compiler/examples/io
Calling SimpleIR functions
compiler/examples/interop