[DUG] Delphi Calling Convetion is Weird!!

Stacey Verner stacey at cjntech.co.nz
Fri Feb 16 14:22:38 NZDT 2007


Hi Stacey,

	----- Original Message ----- 

	From: Stacey Verner <mailto:stacey at cjntech.co.nz>  

	To: NZ Borland Developers Group - Delphi List
<mailto:delphi at ns3.123.co.nz>  

	Sent: Friday, February 16, 2007 11:34 AM

	Subject: [DUG] Delphi Calling Convetion is Weird!!

	 

	After an odd bug and a bit of testing I have found that the
parameters in Delphi (tested 6 and 2006) are evaluated very strangely.

	 

	The 3rd parameter is evaluated first followed by 4, 5, 6 etc and
then the 2nd and then the 1st.

Always this order? Or does it vary sometimes if there are a different
number of parameters? or if the mix of parameters varies, ie between
static values, in-line expressions, function invocations?

 

Yep. Always this order. I just tried it with 2, 3, 4, 5, 6, 7, 8 and 9
parameters and the results were as follows:

 

2 parameters: 2, 1

3 parameters: 3, 2, 1

4 parameters: 3, 4, 2, 1

5 parameters: 3, 4, 5, 2, 1

6 parameters: 3, 4, 5, 6, 2, 1

7 parameters: 3, 4, 5, 6, 7, 2, 1

8 parameters: 3, 4, 5, 6, 7, 8, 2, 1

9 parameters: 3, 4, 5, 6, 7, 8, 9, 2, 1

 

	 

	This appears to be because the default calling convention is
register which (from the documentation) puts up to 3 parameters in
registers and the rest on the stack. It seems to process the stack ones
first from parameters 3 onwards (Why 3? Shouldn't it be 4 if we are
putting 3 into registers. Must be only putting 2 in the registers), and
then the first 2 in reverse order into the registers. 

It may be that the two registers it uses for parameters 1 and 2 are also
used in calculating parameter addresses in any call; or used in
evaluating expressions in parameters; if so, parameters 1 and 2 can't be
set into the registers until all the rest of the parameters have been
evaluated. Also, registers containing parameters of the main function
can't be set before calling any functions in the parameters, if they
will be used for parameters of those functions.

	The documentation also says that is supposed to pass the from
left to right, but it obviously doesn't.

Do you mean the order in which parameter expressions are evaluated? Yes,
if that's defined, the compiler should respect it. Or the documentation
should be changed to included a caveat about the possible results of the
compiler's optimisation.

 

You'd be safest to call your functions and save their results in
temporary variables which you then pass to the main function. That way
you can control the order of the side effects yourself and it'll work
whatever the compiler does.

 

Yes. Using temporary variables are the best bet, and it's usually
clearer anyway.

  

Brian

 

Stacey

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://ns3.123.co.nz/pipermail/delphi/attachments/20070216/68208247/attachment.html


More information about the Delphi mailing list