[Info-vax] Volatile, was: Re: yet another sys$qiow question

Johnny Billquist bqt at softjar.se
Wed Aug 19 11:18:57 EDT 2015


On 2015-08-19 15:31, Simon Clubley wrote:
> On 2015-08-19, Johnny Billquist <bqt at softjar.se> wrote:
>> On 2015-08-19 14:36, Jan-Erik Soderholm wrote:
>>
>>> Now in the embedded world we might have:
>>>
>>> loop [some condition]
>>>     VarB = PORTA
>>> endloop
>>>
>>> where PORTA is a hardware port (I/O pins) on the processor.
>>>
>>> If PORTA is not volatile, the compiler can do a single read
>>> of PORTA and then use a value saved in a processor register.
>>> With volatile, the hardware I/O port will be read each time.
>>>
>>> The "value" of PORTA can of course change at any time depending
>>> on what happens in the hardware around the processor.
>>
>> Right. Except that it would also move the assignment out of the loop if
>> it wasn't volatile, as there is no point in repeating a constant assignment.
>>
>
> Do you mean if VarB wasn't volatile and if [some condition] didn't
> reference a volatile variable ?

It would move the assignment out of the loop unless VarB or PORTA is 
marked as volatile.
The reference to any volatile variables in the condition do not change 
this. Volatile variables in the conditional expression will change how 
the loop itself is compiled, but it will still move the assignment 
outside, as without volatile, it is totally unrelated to the loop.

> Don't forget that reads from a device can have side effects as well
> so the above loop might be required as a loop.

Yes. But the assignment is an invariant unless you declare at least some 
part of it volatile. And as an invariant, it can just as well be outside 
the loop, as the end result is the same. And so, an aggressive compiler 
*will* move it outside. No point in doing duplicate work that do not 
change anything.

> I'm not sure if gcc would ever move the assignment out of the loop
> because of this as I thought the rule was that the compiler must
> generate code to do a volatile read or write exactly the same number
> of times as it is indicated within the source code.

If either of the variables are volatile, then the assignment needs to 
stay in the loop. If neither is, a compiler is free to move it outside.

	Johnny




More information about the Info-vax mailing list