r/cpp • • 22d ago

Pretty nasty MSVC 19.51 hash of float bug

Hash of 0.0 and -0.0 are not the same, as the condition:

_Keyval == 0.0F ? 0.0F : _Keyval

is optimized away if you compile with:

/arch:AVX2 /O2

https://godbolt.org/z/45WPzceYx

If you use Visual Studio 2022 it works fine. I'm somewhat surprised they don't have regression tests since the standard library explicitly handles this case.

So I guess, check you hash maps if you update.

62 Upvotes

73 comments sorted by

•

u/STL MSVC STL Dev 21d ago edited 21d ago

After investigating, I believe this has already been fixed. (I will use my mod powers to sticky this comment.)

The original test case, and my reduced test case, passes with -std:c++20 /arch:AVX2 /O2 when compiled with the latest MSVC Compiler Preview 19.53.36919. (A frontend dev also confirmed that it passes with 19.52.37030.) I believe that this was fixed by internal MSVC-PR-757910 "[BE] Preserve signed zero in EQ/NE select fold under fp:precise/fp:strict" on 2026-07-14, which according to our records first shipped in the MSVC Compiler Preview 19.52.36615.0. The 19.52 Compiler (aka 14.52 Build Tools) will have its General Availability production release very soon, as it is already a Release Candidate and "Version 14.52 is expected to go stable in November and will ship with the 18.12 release of Visual Studio (Stable Channel)."

This PR fixed public bug report DevCom-11119601 "ARM64 misoptimizes +0.0 vs. -0.0." The bug report claimed that this was specific to ARM64 in the 19.51 Compiler, and the internal PR also said "ARM64-only (x64 keeps this as branches, so the OPQUESTION simplifier never sees it)". But I believe that this also fixed the x64 /arch:AVX2 scenario, and both the MSFT dev who reported the bug and the backend dev who fixed the bug didn't realize it also affected x64 when /arch:AVX2 is used (as that is not a default flag). The fix was in the backend's internal source file ssa_optimizer_question.cpp (SSA = "Static Single Assignment", a popular optimization technique throughout the industry, and "question" means the conditional/ternary operator). I know a few things about compiler internals and remembered that the backend has special switches to disable certain optimizations. I was able to confirm that both the original repro and my reduced repro on Compiler Explorer (see https://godbolt.org/z/5M8KGEc5v ) pass when the undocumented and unsupported option to disable SSA optimization of question-operators is passed, -std:c++20 /arch:AVX2 /O2 /d2ssa-patterns-quest- . That convincingly proves to me that this MSVC-PR actually fixed both the ARM64 and x64 repros.

→ More replies (1)

34

u/manni66 22d ago edited 22d ago

Is this a bug? Or does it fix a bug?

Edit: it is a bug.

If k1 == k2 is true, h(k1) == h(k2) is also true.

https://en.cppreference.com/cpp/utility/hash

7

u/R3DKn16h7 22d ago

yeah :)

what is weird is that the standard library implementation has a specific case to handle this, but it must be getting optimized away

18

u/STL MSVC STL Dev 21d ago

Yeah, that library logic is almost 2 decades old at this point. (I don't remember whether I personally added it, adjusted something Dinkumware already had, or just reviewed a Dinkumware change, but that was how I learned about negative zero and the unordered containers' requirements around element equivalence and hash equality.)

I'll go get the compiler backend team to fix this.

7

u/abstractsyntaxtea MSVC ASan Dev 21d ago

beat me to it :-)

9

u/againey 22d ago

Visual Studio versions can get confusing. VS2022 appears to be versions 19.30 through 19.44, so 19.51 should be more recent, VS2026 it seems, making this a bug, not a fix.

2

u/Depixelate_me 20d ago

They are not confusing: the objective is to force users to purchase vs2026 if they wish to have the production ready :c++23 option. Vs2022 will be forever stuck with the ABI unstable c++23preview.

This despite their bogus claim of decoupling compiler from IDE.

29

u/HommeMusical 22d ago

This is certainly a bug, but hashing floats is very often a bad idea, for exactly the same reason that comparing floats for equality is a bad idea: two numbers that only differ in the 53rd bit, the least significant bit, would hash to totally different.

Given you have a minus zero, it has to be that you are doing floating calculations, so comparing for equality at the end seems fraught with risks.

Why are you doing this?

11

u/AxeLond 22d ago

If only compilers wouldn't need to deal with scenarios which are often a bad idea to do in the first place.

