[cfe-users] unsequenced modification and access

Javier Múgica javier_3 at runbox.com
Tue Jun 16 09:43:58 PDT 2015


I have an answer for my own question. NO, the compiler does not necessarily push the ++ to the end of the instruction. This code, compiled with -O1 (I have not tested -O0) provides a counterexample:

while(p!=top) *p++=*(p+k);

when it comes to evaluating the instruction, p is in ecx. The compiler moves it to eax, then increments ecx, then stores the value of ecx in p, then acquires the just stored value again in ecx (which obviously does nothing), then increments ecx by k, then takes the contents of ecx into eax, effectively doing:

eax=p;
p++;
ecx=p+k;
*eax=*ecx;

Regards

On Thu, 11 Jun 2015 10:50:48 +0200 (CEST), "Javier Múgica" <javier_3 at runbox.com> wrote:

> I get the warning Wunsequenced if I write code like
> 
> for(k=n;k;) k--, aux+=*p**p++;
> 
> or
> 
> for(i=n;i--;) *x++=*(x+1);
> 
> 
> Clang behabour here is right. The access to *p or *x, to the one without the ++, is unsequenced with respect to the increment of the pointer indicated by the other p++ or x++. This means that it is undefined which may take place before. But I suppose that the compiler (any compiler) will just push the ++ after the whole instruction, thereby achieving the programmer's desired effect. May I rely on that?
> 
> The first example is of a kind I use often in some innermost loops that need to be optimized. I *suppose* that the right change in order to get pedantic-good code and not decreasing the performance of the emitted code is
> 
> for(k=n;k;){k--; Double auxb=*p++; aux+=auxb*auxb;}
> 
> for the compiler will optimize away the variable auxb when optimizing. I preferred this solutions instead of
> 
> for(k=n;k;){k--; Double aux+=*p**p; p++;}
> 
> But maybe nowadays compilers are clever enough when optimizing, and in particular llvm, that the three different codings would compile to the same, and there is no need to worry about helping the compiler that much.
> 
> Regards






More information about the cfe-users mailing list