Repository navigation
Description
The Math.Min and Math.Max functions that take double/float were updated to be IEEE compliant in dotnet/coreclr#20912. However, the JIT does not do a great job optimizing this code and it has resulted in a regression.
For example, in the Ray Tracer that Matt Warren ported to C# as part of https://mattwarren.org/2019/03/01/Is-CSharp-a-low-level-language/#using-mathf-functions-instead-of-math, I see the following locally:
- C++ 19.16: 26sec
- C# netcoreapp2.2: 36sec
- C# netcoreapp3.0: 57sec
Reverting the change back to the original implementation gives:
- C# netcoreapp3.0: 31sec
The function could likely be intrinsified in order to help with the codegen here. This can't be done using exclusively minss as that always returns the second operand if either of the operands is NaN, so we could emulate this branchlessly using the recommendation in the architecture manual:
If only one value is a NaN (SNaN or QNaN) for this instruction, the second source operand, either a NaN or a valid floating-point value, is written to the result. If instead of this behavior, it is required that the NaN in either source operand be returned, the action of MINSD can be emulated using a sequence of instructions, such as, a comparison followed by AND, ANDN and OR.
I believe that should be something similar to the following:
if (Sse.IsSupported)
{
var lhs = Vector128.CreateScalarUnsafe(val1);
var rhs = Vector128.CreateScalarUnsafe(val2);
var tmp1 = Sse.MinScalar(rhs, lhs);
var tmp2 = Sse.CompareUnorderedScalar(lhs, lhs);
if (Avx.IsSupported)
{
return Avx.BlendVariable(tmp1, rhs, tmp2).ToScalar();
}
else
{
var tmp3 = Sse.And(tmp2, rhs);
tmp2 = Sse.AndNot(tmp2, tmp1);
return Sse.Or(tmp2, tmp3).ToScalar();
}
}
Activity
tannergooding commentedon Mar 1, 2019
The above suggested fix brings the time back down to:
Will need to finish validating that it is also correct.
jkotas commentedon Mar 1, 2019
Please make sure to fix this regression on all supported platforms, not just x64.
tannergooding commentedon Mar 1, 2019
Fixing it for x86 and x64 is just the above. Fixing it for ARM/ARM64 will likely require the JIT to treat the method as intrinsic until the HWIntrinsic support actually becomes available.
The root problem is the JIT doesn't handle NaN comparisons very well, which results in a bunch of branches in a small window of code. I'll try to give some more thought on if I can also improve the software fallback case.
jkotas commentedon Mar 1, 2019
What is the implementation strategy used for this by other environments, e.g. C/C++ compilers? Does the compiler handles it, or is the
maximplementation handcrafted in library code?tannergooding commentedon Mar 1, 2019
GCC and MSVC both forward down to the CRT software implementation (
fminandfmax). Clang (when optimizations are enabled) emits some assembly similar to my prototype above.All of them have a "fast floating-point math" switch and just emit
minsswhen that is enabled.jkotas commentedon Mar 1, 2019
I think we should do the same here like we do for majority of the other Math operations. Would that fix the regression?
tannergooding commentedon Mar 1, 2019
I'll check, but I find it doubtful as the CRT implementations are roughly what we already have in the C# implementation.
From previous analysis on related functions, the cost of the two calls (one to our
COMSingle::Minand one from that tofminf) ends up being more expensive than the actual assembly being run.For reference: just aggressively inlining the current "correct" implementation cuts the time down from 57sec to 48sec, showing that the call is a significant portion of the current cost.
tannergooding commentedon Mar 1, 2019
@jkotas, Unfortunately, my suspicion was correct. Changing these to FCALL into the CRT
fminandfmaxregresses the time from57secto78sec.I'll continue looking at the software fallback case to see if I can improve it standalone as well. I expect we might be able to just emulate the
cmp, and, andnot, orsequence using bit manipulation to get a speedup.mikedn commentedon Mar 1, 2019
I can improve NaN comparisons in the JIT. Though last time I tried it didn't seem to make a difference.
mikedn commentedon Mar 1, 2019
Though it looks to me that the C++ version of the raytracer is using
and that has nothing to do with
Math.Min. And it's not uncommon for this kind of code to not care about NaN-accuracy and I don't see why the C# version would do it differently.Still, it's probably worth taking a look at what can be done to improve
Math.Min/Max, even though it will probably never matchx < y ? x : y.tannergooding commentedon Mar 2, 2019
I have a PR up which resolves this for x86/x64: dotnet/coreclr#22965. The prototype I wrote in the original post was nearly correct, but didn't handle
-0.0vs+0.0correctly; where-as the PR has the additional checks to do that.The software fallback implementation has a few problems.
First, the codegen for
IsNaNis pretty bad. This is because the implementation forIsNaNis doing a strict bit-comparison. The fix is actually fairly trivial in that we could change the implementation tobool IsNaN(float x) => x != xand the JIT correctly emits aucomissinstruction followed byjp.BitConverter.SingleToInt32Bitsalso currently goes through the stack, rather than usingmovd, which might be nice to fix as a separate issueSecond, the
IsNaNchecks are being done first; when they could be handled last since they are the uncommon case and either operand beingNaNcauses every other comparison to returnfalse.Third, the JIT treats
x < yas commutative withy >= x. This is normally great, since the IEEE spec says that-0.0and+0.0are equal, and this is the only case that could matter. However, it makes it very difficult to "efficiently" handle cases where this difference does matter; and so we end up having to do 2 separate comparisons (first the equality and then the less than comparison) to get this working correctly.mikedn commentedon Mar 2, 2019
Can you tell me what exactly are you measuring? I've been looking other that blog post but I don't see such values. And attempting to run the raytracer takes a lot longer, minutes on my machine.
tannergooding commentedon Mar 2, 2019
The execution of the entire program using the
time-windowstool listed in the blog post (which is a port of the unixtimecommand).The programs are exactly as given in the blog post, with the C++ code modified to be 2 samples (also specified in th blog post).
The times I gave above should be seconds though, not sure why I typed
ms(probably just habit, editing them now).tannergooding commentedon Mar 2, 2019
Times should be updated to be in the correct unit (seconds not ms). Sorry for the confusion.
mikedn commentedon Mar 2, 2019
Thanks. I also discovered that I was using a debug corelib and that's why it was taking minutes for me. Now I get 58s (and 33s for the C++ version, compiled with VS2019). So the results are comparable and I can play a bit with it.
First observation is that changing
mintoreturn l < r ? l : r;like in the C++ version brings down the C# time to 35s.mikedn commentedon Mar 2, 2019
This
Math.Mincomment is kind of misleading:The JIT will transform
val1 < val2intoval2 > val1pretty much always. The JIT may sometimes transformval1 < val2into!(val1 >= val2), or in the specific case ofMincode -return (val1 < val2) ? val1 : val2;intoreturn (val1 >= val2) ? val2 : val1;.mikedn commentedon Mar 2, 2019
movdsaves 2-3s, around 6%. Might worth doing it but it is not enough.x != xrather thanIsNaNdoesn't seem to make a difference performance wise but it does generate smaller codeBut the current
Mincode seems pretty bad, it doesn't take advantage of facts likex < NaN = false. I need to stare at it a bit more but the following should be equivalent and generates far less code:runs in ~47s and generates
There may be an way to eliminate one of the
vucomiss xmm0, xmm1but I don't see it right now, the negative 0 check is in the way.It's a bit large to force inline it but doing that brings the time down to 39s.
CarolEidt commentedon Apr 23, 2019
@tannergooding - is https://github.com/dotnet/corefx/issues/36925 the plan for addressing this? If so, should this be moved out from 3.0 to future (since it seems that proposal won't make it into 3.0)?
tannergooding commentedon Apr 23, 2019
This was reduced to a 3-6ms regression after https://github.com/dotnet/corefx/issues/36931 was merged.
I think this can probably be closed for now.
CarolEidt commentedon Apr 24, 2019
Thanks @tannergooding