Retargeting lcc compiler: passing structure arguments

445 views Asked by At

I am trying to retarget lcc for a custom VM. I am facing a problem when passing structures as arguments (by value). The VM's stack grows from low to high addresses. The offsets for the structure fields are being incorrectly generated for arguments.

For e.g., for the code below:

foo(sample p, sample q); 

struct sample 
{ 
    int a; 
    int b; 
}; 
main() 
{ 
    sample x, y; 
    foo(x, y); 
} 

The structures fields a and b as seen by foo() are located at address (&p and &p-4) and (&q and &q-4). These should be (&p and &p+4) and (&q and &q+4). The addresses for struct x and y in main() are correctly referring to their fields (i.e. addresses being generated are &x, &x+4 and &y, &y+4). I have verified that the code generated for ARG+B nodes is correctly copying the passed struct argument on the stack (the base of the copied struct begins at lower address).

Any help would be appreciated.

1

There are 1 answers

6
Mahonri Moriancumer On

Your observation of how your compiler lays down the stack can often cause confusion.

The stack may grow in either direction, depending on the system. My experience is that most grow from highest address to lowest address as per your observation on your system (with 'x' and 'y').

The values 'a' and 'b' within the structure are another matter. The compiler has no prerogative to reorder these. The C specification requires these to be ordered, within the structure, as they are defined.

Hence, your observations, while surprising, are correct; and the compiler is operating properly as well.

(Or, perhaps I am mis-understanding the detail provided?)