Skip to content

Instantly share code, notes, and snippets.

@CookiePLMonster
Forked from riverar/repro.cpp
Last active September 16, 2020 13:23
Show Gist options
  • Save CookiePLMonster/3e685641546935b4db015f74b7286ea3 to your computer and use it in GitHub Desktop.
Save CookiePLMonster/3e685641546935b4db015f74b7286ea3 to your computer and use it in GitHub Desktop.
VS optimizer bug sample
#include <iostream>
#include <cmath>
// Sample of an optimizer bug in Visual Studio 2003 - 2019 (or more)
//
// Compiling this program in Release (/O1, /O2 or /Ox and LTCG) in both x86 and x64
// configurations produces a different output from unoptimized (Debug) configurations.
//
// Expected output: 709
// Produced output: 31
//
// GCC, ICC, clang-cl, as well as ideone.com output the correct value.
//
// By Adrian Zdanowicz and Rafael Rivera
int zero = 0; // Can't seem to make this a local, delete it or make const.
int main()
{
int iterations = 0, maxvis = 0, i2 = 0, qx0 = 0, ix = 0, iy = 0, q1 = 0, qx2 = 0, qy2 = 0;
qx0 = std::atoi("0");// This cannot be reduced.
// qx0 = static_cast<int>(std::floor(0)); // Or this - both fail the test.
if (zero) // Can't remove this.
i2 = 12;
else
i2 = 15;
if (i2 < 2) i2 = 2; // Nor this.
q1 = -15;
qx2 = qx0 + 15; // Can't make this a constant = 15.
qy2 = 15; // Can't remove this in favour of using qx2.
maxvis = i2;
for (iy = q1; iy <= qy2; iy++) // qy2 can be replaced with a constant 15, but not with qx2.
{
for (ix = q1; ix <= qx2; ix++)
{
i2 = iy - qx0; // Nor this.
// std::cout << i2 << std::endl; // Uncommenting this "fixes" the code.
if ((ix * ix + i2 * i2) > (maxvis * maxvis)) continue; // Can't touch this either.
iterations++;
if (iterations >= 961) break; // Can't remove this.
}
if (iterations >= 961) break; // Nor this.
}
std::cout << iterations;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment