google / benchmark

A microbenchmark support library
Apache License 2.0
8.98k stars 1.62k forks source link

[BUG] DoNotOptimize() doesn't prevent gcc/clang from optimizing out array lookup #1432

Open gizlu opened 2 years ago

gizlu commented 2 years ago

Describe the bug DoNotOptimize() doesn't prevent gcc from optimizing out array lookup.

System

To reproduce See assembly produced for this: https://godbolt.org/z/ahPss8hvY On clang -O2 everything is ok - addition and mov from LUT array On gcc -O2 - mov is missing

Expected behavior DoNotOptimize() should prevent gcc from optimizing out array lookup

Edit: example minimisation

gizlu commented 2 years ago

Update: Removing const specifier from array definition triggers this bug also on clang. See https://godbolt.org/z/fETxqYaqn

HFTrader commented 1 year ago

Just a note.

There are special cases for GCC but even applying the same rules for clang, it still optimizes away.

https://godbolt.org/z/KTW4sf6P9

HFTrader commented 1 year ago

It looks like just doing something with the passed variable prevents GCC from optimizing it. GCC seems to sense that the generated assembly is empty.

https://godbolt.org/z/esd8hE6T9

This works:

template <class Tp>
inline BENCHMARK_ALWAYS_INLINE void DNO(Tp const& value) {
  asm volatile("xor %0, %0" : : "r,m"(value) : "memory");
}