Fw: Possible missed optimization opportunity with const?

David Brown david@westcontrol.com
Thu Sep 1 09:38:00 GMT 2016


On 01/09/16 05:08, Toshi Morita wrote:
> 
> 
> Florian Weimer wrote:
> 
>>> On 08/31/2016 10:57 AM, Toshi Morita wrote:
>>> 
>>> However, if the definition of pfoo is changed to: const int *
>>> const pfoo = (const int * const 0x1234); the optimization seems
>>> to fail:
>> 
>> The optimization is not valid in this case because the compiler
>> cannot know that the object was declared const. It could well be
>> mutable.
> 
> Sorry, that should be:
> 
> const int * const pfoo = (const int * const)0x1234;
> 
> So assuming this is still wrong, what is the correct way to define a
> pointer to a hardware register at 0x1234 which contains immutable
> data? I'm missing something here.
> 
> Toshi
> 

If it is a hardware register, you normally want to put a "volatile"
there so that you get exactly the number of reads you want.  And if you
only want to read it once, then read it only once.  Sometimes it is
easier to write things in clear and simple code, rather than hoping the
compiler will optimise the unnecessary source code.

It would be nice if there was a good way to tell the compiler that a
particular object exists at a particular address.  Expressions like the
one you gave, or placement new, give the compiler a reference or pointer
to such an object, but you can't define characteristics of the object
(such as telling the compiler that the object itself is const).

The AVR port of gcc lets you write:

const int foo __attribute__((address(0x1234)));

Maybe it would be possible to make this a common __attribute__ in gcc?

(As an embedded programmer who works with gcc on a number of different
targets, it is always annoying to see a useful attribute, builtin, or
extension on one port but not have it available on the other ports!)



More information about the Gcc-help mailing list