The MASM Forum Archive 2004 to 2012

General Forums => The Campus => Topic started by: victorvmpm on October 05, 2010, 05:13:43 PM

Title: generating array code
Post by: victorvmpm on October 05, 2010, 05:13:43 PM
Hi, I'm studying in the university and I was wondering how a compiler creates the code for an array on a stack?

I was thinking of int a[5]

it would be:
mov eax, 5
mul 4
add esp, eax

but if it was from a function:

int a[z.getlength()];

without knowing z, what could would it generate?

How would it manage code for incoming local variables?


Any ideas?

P.S. Everything is local and can't go on the .data section


Thanks in Advance
Victor Pereira






Title: Re: generating array code
Post by: redskull on October 05, 2010, 05:23:08 PM
Generally speaking, it can't.  In C, for example, array indices must be constant.  Language that allow it probably default to using the heap instead of the stack.

-r
Title: Re: generating array code
Post by: clive on October 05, 2010, 06:16:47 PM
Well typically you move ESP to EBP on entry to fix the stack frame, and access parameters and local with respect to that. Compilers that do everything relative to the stack pointer keep track of where it is, but that only works well for fixed allocations.

Your first case would be written as SUB ESP,20 (the stack grows down, and the compiler can pre-compute constants removing unnecessary run-time math), or ADD ESP,-20

For the variable case


  PUSH EBP ; Epilogue
  MOV EBP,ESP
  ADD ESP,-32 ; locals
  PUSH ESI


  MOV EAX, [EBP + 8]; length parameter or call a routine returning array size in EAX
  SHL EAX,2 ; *4
  SUB ESP,EAX ; Allocate from stack
  MOV ESI,ESP ; Fix array at ESI


  POP ESI ; Prologue
  MOV ESP,EBP
  POP EBP
  RET
Title: Re: generating array code
Post by: victorvmpm on October 06, 2010, 05:27:00 PM
Thanks for the posts!

I was thinking it last night, and I thought of a solution, however it would be too hard to implement.

I was thinking of having the array as 2 of 4 byte elements one of them the data and the other the reference to the next element. Unfortunately, that would mean that the table would be on runtime and managed on the heap. Even though is just an idea I haven't thought of how to implement it.