6

u/HommeMusical 21d ago

It totally needs fixing. But I feel that OP is riding for a fall.

-4

u/R3DKn16h7 22d ago

well I think uses of hash maps with floating point as keys is somewhat reasonable

9

u/hippotango 22d ago

I tend to agree with /u/HommeMusical. I suppose it depends on your use case, but I would treat this as a code smell. It would seem like it could be very difficult to determine correctness if the production of keys involves computation in any way.

2

u/R3DKn16h7 22d ago

what if i just want to cache stuff. I'm not saying one should use floats as keys. but also not that one should not use them. that's not my point, to be honest.

5

u/HommeMusical 21d ago

what if i just want to cache stuff.

Why would that stuff be cached by a float key?

4

u/no_overplay_no_fun 21d ago

Let's say I want to cache a function that takes a double and returns an array of doubles. Which key would you use? Would you use a binary tree instead of a hash table?

1

u/TheSkiGeek 21d ago

There are similar concerns that your cache might contain different values for, say, “0.3”, “0.2 + 0.1”, and “0.4 - 0.1”.

2

u/bwmat 18d ago

Given those are distinct double values, that doesn't necessarily seem like a bad thing

19

u/Apprehensive-Draw409 22d ago

It's not. Take something simple like 0.3. how confident can you be that your code base will always get the same float when it tries to represent it? There's a float representation just above and one just below it. But not exact 0.3.

How certain are you that 0.4-0.1 will give the same value as 0.2+0.1? Even if you convince yourself, how certain are you that the code of the next developer on this codebase will also fall on the same value?

If you need to hash floats, you probably want fixed point or encoded decimals.

15

u/interlockedxor 21d ago

Hash maps with floating point keys are reasonable in many circumstances. For example, suppose you write a compiler and you need to store float literals in a data-section of the linked executable, so you use hashing to disambiguate float literals encountered in the source.

It's obviously "niche", but I hate blanket/absolute statements which spread fear but not actual understanding. Aside from the example above, I've needed to hash floats for a variety of reasons in various projects related to compression, rendering, and more.

8

u/HommeMusical 22d ago edited 21d ago

Absolutely not. This is why many, perhaps most, languages prohibit this. Certainly Python and JS do.

Why don't you explain what you're doing? Conceivably there might be a use case, but given you aren't telling us why you're doing this weird thing, I continue to be skeptical.

EDIT: OOPS, I was wrong about Python! Thanks for the correction. Now I'm not sure about JS either.

EDIT 2: It's an interesting hash that seems to preserves proximity:

>>> hash(1.200000000000000)
461168601842738689
>>> hash(1.2000000000000001) - hash(1.200000000000000)
512

My guess it's just the bit pattern of the float, "reinterpret_cast" to an int.

9

u/no_overplay_no_fun 22d ago

FYI my python Python 3.14.4 (main, Aug 20 2026, 10:41:58) [GCC 15.2.0] does not prohibit this.

I would say that a natural usecase would be to use a hash map to cache results of function calls and provide them when the function is called again with the same inputs. At least this is why I have done this a few times. And python's cache decorator has no problem doing this as well.

2

u/HommeMusical 22d ago

Ooops, fixed!

5

u/StaticCoder 21d ago

JS doesn't even have integers, so forbidding floats as hash keys would be quite surprising.

5

u/HommeMusical 21d ago

Dictionaries in JS can only have string keys, but then JS coerces everything into a string when you try to hash it.

8

u/StaticCoder 21d ago

Lovely! I still can't believe node.js exists

4

u/HommeMusical 21d ago

Agree 100%.

In the last few weeks, I've talked to someone who argued that PHP was the best language ("and you never worked in ERP, so what do you know about software?" - I had to look up what ERP it was), and someone else who claimed that COBOL was more important than ever.

At least the second person was very nice, and it was very interesting to hear what it was like to write COBOL in the twenty-first century, but in both cases, almost all the advances of the last thirty years in programming had completely passed them by. COBOL was already considered to on its way out when I went to university in the early 80s.

(Make no mistake - JS and node, miserable as they are, are far better than PHP.)

3

u/TSP-FriendlyFire 21d ago

To be fair, claiming that COBOL is more important than ever isn't necessarily the same thing as claiming it's the best language. COBOL is unfortunately still very much in use in a lot of glacial industries like the finance sector, so it'll remain an important language, if niche, for as long as those industries aren't forced by some external force to upgrade away from it.

