[prev in list] [next in list] [prev in thread] [next in thread] 

List:       gcc
Subject:    Re: Possible missed optimization opportunity with const?
From:       David Brown <david.brown () hesbynett ! no>
Date:       2016-08-18 13:04:19
Message-ID: 57B5B253.5070708 () hesbynett ! no
[Download RAW message or body]

On 18/08/16 00:44, Toshi Morita wrote:
> David Brown <david.brown@hesbynett.no> wrote:
> 
>> No, it would not be valid.  Declaring pfoo as a "const int*" tells the
>> compiler "I will not change anything via this pointer - and you can
>> optimise based on that promise".  It does /not/ tell the compiler "the
>> thing that this points to will not change".
>>
>> So the compiler is correct in reading *pfoo twice.
> 
> The revised example posted by Kei uses "const int const *pfoo" and GCC
> is able to remove the second read, so this interpretation of const seems
> incorrect?
> 
> Toshi
> 

I didn't see the post you are referring to - was it sent to the mailing
list, or only your email address?

But if I can make a guess here, the difference here is that now the
pointer object "pfoo" itself is const, and therefore cannot be modified
(without causing undefined behaviour).  So the compiler knows that it
will definitely point to "foo", and can use that information to optimise
better.

When "pfoo" was not "const", the compiler does not know that pfoo points
to foo in main - it could point somewhere else.  (In particular, a
file-scope constructor in another module might change it, since pfoo has
external linkage.)  Thus it does not know if bar() changes *pfoo, and it
has to read *pfoo twice.  You would get the same effect by making pfoo
"static", since the compiler then knows that it's value is &foo at the
start of main().


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic