gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

ASM > Returning values

#45097 - ymalik - Tue Jun 07, 2005 6:02 pm

The following ASM function is supposed to return a value:
Code:

// int func(int);
func:
   add r0, r1, #4
   mov px, lr

However, when I call it as
Code:

x = func(34);

and print out the value of x in GDB, I get 1378954186.
According to the ARM Procedure Call Standard, r0 and r1 can serve as return values.

#45099 - tum_ - Tue Jun 07, 2005 6:06 pm

ymalik wrote:
The following ASM function is supposed to return a value:
Code:

// int func(int);
func:
   add r0, r1, #4
   mov px, lr

However, when I call it as
Code:

x = func(34);

and print out the value of x in GDB, I get 1378954186.
According to the ARM Procedure Call Standard, r0 and r1 can serve as return values.


The content of r1 is unknown, so the result is not surprising.

#45102 - strager - Tue Jun 07, 2005 6:17 pm

ymalik wrote:
The following ASM function is supposed to return a value:
Code:

// int func(int);
func:
   add r0, r1, #4
   mov px, lr



Here's your code with comments:
Code:

// int func(r0, r1, r2, r3);
func:
    add r0, r1, #4 @r0 = r1 + 4
    mov pc, lr  @ return to same caller
    @ return(r0)


The correct way is to use this code:
Code:

// int func(r0, r1, r2, r3)
func:
    add r0, r0, #4 @ r0 += 4
    bx lr  @ return to specific caller
    @ return(r0)

#45104 - ymalik - Tue Jun 07, 2005 6:19 pm

Ok, I thought that if you returned a value, the parameters would be stored in r1-r3 (for a 4-byte return value).

#45105 - strager - Tue Jun 07, 2005 6:33 pm

No, each register is 4 bytes each, and parameters are passed in registers 0 to 3. Any more parameters are pushed into the stack. The return value is always stored in r0.

#45107 - Quirky - Tue Jun 07, 2005 7:10 pm

With GCC you can return structs in registers according to the documentation for -freg-struct-return

#45110 - strager - Tue Jun 07, 2005 7:14 pm

Quirky wrote:
With GCC you can return structs in registers according to the documentation for -freg-struct-return


But it is better to return plain-old pointers.

#45116 - tepples - Tue Jun 07, 2005 7:46 pm

strager wrote:
But it is better to return plain-old pointers.

Do you mean return pointers to static data, or do you mean return pointers obtained from malloc()?
_________________
-- Where is he?
-- Who?
-- You know, the human.
-- I think he moved to Tilwick.

#45121 - ymalik - Tue Jun 07, 2005 7:56 pm

You can return structs in registers as long as the struct is less than 8 bytes. A struct is just a sequence of bytes, after all.