MIPS Compiler local variables -
i'm writing tinyc compiler translates mips assembly. i'm stuck question how implement local variable handling. following example makes hard think of proper solution:
int* funca() { int = 3; return &a; } int main() { return *(funca()); }
normally create local variable on stack. in case 'int a' created on stack. problem in end want return address of 'a' , not value &a. in moment leave 'funca()' reset stack old state , pointer return in end not valid anymore , show later nirvana.
my first attempt handle registers, &-operator translate this:
.globl funca funca: addiu $sp, $sp, -4 # save return address sw $ra, ($sp) addiu $sp, $sp, -4 # save reg use further processing sw $s0, ($sp) addiu $t0, $zero, 3 # $t0 = , add 3 la $s0, ($t0) la $t0, ($s0) sw $t1, ($t0) # crashes here la $v0, ($t1) # put result in $v0 lw $s0, ($sp) addiu $sp, $sp, 4 # restore stack lw $ra, ($sp) addiu $sp, $sp, 4 jr $ra # jump
it crash in marked line because destination register doesn't have address store something. 1 idea to create datasegment every local variable, overhead , wouldn't work recursive functions.
does have proper solution how handle local variables if return address local variable , not value?
any appreciated!
the primary issue running example c starting not code. same issue trying implement code in mips exists in original, c code. should never create local variable within function , try return address. local variable held in register or on stack , data wiped out.
for example, wrote bit of code in c illustrate , compiled mingw32-gcc:
int* funca() { int = 3; return &a; } int main (void) { int * mypointer; mypointer = funca(); return 0; }
the compiler produces warning:
warning: function returns address of local variable
Comments
Post a Comment