Strange clang unused-but-set-variable error with volatile variables

In Linux kernel development, sometimes we use operations with volatile variables to burn cpu cycles for testing purpose. For example,

$ cat test.c
void test() {
        volatile int j = 0;
        for (int i = 0; i < 100000000; i++)
                j++;
        return;
}
$ clang -g -Wall -Werror -S -emit-llvm test.c
$

The clang is built with latest llvm-project source. For the above example, looking at test.ll file, the IR looks correct with proper load/stores related to volatile variables.

But a slight variation of the above code caused a compilation error.

$ cat test.c
void test() {
        volatile int j = 0;
        for (int i = 0; i < 100000000; i++)
                j+=1;
        return;
}
$ clang -g -Wall -Werror -S -emit-llvm test.c
test.c:2:15: error: variable 'j' set but not used [-Werror,-Wunused-but-set-variable]
        volatile int j = 0;
                     ^
1 error generated.
$

Can somebody help explain why the second example (with j+=1) cuased the compiler warning?
Currently we assume volatile variable, if involved with some operations, will never be optimized away, is this assumption true?

The code will work the way you expect. The warning is just that the construct looks suspicious. Maybe we should disable the warning for volatile variables.

@efriedma-quic Sounds a good idea to disable the warning for volatile variables. I am wondering what caused the second code sample failed but not the first one.

1 Like