I fully expect our banking systems to still run on COBOL even after we've invented FTL travel, colonized the stars, and solved aging.

2

u/HommeMusical 21d ago

Oh, I know there are still legacy banking systems that use it, but I don't see the evidence that it's "more important than ever".

When I first encountered COBOL, around 1980, multiple smart people gave me the advice that it was necessary to learn COBOL because so many jobs required it. I did not.

No one would give that advice now.

Since then in the programming world, we've had digital audio, digital video, the Internet, smart phone, 99% of video gaming (I was playing Space Invaders at the time, but there was so little of it), AI, free video conferencing and phone calls. COBOL has been involved in zero of this.

Another way to see this is that in 1980, ~~5% of the CPU power of the world was running COBOL. (This number is pulled from my posterior, though I tried to search it, but it's based on my personal experience.)

Now, with more microprocessors than people, my guess is that less than 0.00001% of CPU processing is running COBOL. (There are 7 billion smart phones, basically none of which ever run COBOL.)


Also, now we have LLMs, I expect a lot of those COBOL systems to finally disappear over the next decade.


Have an upvote for being polite, and also, because I'm happy reading the news this morning.

4

u/bwmat 18d ago

There's a Map type that can use anything as a key

2

u/sol_runner 22d ago

Not really.

If you're making a hashmap you probably want to retrieve based on "proximity" instead of exact values.

If your floats are in a range, you can normalize them to integers. If they're unbounded but you only need up to around 2,000,000 and only precision of 0.001 then you can create a fixed representation.

Alternatively a different quantization that's fit for your use. Floats without any type of bucketing is like equivalence checking. Which is a bug source.

-1

u/no_overplay_no_fun 22d ago

I think that if you have the range and normalize them to ints you are essentially doing a work of a hash function on floats anyway. At least from the point of view of the hash table. What would be the gain in such case?

4

u/sol_runner 21d ago edited 21d ago

"A hash function on floats" needs to be defined here.

std::hash to the best of my knowledge hashes based on the bit representation with special handling for -0 and +0 (so OPs bug is a bug) but hash of 5.0 has no relation to hash of 5.0000001. So they can be (and usually are) very different results.

It's usually not the intended behavior for that small number to make a difference.

Floats are (and should be) compared with a tolerance based on your use case. In the end normalization is just one way that's usually a single line solution from a float to an int. You can use another way to go from float to something that can be hashed: for example, fixed point notations are fine too, they just take more effort and are usually an overkill in effort.

Is there a real use case for bit hashing floats? Probably a very very specific case of high precision lookup tables, and even there we quantize for robustness. All high precision tables I know of use interval arithmetic.

Edit: OP provided a use case in another comment:

what if i just want to cache stuff. I'm not saying one should use floats as keys. but also not that one should not use them. that's not my point, to be honest.

So in this case, a function, let's say float plus_2(float) will reprocess the +2 for every unique bit representation. For example, adding 0.1f ten times gives you 0x3F800001 (bits repr, in hex) while 0.1f * 10.0f gives you 0x3F800000 (same as 1.0f) reproduced on GCC 16.2

Meanwhile the output of plus_2 for all of them is the same (0x40400000)

So the std::hash cache fails at this. The fact that I had to hunt through my slides to find this example just shows how hard it can be to track down later.

1

u/no_overplay_no_fun 21d ago

Floats are (and should be) compared with a tolerance based on your use case.

Completely agree. I would just like to add that there will be use cases where the tolerance is 0.

I do not see how the caching fails. The function just returns the same output for different inputs. This might be surprising for +2 but such is life with floats. (a + 2 == a should also not be surprising for some floats a.) My understanding of "caching a function call" here is that "if call a function with input k and I already made a computation for input k, I will just go to the cache and provide the result and will not recompute."

1

u/sol_runner 21d ago edited 21d ago

If you have a 0 tolerance use case then floats are not a data type you should be using since float operations inherently add imprecisions. You can have small tolerances but I haven't seen a single use where tolerance with floats is exactly 0.

If I use a cache I expect fun(10-5) and fun(sqrt(25)) and fun(3.2+1.8) to only compute the function once. If it's computes the function twice, I'll call my cache a bad one - those are not different inputs. They differ because floats ops drifted. The quirks of floats are a limitation on the math we're trying to do. It's not the intent, and you need to provide tolerances to handle those quirks.

If you have a concrete example for need for absolute equality of floats that has basis in an actual problem, let me know - otherwise this just goes in circles. Edit: sorry about the frustration here. I've redacted but I own my mistake.

Even fast inverse square root which does rely on bit cast of a float does a recalibration with newtons method.

5

u/mark_99 21d ago

Using floats as keys in any data structure (hash table, std::map, whatever) is valid under the same circumstances as using FP equality.

You need approximate comparisons if you are doing arithmetic because that's what introduces the imprecision. If you are not, i.e. you are only copying/assigning the values, then it's fine.

NaN is troublesome, but in many use cases can be treated as an invalid input (and std::strong_order gives a valid ordering that includes both NaN and signed zeros, for ordered data structures).

Furthermore trying to do approx_equal() in an ordered data structure is UB as it breaks transitivity.

Your suggestion of quantising to integers fixes the UB but as there are arbitrary boundaries between the intervals you're not really grouping by proximity, and seemingly equivalent calculated values can fall in different intervals.

There are many circumstances where you are operating on float values but not recalculating them, for instance a price-indexed order book.

2

u/bwmat 18d ago

Furthermore trying to do approx_equal() in an ordered data structure is UB as it breaks transitivity.

Lol, we have some code which computes aggregations using floating point values as keys, in a context where we consider them equal with a delta/epsilon kind of check. We can't use the hash aggregation path because you can't really have a (non-constant) hash function which agrees with that definition of equality. 

So we fallback on the sort/unique code path

But then how do you even define the 'groups' in that situation? 

I've never gotten a response about how we should deal with that, so we just let it 'work' like it does, with everything above the low comparator level assuming equality isn't fuzzy

1

u/no_overplay_no_fun 21d ago

Ah, I see, thanks for the explanation! Probably better to end the discussion here if it makes you annoyed. Let me know if you want to hear more about floats. ;) best wishes

