Volatile is discarded in the frontend during a cast to a reference to a volatile type
Loads and stores of references to volatile variables aren't reflected in the generated IR as being as volatile. None of const_cast<volatile int&>(x), static_cast<volatile int&>(x), or (volatile int&)(x) are properly reflected. If I'm understanding correctly, f0 here should be generating six add instructions and the InstCombine should not be allowed
void f0() {
const_cast<volatile int&>(x) = const_cast<volatile int&>(x) + 1;
const_cast<volatile int&>(x) = const_cast<volatile int&>(x) + 1;
static_cast<volatile int&>(x) = static_cast<volatile int&>(x) + 1;
static_cast<volatile int&>(x) = static_cast<volatile int&>(x) + 1;
(volatile int&)x = (volatile int&)(x) + 1;
(volatile int&)x = (volatile int&)(x) + 1;
}
f0(): # @f0()
add dword ptr [rip + x], 6
ret
Volatile is respected if it's in the context of a pointer or a reference variable is created.
https://godbolt.org/z/hE6xxP8To
GCC and MSVC do not fold the increments in f0: https://godbolt.org/z/hEPe66cjT.
@llvm/issue-subscribers-clang-codegen
Smaller repro where a write is removed in EarlyCSEPass: https://godbolt.org/z/Y9rz64vbr
void asdf(int &x)
{
static_cast<volatile int &>(x) = 1;
static_cast<volatile int &>(x) = 2;
}
asdf(int&): # @asdf(int&)
mov dword ptr [rdi], 2
ret
I think EarlyCSEPass is behaving correctly, clang should be generating store volatiles (which EarlyCSEPass would not remove). (Issue should probably be updated to have a clang frontend label).
(Ps I'm the author of the llvm opt pass view tool on compiler explorer and I'm thrilled to see it being used in bug reports already, especially my own bugs!)
has anyone started working on this??
Review :https://reviews.llvm.org/D157890