Use MSVC intrinsics for the 64×64-bit multiplication in full_multiplication()
detail::full_multiplication() in include/nlohmann/detail/bit_ops.hpp (added in #5617) computes the 128-bit product of two 64-bit numbers. GCC and Clang use unsigned __int128. All other compilers, including MSVC, fall back to four 32-bit partial products. MSVC has intrinsics for this:
- x64:
_umul128(a, b, &high)returns the low half and stores the high half (<intrin.h>). - ARM64:
a * bfor the low half and__umulh(a, b)for the high half.
Proposal
Add an #elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64)) branch to full_multiplication() and keep the portable fallback for everything else (32-bit MSVC, other compilers). clang-cl defines __SIZEOF_INT128__ and takes the first branch, so the order of the branches matters. Add a unit test that compares the result with the portable formula for edge values: 0, 1, UINT64_MAX, values around 2^32, and a few random pairs.
Why now, and why not yet
- On
develop, MSVC gains little. The only caller is the Eisel–Lemire fallback innumber_parse.hpp, which is only used whenstd::from_charsfor floating-point is unavailable. Current MSVC has it. - With the zero-copy view stack (#5768) it matters. #5634 writes doubles with Żmij (
detail/conversions/zmij.hpp), which callsfull_multiplication()several times per number, and #5738 parses floats with it. MSVC would then run the slow fallback in the hot path ofdump()for every double.
So this is worth doing once that stack is merged (or with it), and should be measured on MSVC x64 with dump() of a float-heavy file such as canada.json.
Background
Discussion #3782 asked for intrinsics in Grisu2's diyfp::mul() in to_chars.hpp, which uses the same 32-bit partial products. After #5634, Grisu2 is only used for float, so changing diyfp::mul() is not worth it on its own. It could call full_multiplication() to remove the duplicate code, keeping its rounding of the low half.
Written by Claude Code.
Hi! This looks like a good one to pick up, and I'd like to work on it. Happy to take it if it's still open. Thanks!