1
votes

My understanding is that the C++ standard mandates that accesses to volatile objects are evaluated strictly according to the rules of the abstract machine. I am sure that means that the number of loads and stores to a given volatile variable cannot be changed, nor can those accesses be reordered.

But what about reordering with respect to other non-volatile access?

Can a fully redundant volatile access in both arms of an if statement be hoisted or sunk out of that if? E.g. Assuming no data dependencies would be violated can

if (e) {
    = non-volatile-load;
    non-volatile-store =;
    t = volatile-load;
    = non-volatile-load;
    non-volatile-store =;
} else {
    = non-volatile-load;
    non-volatile-store =;
    t = volatile-load;
    = non-volatile-load;
    non-volatile-store =;
}

be optimized to

t = volatile-load;
if (e) {
    = non-volatile-load;
    non-volatile-store =;
    = non-volatile-load;
    non-volatile-store =;
} else {
    = non-volatile-load;
    non-volatile-store =;
    = non-volatile-load;
    non-volatile-store =;
}

or to

if (e) {
    = non-volatile-load;
    non-volatile-store =;
    = non-volatile-load;
    non-volatile-store =;
} else {
    = non-volatile-load;
    non-volatile-store =;
    = non-volatile-load;
    non-volatile-store =;
}
t = volatile-load;

What if the volatile-load were instead a volatile-store?

1
A non-volatile variable could be held in a register for its entire lifetime, and never be stored in memory. - Bo Persson
If these "non-volatile" things (and also that "t") do not cause any side effects in undisclosed parts of code then by as-is rule the program can be optimized into just "volatile-load". If these cause then it matters what these cause. - Öö Tiib
volatile is not the tool to reason about load-store ordering. You need atomic, mutex or some other way to achieve acquire/release semantics. - rustyx
@rustyx i think, you are confused. load/store is a quite generic term, and by no means is confined to thread synchronization domain. - SergeyA
Consider the case where a volatile variable represents a hardware register or a shared memory location (among threads). Do your cases still hold? - Thomas Matthews

1 Answers

1
votes

Under the as-if rule,...

... conforming implementations ... are required to emulate (only) the observable behavior of the abstract machine as explained below

And observable behavior is specified below as (emphasis mine)...

– Accesses through volatile glvalues are evaluated strictly according to the rules of the abstract machine.

So yes, the compiler may reorder accesses to non-volatile variables (of course within the boundaries of memory fences in a threaded environment; volatile offers no such semantics, atomic does).