I started using Unreal Engine at version 4.23. At the time, they supported both Visual Studio 2017 and 2019:

I thought I would go with the latest version as Microsoft keeps working to improve Visual Studio so I installed 2019. All was good for a while.

The Twist

For the most part I work in the “DebugGame Editor” configuration, so all my code is compiled in debug mode. So it was quite a surprise when one day I built “Development Editor“, which includes optimizations for the game code, and a feature that was working perfectly suddenly broke. Badly.

The code looked fine. If I added #pragma optimize("", off) around the file, it started working properly again. Now, the title may have already spoiled the ending, but I’m generally very skeptical of issues that look like compiler bugs. I know it happens and I have found some myself, but it’s much more rare than a programmer error. Often, you’re triggering the problem by using undefined behaviour.

In this case it was the compiler.

By printing the results of intermediate calculations, I could prove that after normalizing a vector, the results were garbage. Sometimes NaN, sometimes infinity, sometimes correct. In the implementation of FVector::GetSafeNormal() there is this line:

const float Scale = FMath::InvSqrt(SquareSum);
return FVector(X*Scale, Y*Scale, Z*Scale);

It turns out that FMath::InvSqrt() is an optimized SSE function which, as the comment says, “performs two passes of Newton-Raphson iteration on the hardware estimate”. You can find the source here.

That’s the function that was being wrecked by Visual Studio. As soon as I replaced it with 1.0f / FMath::Sqrt() everything started working as intended.

The Plot Thickens

The version of Visual Studio 2019 I was using was 16.3.6, from October 2019. I know, ancient.

People on Twitter were saying that there are many issues with Visual Studio 2019’s codegen. Then something else happened. I upgraded Unreal to 4.24 and was presented with this error screen:

In case it wasn’t obvious, the 14.23 toolchain corresponds to Visual Studio 2019 16.3. Ouch. This is the link: https://developercommunity.visualstudio.com/content/problem/734585/msvc-142328019-compilation-bug.html

It claims to be fixed in 16.4. I was curious so I installed the latest (16.5.3) and lo and behold, the problem was indeed fixed.

But we’re not done yet:

Everything Old Is New Again

So everything points to going back to Visual Studio 2017. Oh well. How do we do that?

It’s actually quite simple. First, we need to tell Unreal to use 2017, in Editor Preferences:

Then we regenerate the Visual Studio project, by right-clicking on the .uproject file:

And we’re ready. Don’t forget to set your environment properly, as described in my C++ post.

Now I’m running Visual Studio 2017 15.9.21. So far, so good.