Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign volatile to non-volatile sematics and the C standard

volatile int vfoo = 0;
void func()
{
    int bar;
    do
    {
        bar = vfoo;  // L.7
    }while(bar!=1);
    return;
}

This code busy-waits for the variable to turn to 1. If on first pass vfoo is not set to 1, will I get stuck inside.

This code compiles without warning. What does the standard say about this?

  • vfoo is declared as volatile. Therefore, read to this variable should not be optimized.
  • However, bar is not volatile qualified. Is the compiler allowed to optimize the write to this bar? .i.e. the compiler would do a read access to vfoo, and is allowed to discard this value and not assign it to bar (at L.7).
  • If this is a special case where the standard has something to say, can you please include the clause and interpret the standard's lawyer talk?
like image 262
aiao Avatar asked Mar 03 '23 04:03

aiao


2 Answers

What the standard has to say about this includes:

5.1.2.3 Program execution

¶2 Accessing a volatile object, modifying an object, modifying a file, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment. Evaluation of an expression in general includes both value computations and initiation of side effects. Value computation for an lvalue expression includes determining the identity of the designated object.

¶4 In the abstract machine, all expressions are evaluated as specified by the semantics. An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by calling a function or accessing a volatile object).

¶6 The least requirements on a conforming implementation are:

  • Accesses to volatile objects are evaluated strictly according to the rules of the abstract machine.
  • ...

The takeaway from ¶2 in particular should be that accessing a volatile object is no different from something like calling printf - it can't be elided because it has a side effect. Imagine your program with bar = vfoo; replaced by bar = printf("hello\n");

like image 177
R.. GitHub STOP HELPING ICE Avatar answered Mar 15 '23 05:03

R.. GitHub STOP HELPING ICE


volatile variable has to be read on any access. In your code snippet that read cannot be optimized out. The compiler knows that bar might be affected by the side effect. So the condition will be checked correctly.

https://godbolt.org/z/nFd9BB

like image 36
0___________ Avatar answered Mar 15 '23 07:03

0___________