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?