"a[++i] = i" vs "a[i] = ++i"

Timon Gehr timon.gehr at gmx.ch
Tue Dec 24 13:49:35 PST 2013


On 12/24/2013 06:46 PM, H. S. Teoh wrote:
> ...
>
> What is "strict left to right evaluation", since * has to be evaluated
> before +? Or you consider all side-effects to be evaluated first (from
> left to right), and then the expression?
>

It is about the order operands are evaluated in.

Eg. if you have a binary expression, first evaluate the left operand and 
then the right operand (and finally compute the result).

>...
>
> A potential issue is that forcing a particular evaluation order may be
> detrimental to the optimizer, e.g., according to strict left-to-right
> evaluation (if I understand you correctly), then to evaluate this:
>
> 	z = (y = ++x) + ((++y)--) * (x=y)
>
> you'd have to compile it into the equivalent of:
>
> 	y = ++x;	// i.e., ++x; y = x;
> 	tmp1 = y;
> 	tmp2 = ++y;	// i.e., ++y; tmp2 = y;
> 	y--;
> 	x=y;
> 	z = tmp1 + tmp2 * x; // i.e., tmp3 = tmp2*x; tmp3 += tmp1; z = tmp3;
>
> Since the order can't be permuted without changing the semantics, the
> codegen would have to load x and y multiple times as well as introduce
> temporaries in order to evaluate the final expression, and the optimizer
> wouldn't be able to do anything about it.
>...

Yes, but in this case we wouldn't want the optimizer to do anything 
other than this. The case where unspecified order helps is when the 
optimizer cannot prove that two evaluation orders yield the same result 
(even though it is the case), in which case it can freely choose the 
more performant of the two. I don't think this is the right trade-off for D.

> Of course, this is probably not *that* big of a deal if normal
> expressions without side-effects can be optimized as usual -- it'd be
> the user's own fault for writing unoptimizable code. Code with
> side-effects are already difficult to optimize anyway, so it probably
> doesn't make that big of a difference.
>
>
> T
>



More information about the Digitalmars-d-learn mailing list