10

u/AKostur 22d ago

0.0 and -0.0 aren’t the same value: I wouldn’t expect them to hash to the same value.

37

u/arghness 22d ago

You may not expect it, but if 0.0 == -0.0 then the hashes should be the same, from the standard for std::hash.

0

u/AKostur 22d ago

If 0.0 == -0.0, isn’t that the bug?

39

u/JMBourguet 22d ago

0.0 == -0.0 is a requirement of IEEE 754.

4

u/R3DKn16h7 22d ago

for msvc 0.0 == -0.0 indeed, at least for these flags

what is worrying me is that is optimizing away the condition, I think

0

u/AKostur 22d ago

I'm curious about the condition you've written: is there a "-" sign missing in there somewhere? Right now it reads as "If _Keyval is 0.0, be 0.0, else be _Keyval", which basically works out to be a no-op?

2

u/Serialk 22d ago

It's not a noop for -0.0, that's the point

1

u/AKostur 22d ago

Right, it would compare as equal to 0.0, and thus get changed to a positive 0.0.  (Which may change its bitwise representation)

1

u/STL MSVC STL Dev 21d ago

Yes, the intent is to change the bitwise representation. The literal library code is:

https://github.com/microsoft/STL/blob/e1ed302683e5e822f663fbb0f44cee7e9ddc6af0/stl/inc/type_traits#L2492

This "canonicalizes" negative zero to positive zero before hashing its bits. It's a little unfortunate that we need to pay a branch here (maybe it turns into a conditional move), but these are the only two different-representation floating-point values that compare equal. We could of course mask away the sign bit entirely, but then that would increase collisions between -3.14 and 3.14.

2

u/ack_error 21d ago

Branch is probably not the worst actually, a float compare takes 2-4 cycles of latency on most architectures and the branch predictor helps take that compare off the critical path.

If I were nickle-and-diming latency cycles here for a branchless solution, I'd do the compare on the float but the select post-conversion on the integer side. That way the float compare runs in parallel to the move to GPR -- which is pretty expensive -- and only 1c of latency is added on the critical path.

7

u/xaervagon 22d ago

Does c++ actually require ieee 754 compliance now? I remember way back when, types were "whatever your CPU provided" and you just made with that.

7

u/AKostur 22d ago

Doesn't seem to, but is implementation defined. However, std::numeric_limits<float>::is_iec559() does test as true, so that implementation claims IEEE 754 compliance.

2

u/James20k P2005R0 22d ago

Its worth noting that even with implementations claiming to be ieee compliant, there are still several parts of the spec/compilers that are not ieee compliant, eg:

  1. Dividing by zero with floats is UB
  2. C++ compilers may transform a*b + c -> fma(a, b, c) (and they actively do this in practice without ffast-math)
  3. Anything involving 80 bit extended precision is a minefield
  4. Rounding modes aren't necessarily as implemented as you might want

