Preventing the optimizer from optimizing a variable away in visual studio
c++, c++11, visual-c++, visual-studio, visual-studio-2013
Solution
I know it's very late for answering this but I'm having a similar problem. My constellation is VSCode + CMake + MSVC, and I've done some researching and found the following Visual Studio article: https://developercommunity.visualstudio.com/t/compiler-optimizes-out-some-variables-in-release-b/276808
If you are concerned that the compiler is optimizing in the root of a benchmark, there are two general approaches which I find effective: 1. Strategic use of volatile variables to prevent the above optimizations from kicking in. 2. Disable optimizations around the "main" function with #pragma optimize("", off) / #pragma optimize("", on). I prefer option 2, where I find the intent more clear.
I tested the option with #pragma optimize("", on / off) around the main function and it actually works.
The other option is of course disable optimization entirely with /Od tag for compiler. (https://learn.microsoft.com/en-us/cpp/build/reference/od-disable-debug?view=msvc-170)
Problem
Sometimes when writing benchmarks I have found it useful to use an "opaque" function which prevents the optimizer from completely removing a variable. On gcc and clang I have an implementation using inline assembly which seems to work as I want in all cases I have tested so far. Here is a simple example of what I am interested in (example on godbolt): ``` template<class T> void opaque(T&& t) { asm volatile("" : "+r" (t)); } int test(int a) { return a + 5; } int main() { int a = 10; opaque(a); return test(a); } ``` The above code generates the following assembly: ``` movl $10, %eax addl $5, %eax ret ``` whereas, without the opaque function it generates: ``` movl $15, %eax ret ``` How would I write an equivalent to the opaque function for the visual studio compiler (specifically 2013)?