Compilers are expected to make
volatiles immune to optimizations that result in incorrect access to the volatile variables e.g. reducing the load/stores, re-ordering them, and etc.
A
recent study on volatiles identified a few bugs with
GCC 4.3.0 and
LLVM-GCC 2.2. We put our compiler to test and found none of the three bugs identified in this paper applies.
Not bad!The first test case loads a volatile variable in the loop. Although invariant, we expect the compiler to leave x in the loop. The generated pseudo assembly code at O2 and O3 confirm this.
Here is the source code:
const volatile int x;volatile int y;void foo(void) {
for(y=0; y>10; y++) {
int z=x; }
}
The assembly listing of the source code above at O3, below, shows the load of x in each iteration of the unrolled loop:
@1L3 DS 0H
L r0,x(r15,r1,0)
L r0,y(r14,r1,0)
AHI r0,H'1'
ST r0,y(r14,r1,0)
L r0,y(r14,r1,0)
CHI r0,H'10'
BNH @1L5
L r0,x(r15,r1,0)
L r0,y(r14,r1,0)
AHI r0,H'1'
ST r0,y(r14,r1,0)
L r0,y(r14,r1,0)
CHI r0,H'10'
BNH @1L5
L r0,x(r15,r1,0)
L r0,y(r14,r1,0)
AHI r0,H'1'
ST r0,y(r14,r1,0)
L r0,y(r14,r1,0)
CHI r0,H'10'
BNH @1L5
L r0,x(r15,r1,0)
L r0,y(r14,r1,0)
AHI r0,H'1'
ST r0,y(r14,r1,0)
L r0,y(r14,r1,0)
CHI r0,H'10'
BH @1L3
The second test accesses a volatile variable on the fall through path of a condition.
Source is:
extern in qux();volatile int w;int bar(void) {
if(qux()) return 0; else return w; }
In the pseudo listing, below, w is correctly accessed when qux() returns zero. This listing generated at O3 is:
L r15,=V(qux)(,r3,66)
L r2,_CEECAA_(,r12,500)
BASR r14,r15
LTR r15,r15
L r1,=Q(w)(,r3,70)
BE @1L1
LA r15,0
B @1L3
@1L1 DS 0H
L r15,w(r1,r2,0)
@1L3 DS 0H
In the last source code a volatile variable is incremented inside the loop.
volatile int a;void baz(void) {
int i; for(i=0; i<3; i++){
a += 7; }
}
We unroll and the loop by three and access "a" three times. The listing of compile at O3 looks like below.
L r0,a(r14,r1,0)
AHI r0,H'7'
ST r0,a(r14,r1,0)
L r0,a(r14,r1,0)
AHI r0,H'7'
ST r0,a(r14,r1,0)
L r0,a(r14,r1,0)
AHI r0,H'7'
ST r0,a(r14,r1,0)