2

u/ack_error 21d ago

C++ is in an annoying middle ground between floating point robustness and performance. It has too much leeway and not enough facilities for robust math, but everyone has to throw compiler switches and shift into a nonstandard dialect rules to get the performance optimizations they expect like vectorization.

6

u/AKostur 22d ago

I stand corrected. Good thing I don't need to deal with floating point in my field. Seems like if you add "/fp:strict", the problem goes away too. Did some searching which came up with some suggestions where things are going wrong. But I do now agree that this appears to be a bug in std::hash. (I also don't work in Windows)

6

u/Sinomsinom 22d ago edited 21d ago

According to the ieee 754 spec, -0.0 and +0.0 should be treated as equal in the context of numeric comparisons.

While IEEE 754 compliance isn't required, in practice it is what most people expect from floating point numbers in a low-ish level language nowadays. So 0.0 == -0.0 is not a bug.

(In both C++ and C there are ways of testing if the compiler is iee754 compliant though, and MSVC claims it is in those tests)

5

u/arghness 22d ago

IEEE 754 defines that they compare as numerically equal. You can use std::signbit() if you want to differentiate them.

3

u/FrogNoPants 21d ago

A simple solution is to bit cast your float to an integer, and now the comparison returns false, and the problem no longer exists, yw. In fact you should probably be doing this to avoid it shitting itself on NANs anyway.

1

u/Depixelate_me 20d ago

I wish vs2022 had this bug as it would mean we have an ABI stable c++23 option in IDE...:(

This greediness (we paid good money for vs2022!) is how you get people to explore other windows c++ dev solutions...

0

u/PoorAnalysis 22d ago

There are plenty of data types where different underlying bit patterns actually represent the same conceptual value, and should therefore "compare" equal even though their hashes wouldn't match.

Floats are one such type.

Unless std::hash is required to apply some sort of normalization before hashing, I don't see how this is a bug, or avoidable.

8

u/HommeMusical 22d ago

Of what use is a hash where a == b does not imply hash(a) == hash(b)?

You certainly can't use it for unordered containers for example.

2

u/PoorAnalysis 21d ago

Depends on your use case. Floats as a key to a set sounds mad anyway; should 0.1+0.2 and 0.3 be the same entry or different?

2

u/HommeMusical 21d ago

Well, I can't really think of any correct use cases that don't have that issue.

You should almost never compare floats for equality and hashing them has the same issue.

2

u/StaticCoder 21d ago

Floats are a lot worse than that though, because NaN is not equal to itself.

2

u/PoorAnalysis 21d ago

Same goes for boost::tribool's indeterminate state. Mathematically, non-equality make sense in those cases.

2

u/StaticCoder 21d ago

Mathematically, NaN is meaningless, and making float comparison not a real comparator is a source of bugs. I have yet to see any kind of code made correct by NaN != Nan, but I've seen plenty ot makes buggy.

1

u/PoorAnalysis 21d ago

True, mathematically you shouldn't be comparing NaNs, but if you do, and if the choice is only between returning True or False, False makes the most maths sense.

Maybe triggering a hardware exception like "divide by zero" would be the better decision.

1

u/bwmat 18d ago

My understanding is that NaN is actually just an optimization technique which allows checking for errors at the end of a complex operation without carrying auxillary state

There should probably be a hardware type (i.e. specialized instructions) which doesn't have this concept

1

u/StaticCoder 21d ago

What makes the most math sense to me is to have == be an equivalence relationship, which means true.

2

u/PoorAnalysis 21d ago

NaN only tells you what it's not, which is a number, it doesn't tell you what it is.

If I have two pets and say both are not dogs, that doesn't mean they are the equivalent species, they could be a cat and a goldfish.

1

u/HommeMusical 21d ago

But do your two pets have exactly the same representation in memory?

1

u/PoorAnalysis 21d ago

Do NaNs?

0

u/carrottread 21d ago

Yes, NaNs can have same bit pattern and still all comparisons return false. In your example if you have one not-dog which is a cat and compare it with itself it will be false.

0

u/StaticCoder 21d ago

I just checked boost tribool and its == returns another tribool, which is fine.

2

u/StaticCoder 21d ago

If different bit patterns represent equal values, then you shouldn't hash the bit patterns directly!