Yes, it’s a bug. Specifically, it’s a bug in the new SSA optimizer introduced in VS2015 Update 3. The undocumented command line option -d2SSAOptimizer- tells the compiler backend to use the old optimizer instead, which causes the bug to not manifest.
FYI, you can minimize your repro to:
int main()
{
volatile int someVar = 1;
const int indexOffset = someVar ? 0 : 1;
for (int i = 1 - indexOffset; i < 2 - indexOffset; ++i)
{
return 0;
}
return 1;
}
which will help the compiler developers localize the problem more quickly.
Addition from Codeguard (I decided that Casey‘s answer should be THE answer):
I have received reply from Microsoft (Gratian Lup, author of blog post Introducing a new, advanced Visual C++ code optimizer):
Yes, this is indeed a bug in the SSA Optimizer itself – usually most
bugs reported as being in the new optimizer are in other parts,
sometimes exposed now after 20 years.It’s in a small opt. that tries to remove a comparison looking like (a
– Const1) CMP (a – Const2), if there is no overflow. The issue is that your code has (1 – indexOffset) CMP (2 – indexOffset) and subtraction
is not commutative, of course – but the optimizer code disregards that
and handles (1 – indexOffset) as if it’s (indexOffset – 1).A fix for this issue will be released in the next larger update for
VS2017. Until then, disabling the SSA Optimizer would be a decent
workaround. Disabling optimizations for only this function may be a
better approach if it doesn’t slow down things too much. This can be
done with #pragma optimize(“”, off):
https://msdn.microsoft.com/en-us/library/chh3fb0k.aspx