This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Possible missed optimization opportunity with const?


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().



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]