From abb4c8659ada30b232abcb8a90b756e783ee3220 Mon Sep 17 00:00:00 2001 From: jadidbourbaki Date: Mon, 14 Sep 2026 22:15:45 -0400 Subject: [PATCH 1/6] Fix std::float16_t rounding of subnormal ties and fast-path overflow --- include/fast_float/decimal_to_binary.h | 18 +- include/fast_float/float_common.h | 40 ++- include/fast_float/parse_number.h | 6 + script/format_parameters.py | 411 +++++++++++++++++++++++++ tests/CMakeLists.txt | 2 + tests/basictest.cpp | 30 ++ tests/exhaustive16_midpoint.cpp | 163 ++++++++++ 7 files changed, 652 insertions(+), 18 deletions(-) create mode 100644 script/format_parameters.py create mode 100644 tests/exhaustive16_midpoint.cpp diff --git a/include/fast_float/decimal_to_binary.h b/include/fast_float/decimal_to_binary.h index 9487682..a16d2c5 100644 --- a/include/fast_float/decimal_to_binary.h +++ b/include/fast_float/decimal_to_binary.h @@ -156,10 +156,20 @@ compute_float(int64_t q, uint64_t w) noexcept { return answer; } // next line is safe because -answer.power2 + 1 < 64 - answer.mantissa >>= -answer.power2 + 1; - // Thankfully, we can't have both "round-to-even" and subnormals because - // "round-to-even" only occurs for powers close to 0 in the 32-bit and - // and 64-bit case (with no more than 19 digits). + int const subnormal_shift = -answer.power2 + 1; + answer.mantissa >>= subnormal_shift; + // A subnormal result can also fall exactly between two floats. With at + // most 19 digits this never happens for float and double, but it does for + // std::float16_t (e.g., 2^-25 = 298023223876953125e-25), so we apply the + // same round-to-even test as in the normal case below. + // See script/format_parameters.py. + if ((product.low <= 1) && (q >= binary::min_exponent_round_to_even()) && + (q <= binary::max_exponent_round_to_even()) && + ((answer.mantissa & 3) == 1)) { + if (((answer.mantissa << subnormal_shift) << shift) == product.high) { + answer.mantissa &= ~uint64_t(1); // flip it so that we do not round up + } + } answer.mantissa += (answer.mantissa & 1); // round up answer.mantissa >>= 1; // There is a weird scenario where we don't have a subnormal but just. diff --git a/include/fast_float/float_common.h b/include/fast_float/float_common.h index 2fc3549..77858da 100644 --- a/include/fast_float/float_common.h +++ b/include/fast_float/float_common.h @@ -225,16 +225,12 @@ using parse_options = parse_options_t; #ifndef FASTFLOAT_ASSERT #define FASTFLOAT_ASSERT(x) \ - { \ - static_cast(x); \ - } + { static_cast(x); } #endif #ifndef FASTFLOAT_DEBUG_ASSERT #define FASTFLOAT_DEBUG_ASSERT(x) \ - { \ - static_cast(x); \ - } + { static_cast(x); } #endif // rust style `try!()` macro, or `?` operator @@ -665,6 +661,7 @@ template struct binary_format : binary_format_lookup_tables { static constexpr uint64_t max_mantissa_fast_path(int64_t power); static constexpr uint64_t max_mantissa_fast_path(); // used when fegetround() == FE_TONEAREST + static constexpr bool fast_path_can_overflow(); static constexpr int largest_power_of_ten(); static constexpr int smallest_power_of_ten(); static constexpr T exact_power_of_ten(int64_t power); @@ -696,6 +693,7 @@ template struct binary_format_lookup_tables { 0x20000000000000 / (constant_55555 * constant_55555 * 5), 0x20000000000000 / (constant_55555 * constant_55555 * 5 * 5), 0x20000000000000 / (constant_55555 * constant_55555 * 5 * 5 * 5), + 0x20000000000000 / (constant_55555 * constant_55555 * 5 * 5 * 5 * 5), 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555), 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555 * 5), 0x20000000000000 / @@ -711,9 +709,7 @@ template struct binary_format_lookup_tables { 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555 * constant_55555 * 5 * 5), 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555 * - constant_55555 * 5 * 5 * 5), - 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555 * - constant_55555 * 5 * 5 * 5 * 5)}; + constant_55555 * 5 * 5 * 5)}; }; #if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE @@ -930,7 +926,9 @@ binary_format::max_mantissa_fast_path(int64_t power) { template <> inline constexpr int binary_format::min_exponent_fast_path() { - return 0; + // w / 10^k with w <= 2^11 and k <= 4 rounds correctly even when evaluated + // in float or double first (checked in script/format_parameters.py). + return -4; } template <> @@ -942,7 +940,9 @@ binary_format::max_exponent_round_to_even() { template <> inline constexpr int binary_format::min_exponent_round_to_even() { - return -22; + // -22 covers the normal ties; subnormal ties such as + // 2^-25 = 298023223876953125e-25 need q = -25 and q = -26. + return -26; } template <> @@ -966,7 +966,8 @@ inline constexpr int binary_format::largest_power_of_ten() { template <> inline constexpr int binary_format::smallest_power_of_ten() { - return -27; + // (10^19 - 1) * 10^-27 < 2^-25, so any q < -26 rounds to zero. + return -26; } template <> @@ -1053,7 +1054,8 @@ binary_format::max_mantissa_fast_path(int64_t power) { template <> inline constexpr int binary_format::min_exponent_fast_path() { - return 0; + // Same argument as for std::float16_t (w <= 2^8, k <= 3). + return -3; } template <> @@ -1089,7 +1091,8 @@ inline constexpr int binary_format::largest_power_of_ten() { template <> inline constexpr int binary_format::smallest_power_of_ten() { - return -60; + // (10^19 - 1) * 10^-60 < 2^-134, so any q < -59 rounds to zero. + return -59; } template <> @@ -1098,6 +1101,15 @@ inline constexpr size_t binary_format::max_digits() { } #endif // __STDCPP_BFLOAT16_T__ +// Whether Clinger's fast path can overflow: only for std::float16_t, where +// 2^11 * 10^4 > 65504. +template +inline constexpr bool binary_format::fast_path_can_overflow() { + return double(max_mantissa_fast_path()) * + double(exact_power_of_ten(max_exponent_fast_path())) > + double((std::numeric_limits::max)()); +} + template <> inline constexpr uint64_t binary_format::max_mantissa_fast_path(int64_t power) { diff --git a/include/fast_float/parse_number.h b/include/fast_float/parse_number.h index 58cdafd..fd1acba 100644 --- a/include/fast_float/parse_number.h +++ b/include/fast_float/parse_number.h @@ -221,6 +221,12 @@ clinger_fast_path_impl(uint64_t mantissa, int64_t exponent, bool is_negative, value = value / binary_format::exact_power_of_ten(-exponent); } else { value = value * binary_format::exact_power_of_ten(exponent); + // Only std::float16_t can overflow here (e.g., "656e2"); let the + // slow path report result_out_of_range. + if (binary_format::fast_path_can_overflow() && + value > (std::numeric_limits::max)()) { + return false; + } } if (is_negative) { value = -value; diff --git a/script/format_parameters.py b/script/format_parameters.py new file mode 100644 index 0000000..1fb5cda --- /dev/null +++ b/script/format_parameters.py @@ -0,0 +1,411 @@ +# +# Checks the binary_format constants in include/fast_float/float_common.h +# with exact integer arithmetic, for double, float, std::float16_t and +# std::bfloat16_t. Every string is parsed as w * 10^q with w < 10^19, so each +# constant has a condition on (w, q) that it must satisfy. +# +# References: +# Daniel Lemire, Number Parsing at a Gigabyte per Second, +# Software: Practice and Experience 51 (8), 2021 https://arxiv.org/abs/2101.11408 +# Noble Mushtak and Daniel Lemire, Fast Number Parsing Without Fallback, +# Software: Practice and Experience 53 (6), 2023 https://arxiv.org/abs/2212.06644 +# +# Usage: python3 script/format_parameters.py [--types float16,bfloat16] +# [--sweep-width 3] [--jobs N] +# + +import argparse +import multiprocessing +import os +import re +import sys + +HEADER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", + "include", "fast_float", "float_common.h") +MASK64 = (1 << 64) - 1 +MAX_W = 10**19 +CXX_TYPES = {"double": "double", "float": "float", + "float16": "std::float16_t", "bfloat16": "std::bfloat16_t"} + + +class Format: + def __init__(self, name): + self.name = name + cxx = CXX_TYPES[name] + with open(HEADER) as f: + text = f.read() + pattern = r"binary_format<" + re.escape(cxx) + r">::(\w+)\(\)\s*\{(.*?)\n\}" + for fn, body in re.findall(pattern, text, re.S): + returns = re.findall(r"return\s+([^;]+);", body) + # the last return is the FLT_EVAL_METHOD 0/1 branch + if returns and re.fullmatch(r"-?(0x[0-9A-Fa-f]+|\d+)", returns[-1].strip()): + setattr(self, fn, int(returns[-1], 0)) + tables = re.search(r"binary_format_lookup_tables<" + re.escape(cxx) + + r", U>\s*\{(.*?)\n\};", text, re.S).group(1) + powers = re.search(r"powers_of_ten\[\]\s*=\s*\{(.*?)\}", tables, re.S).group(1) + self.powers_of_ten = [float(x) for x in + re.sub(r"(bf16|f16|f)\b", "", powers).split(",") if x.strip()] + mant = re.search(r"max_mantissa\[\]\s*=\s*\{(.*?)\}", tables, re.S).group(1) + mant = re.sub(r"//[^\n]*", "", mant).replace("/", "//").replace("\n", " ") + self.max_mantissa = [eval(x.strip(), {"constant_55555": 5**5}) + for x in mant.split(",") if x.strip()] + self.p = self.mantissa_explicit_bits + self.bias = self.p - self.minimum_exponent + self.denorm_min_exp = 1 - self.bias # smallest subnormal is 2^denorm_min_exp + self.emin = self.minimum_exponent + 1 # leading bit of the smallest normal + self.emax = self.infinite_power - 1 + self.minimum_exponent + + def grid(self): + """Every finite value and every midpoint as (num, exp2, kind) with + kind in value, tie_down (even lower neighbour), tie_up, overflow.""" + out = [] + two_p = 1 << self.p + d = self.denorm_min_exp + for m in range(1, two_p): + out.append((m, d, "value")) + for m in range(two_p): + out.append((2 * m + 1, d - 1, "tie_down" if m % 2 == 0 else "tie_up")) + for e in range(self.emin, self.emax + 1): + for f in range(two_p): + out.append((two_p + f, e - self.p, "value")) + kind = "tie_down" if f % 2 == 0 else "tie_up" + if e == self.emax and f == two_p - 1: + kind = "overflow" + out.append((2 * (two_p + f) + 1, e - self.p - 1, kind)) + return out + + +def ratio(num, exp2): + return (num << exp2, 1) if exp2 >= 0 else (num, 1 << -exp2) + + +def ratio10(w, q): + return (w * 10**q, 1) if q >= 0 else (w, 10**-q) + + +def le(n1, d1, n2, d2): + return n1 * d2 <= n2 * d1 + + +def floor_log2(n, d): + e = n.bit_length() - d.bit_length() + if (d << e if e >= 0 else d) > (n if e >= 0 else n << -e): + e -= 1 + return e + + +def round_ties_even(n, d): + m, r = divmod(n, d) + if 2 * r > d or (2 * r == d and m & 1): + m += 1 + return m + + +def reference_bits(fmt, n, d): + """Correctly rounded bit pattern of n/d >= 0.""" + if n == 0: + return 0 + e = floor_log2(n, d) + s = fmt.denorm_min_exp if e < fmt.emin else e - fmt.p + m = round_ties_even(n, d << s) if s >= 0 else round_ties_even(n << -s, d) + if e < fmt.emin: + return m + if m == 2 << fmt.p: + m >>= 1 + e += 1 + if e > fmt.emax: + return fmt.infinite_power << fmt.p + return ((e - fmt.minimum_exponent) << fmt.p) | (m - (1 << fmt.p)) + + +def ceil_log2(x): + z = 0 + while (1 << z) < x: + z += 1 + return z + + +def table_entry(q): + """T[q] as stored in fast_table.h (see table_generation.py).""" + if q < 0: + power5 = 5**-q + z = ceil_log2(power5) + b = z + 127 if q >= -27 else 2 * z + 128 + c = 2**b // power5 + 1 + while c >= 1 << 128: + c //= 2 + return c + power5 = 5**q + while power5 < 1 << 127: + power5 *= 2 + while power5 >= 1 << 128: + power5 //= 2 + return power5 + + +TABLE = {q: table_entry(q) for q in range(-342, 309)} + + +def compute_product_approximation(q, w, bit_precision): + t = TABLE[q] + first = w * (t >> 64) + high, low = first >> 64, first & MASK64 + if (high & (MASK64 >> bit_precision)) == MASK64 >> bit_precision: + second_high = (w * (t & MASK64)) >> 64 + low = (low + second_high) & MASK64 + if second_high > low: + high += 1 + return high, low + + +def compute_float(fmt, q, w, subnormal_tie_test=True): + """Model of compute_float in decimal_to_binary.h. Returns + (mantissa, power2, truncated mantissa, k) with truncated == floor(w 10^q 2^k).""" + if w == 0 or q < fmt.smallest_power_of_ten: + return 0, 0, None, None + if q > fmt.largest_power_of_ten: + return 0, fmt.infinite_power, None, None + lz = 64 - w.bit_length() + w <<= lz + high, low = compute_product_approximation(q, w, fmt.p + 3) + upperbit = high >> 63 + shift = upperbit + 64 - fmt.p - 3 + mantissa = high >> shift + power2 = ((152170 + 65536) * q >> 16) + 63 + upperbit - lz - fmt.minimum_exponent + tie_q = fmt.min_exponent_round_to_even <= q <= fmt.max_exponent_round_to_even + if power2 <= 0: + if -power2 + 1 >= 64: + return 0, 0, None, None + extra = -power2 + 1 + mantissa >>= extra + truncated, k = mantissa, fmt.bias + if (subnormal_tie_test and low <= 1 and tie_q and (mantissa & 3) == 1 + and ((mantissa << extra) << shift) == high): + mantissa &= ~1 + mantissa += mantissa & 1 + mantissa >>= 1 + return mantissa, int(mantissa >= 1 << fmt.p), truncated, k + truncated, k = mantissa, 1 + fmt.bias - power2 + if low <= 1 and tie_q and (mantissa & 3) == 1 and (mantissa << shift) == high: + mantissa &= ~1 + mantissa += mantissa & 1 + mantissa >>= 1 + if mantissa >= 2 << fmt.p: + mantissa = 1 << fmt.p + power2 += 1 + mantissa &= ~(1 << fmt.p) + if power2 >= fmt.infinite_power: + return 0, fmt.infinite_power, truncated, k + return mantissa, power2, truncated, k + + +def parsed_bits(fmt, w, q, subnormal_tie_test=True): + """from_chars on the digits w * 10^q. Clinger's fast path is one correctly + rounded operation on exact operands, so it equals the reference.""" + if fmt.min_exponent_fast_path <= q <= fmt.max_exponent_fast_path and w <= 2 << fmt.p: + return reference_bits(fmt, *ratio10(w, q)), None, None + mantissa, power2, truncated, k = compute_float(fmt, q, w, subnormal_tie_test) + return mantissa | (power2 << fmt.p), truncated, k + + +failures = 0 + + +def check(ok, text): + global failures + print((" ok " if ok else " FAIL ") + text) + failures += not ok + + +def note(text): + print(" note " + text) + + +def continued_fraction(numer, denom): + cf = [] + while denom: + quot, rem = divmod(numer, denom) + cf.append(quot) + numer, denom = denom, rem + return cf + + +def convergents(cf): + p2, q2, p1, q1 = 0, 1, 1, 0 + for a in cf: + p1, p2, q1, q2 = a * p1 + p2, p1, a * q1 + q2, q1 + yield p1, q1 + + +def check_constants(fmt): + half_denorm = ratio(1, fmt.denorm_min_exp - 1) + q = fmt.smallest_power_of_ten + check(le(*ratio10(MAX_W - 1, q - 1), *half_denorm), + "smallest_power_of_ten=%d: q < %d rounds to zero" % (q, q)) + check(not le(*ratio10(MAX_W - 1, q), *half_denorm), + "smallest_power_of_ten is tight") + threshold = ratio((4 << fmt.p) - 1, fmt.emax - fmt.p - 1) # max + ulp/2 + q = fmt.largest_power_of_ten + check(le(*threshold, *ratio10(1, q + 1)), + "largest_power_of_ten=%d: q > %d overflows" % (q, q)) + check(not le(*threshold, *ratio10(1, q)), "largest_power_of_ten is tight") + + two_p1 = 2 << fmt.p + q = fmt.max_exponent_fast_path + check(5**q <= two_p1 < 5 ** (q + 1), + "max_exponent_fast_path=%d: 10^q exact in T iff q <= %d" % (q, q)) + check(fmt.powers_of_ten[: q + 1] == [10.0**i for i in range(q + 1)], "powers_of_ten") + check(fmt.max_mantissa[: q + 1] == [two_p1 // 5**i for i in range(q + 1)], + "max_mantissa[q] == floor(2^%d / 5^q)" % (fmt.p + 1)) + overflow = not le(two_p1 * 10**q, 1, *ratio(two_p1 - 1, fmt.emax - fmt.p)) + note("fast path product 2^%d * 10^%d %s the largest finite value" + % (fmt.p + 1, q, "exceeds" if overflow else "is below")) + k = -fmt.min_exponent_fast_path + check(0 <= k <= fmt.max_exponent_fast_path, "min_exponent_fast_path=%d" % -k) + if fmt.p <= 10: + # double rounding: w / 10^k rounded to `wide` bits, then to T + for wide in (24, 53, 64): + bad = 0 + for kk in range(1, fmt.max_exponent_fast_path + 1): + for w in range(1, two_p1 + 1): + e = floor_log2(w, 10**kk) + s = e - wide + 1 + m = round_ties_even(w, 10**kk << s) if s >= 0 else round_ties_even(w << -s, 10**kk) + if reference_bits(fmt, *ratio(m, s)) != reference_bits(fmt, w, 10**kk): + bad += 1 + check(bad == 0, "w / 10^k, k <= %d, via %d-bit intermediate never double-rounds" + % (fmt.max_exponent_fast_path, wide)) + + +def check_ties(fmt): + """A tie is m * 2^e with m odd. It is w * 10^q, w < 10^19, iff q <= e and + w = m 5^-q 2^(e-q) (q <= 0) or 5^q | m (q > 0). Ties whose lower neighbour + is even (m == 1 mod 4) must fall in the round-to-even range.""" + p = fmt.p + lo, hi = fmt.min_exponent_round_to_even, fmt.max_exponent_round_to_even + q = 0 + while ((1 << (p + 1)) + 1) * 5 ** (q + 1) < MAX_W: + q += 1 + normal_lo = -q + q = 0 + while 5 ** (q + 1) < 1 << (p + 2): + q += 1 + while True: + c = 1 + while 5**q * c <= 1 << (p + 1): + c += 4 + if 5**q * c < 1 << (p + 2) and q <= fmt.emax - p - 1: + break + q -= 1 + normal_hi = q + e = fmt.denorm_min_exp - 1 + sub = [] + q = e + while 5**-q << (e - q) < MAX_W: + sub.append(q) + q -= 1 + check(lo <= normal_lo and hi >= normal_hi, + "round_to_even range [%d, %d] covers normal ties [%d, %d]" % (lo, hi, normal_lo, normal_hi)) + if sub: + check(lo <= min(sub), "and the subnormal ties at q in [%d, %d]" % (min(sub), max(sub))) + else: + note("no subnormal tie has fewer than 20 digits") + longest = len(str(((1 << (p + 2)) - 1) * 5**fmt.bias)) + check(fmt.max_digits >= longest, "max_digits=%d >= %d, the longest tie" % (fmt.max_digits, longest)) + + +def check_table(fmt): + """Facts behind the tie test (product.low <= 1 and dropped bits zero).""" + q_lo, q_hi = max(fmt.smallest_power_of_ten, -27), -1 + check(fmt.min_exponent_round_to_even >= -27, "tie test stays where 5^-q < 2^64") + check(all(TABLE[q] & MASK64 for q in range(q_lo, q_hi + 1)), + "T[q] low word nonzero for %d <= q <= %d" % (q_lo, q_hi)) + fake = False + for q in range(q_lo, q_hi + 1): + t_hi = TABLE[q] >> 64 + v2 = (t_hi & -t_hi).bit_length() - 1 + z = ceil_log2(5**-q) + for shift in (61 - fmt.p, 62 - fmt.p): + # skipped second product: w * t_hi == 0 or 1 mod 2^(shift+64) + if shift + 64 - v2 <= 63: + fake = True + if v2 == 0 and (1 << 63) <= pow(t_hi, -1, 1 << (shift + 64)) < 1 << 64: + fake = True + # computed second product: a non-tie within 2^-62 of a rational + # with denominator 2^(z-1-shift) is impossible + if z - 1 - shift > 62: + fake = True + check(not fake, "no false tie for %d <= q <= %d" % (q_lo, q_hi)) + bad = False + for q in range(fmt.smallest_power_of_ten, fmt.largest_power_of_ten + 1): + for _, w in convergents(continued_fraction(TABLE[q], 2**137)): + if w >= 2**64: + break + if (TABLE[q] * w) % 2**137 > 2**137 - 2**64: + bad = True + check(not bad, "Mushtak-Lemire condition for %d <= q <= %d" + % (fmt.smallest_power_of_ten, fmt.largest_power_of_ten)) + + +def sweep_q(args): + fmt, grid, q, width = args + cands = set() + for num, exp2, _ in grid: + n, d = ratio(num, exp2) + if q >= 0: + d *= 10**q + else: + n *= 10**-q + cands.update(w for w in range(n // d - width, n // d + width + 2) if 1 <= w < MAX_W) + wrong, wrong_without, bad_trunc = [], 0, 0 + for w in cands: + n, d = ratio10(w, q) + want = reference_bits(fmt, n, d) + got, truncated, k = parsed_bits(fmt, w, q) + if got != want: + wrong.append((w, q, got, want)) + if truncated is not None: + exact = (n << k) // d if k >= 0 else n // (d << -k) + bad_trunc += truncated != exact + if parsed_bits(fmt, w, q, False)[0] != want: + wrong_without += 1 + return len(cands), wrong, wrong_without, bad_trunc + + +def sweep(fmt, width, jobs): + """Compare the model with the reference on every w within `width` of + G / 10^q for every value, tie and the overflow threshold G.""" + grid = fmt.grid() + qs = range(fmt.smallest_power_of_ten - 1, fmt.largest_power_of_ten + 2) + tasks = [(fmt, grid, q, width) for q in qs] + with multiprocessing.Pool(jobs) as pool: + results = pool.map(sweep_q, tasks) + wrong = [x for r in results for x in r[1]] + note("swept %d pairs (w, q)" % sum(r[0] for r in results)) + check(sum(r[3] for r in results) == 0, "truncated mantissa is exact") + check(not wrong, "compute_float matches the reference") + for w, q, got, want in sorted(wrong)[:20]: + print(" w=%d q=%d got 0x%04x want 0x%04x" % (w, q, got, want)) + note("without the subnormal tie test: %d wrong" % sum(r[2] for r in results)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--types", default="double,float,float16,bfloat16") + ap.add_argument("--sweep-width", type=int, default=3) + ap.add_argument("--jobs", type=int, default=os.cpu_count() or 1) + args = ap.parse_args() + for name in args.types.split(","): + fmt = Format(name.strip()) + print("== %s" % fmt.name) + check_constants(fmt) + check_table(fmt) + check_ties(fmt) + if fmt.p <= 10 and args.sweep_width > 0: + sweep(fmt, args.sweep_width, args.jobs) + print("%d failure(s)" % failures) + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index f8cc134..65e7d70 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -94,6 +94,8 @@ endif() if (FASTFLOAT_FIXEDWIDTH_TESTS) fast_float_add_cpp_test(fixedwidthtest) target_compile_features(fixedwidthtest PUBLIC cxx_std_23) + fast_float_add_cpp_test(exhaustive16_midpoint) + target_compile_features(exhaustive16_midpoint PUBLIC cxx_std_23) endif() option(FASTFLOAT_EXHAUSTIVE "Exhaustive tests" OFF) diff --git a/tests/basictest.cpp b/tests/basictest.cpp index f9abefd..9b45822 100644 --- a/tests/basictest.cpp +++ b/tests/basictest.cpp @@ -1832,6 +1832,20 @@ TEST_CASE("float16.inf") { std::errc::result_out_of_range); verify("3.5028234666e38", std::numeric_limits::infinity(), std::errc::result_out_of_range); + // overflow in the fast path + verify("656e2", std::numeric_limits::infinity(), + std::errc::result_out_of_range); + verify("-656e2", -std::numeric_limits::infinity(), + std::errc::result_out_of_range); + verify("7e4", std::numeric_limits::infinity(), + std::errc::result_out_of_range); + verify("2048e4", std::numeric_limits::infinity(), + std::errc::result_out_of_range); + verify("655e2", 0x1.ffcp+15f16); // 65500 rounds to max + // max + ulp/2 rounds to even + verify("6552e1", std::numeric_limits::infinity(), + std::errc::result_out_of_range); + verify("65519", 0x1.ffcp+15f16); } TEST_CASE("float16.general") { @@ -1852,6 +1866,22 @@ TEST_CASE("float16.general") { verify("-0.000000059604644775390625", -0x1p-24f16); verify("-5.9604644775390625e-8", -0x1p-24f16); + // subnormal ties round to even + verify("2.98023223876953125e-8", 0.0f16, std::errc::result_out_of_range); + verify("0.0000000298023223876953125", 0.0f16, std::errc::result_out_of_range); + verify("-2.98023223876953125e-8", -0.0f16, std::errc::result_out_of_range); + verify("8.94069671630859375e-8", 0x1p-23f16); + verify("1.490116119384765625e-7", 0x1p-23f16); + verify("9.834766387939453125e-7", 0x1p-20f16); + // just above or below a tie + verify("2.980232238769531251e-8", 0x1p-24f16); + verify("2.980232238769531249e-8", 0.0f16, std::errc::result_out_of_range); + verify("1.4901161193847656251e-7", 0x1.8p-23f16); + verify("1.4901161193847656249e-7", 0x1p-23f16); + // more than 19 digits + verify("2.9802322387695312500e-8", 0.0f16, std::errc::result_out_of_range); + verify("1.4901161193847656250000e-7", 0x1p-23f16); + verify("-1e-999", -0.0f16, std::errc::result_out_of_range); verify("6.0975551605224609375", 0x1.864p+2f16); verify_runtime(append_zeros("6.0975551605224609375", 655), 0x1.864p+2f16); diff --git a/tests/exhaustive16_midpoint.cpp b/tests/exhaustive16_midpoint.cpp new file mode 100644 index 0000000..816aeeb --- /dev/null +++ b/tests/exhaustive16_midpoint.cpp @@ -0,0 +1,163 @@ +// For std::float16_t and std::bfloat16_t, parse the exact decimal expansion +// of every finite value and of every midpoint between adjacent values, plus +// strings just above and below each midpoint and midpoints padded past 19 +// digits. The expected bits follow from the bit pattern that generated the +// string, so no C library reference is needed. +#include "fast_float/fast_float.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +// Decimal digit strings, most significant digit first, no leading zeros. +std::string times(std::string const &digits, unsigned factor) { + std::string out; + unsigned carry = 0; + for (size_t i = digits.size(); i-- > 0;) { + unsigned v = static_cast(digits[i] - '0') * factor + carry; + out.push_back(static_cast('0' + v % 10)); + carry = v / 10; + } + while (carry != 0) { + out.push_back(static_cast('0' + carry % 10)); + carry /= 10; + } + return std::string(out.rbegin(), out.rend()); +} + +std::string minus_one(std::string digits) { + size_t i = digits.size(); + while (i-- > 0) { + if (digits[i] != '0') { + digits[i] = static_cast(digits[i] - 1); + break; + } + digits[i] = '9'; + } + return digits; +} + +// num * 2^exp2 written as "e" with an exact expansion. +struct Decimal { + std::string digits; + int exponent; + + std::string str() const { return digits + "e" + std::to_string(exponent); } + + Decimal above() const { return {digits + "1", exponent - 1}; } + + Decimal below() const { return {minus_one(digits) + "9", exponent - 1}; } + + Decimal padded(size_t count) const { + return {digits + std::string(count, '0'), + exponent - static_cast(count)}; + } +}; + +Decimal exact_decimal(uint64_t num, int exp2) { + std::string digits = std::to_string(num); + if (exp2 >= 0) { + for (int i = 0; i < exp2; i++) { + digits = times(digits, 2); + } + return {digits, 0}; + } + for (int i = 0; i < -exp2; i++) { + digits = times(digits, 5); + } + return {digits, exp2}; +} + +template struct Layout; + +template <> struct Layout { + static constexpr char const *name = "float16"; + static constexpr int p = 10; + static constexpr int bias = 25; // value = mantissa * 2^(field - bias) + static constexpr uint16_t infinity = 0x7C00; +}; + +template <> struct Layout { + static constexpr char const *name = "bfloat16"; + static constexpr int p = 7; + static constexpr int bias = 134; + static constexpr uint16_t infinity = 0x7F80; +}; + +struct Failure { + long count = 0; + long checked = 0; +}; + +template +void expect(Failure &f, std::string const &s, uint16_t want) { + T value{}; + auto r = fast_float::from_chars(s.data(), s.data() + s.size(), value); + uint16_t got = 0; + std::memcpy(&got, &value, sizeof(got)); + bool zero_or_inf = want == 0 || want == Layout::infinity; + std::errc want_ec = + zero_or_inf ? std::errc::result_out_of_range : std::errc(); + f.checked++; + if (got != want || r.ec != want_ec || r.ptr != s.data() + s.size()) { + f.count++; + if (f.count <= 20) { + std::printf( + "%s: \"%s\" parsed to 0x%04x (ec %d), expected 0x%04x (ec %d)\n", + Layout::name, s.c_str(), got, static_cast(r.ec), want, + static_cast(want_ec)); + } + } +} + +template Failure sweep() { + Failure f; + constexpr int p = Layout::p; + constexpr uint16_t mantissa_mask = static_cast((1u << p) - 1); + for (uint32_t b = 0; b < Layout::infinity; b++) { + uint16_t bits = static_cast(b); + int field = bits >> p; + uint64_t num = bits & mantissa_mask; + int exp2 = (field == 0 ? 1 : field) - Layout::bias; + if (field != 0) { + num |= uint64_t(1) << p; + } + if (num != 0) { + Decimal d = exact_decimal(num, exp2); + expect(f, d.str(), bits); + expect(f, d.padded(21).str(), bits); + } + // The tie between bits and bits + 1 is (2 num + 1) * 2^(exp2 - 1); the + // last one (bits + 1 == infinity) is the overflow threshold. + Decimal tie = exact_decimal(2 * num + 1, exp2 - 1); + uint16_t lower = bits; + uint16_t upper = static_cast(bits + 1); + uint16_t even = (bits & 1) ? upper : lower; + expect(f, tie.str(), even); + expect(f, tie.padded(21).str(), even); + expect(f, tie.above().str(), upper); + expect(f, tie.below().str(), lower); + } + return f; +} + +} // namespace + +int main() { + Failure f16 = sweep(); + std::printf("float16: %ld strings, %ld failures\n", f16.checked, f16.count); + Failure bf16 = sweep(); + std::printf("bfloat16: %ld strings, %ld failures\n", bf16.checked, + bf16.count); + if (f16.count != 0 || bf16.count != 0) { + return EXIT_FAILURE; + } + std::printf("all ok\n"); + return EXIT_SUCCESS; +} From 20a9b353334299916793aa8215607bcaffaf5e1a Mon Sep 17 00:00:00 2001 From: jadidbourbaki Date: Tue, 15 Sep 2026 09:11:27 -0400 Subject: [PATCH 2/6] Gate the subnormal tie test on a compile-time predicate --- include/fast_float/decimal_to_binary.h | 3 ++- include/fast_float/float_common.h | 18 ++++++++++++++++-- script/format_parameters.py | 5 +++++ 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/include/fast_float/decimal_to_binary.h b/include/fast_float/decimal_to_binary.h index a16d2c5..273f0b7 100644 --- a/include/fast_float/decimal_to_binary.h +++ b/include/fast_float/decimal_to_binary.h @@ -163,7 +163,8 @@ compute_float(int64_t q, uint64_t w) noexcept { // std::float16_t (e.g., 2^-25 = 298023223876953125e-25), so we apply the // same round-to-even test as in the normal case below. // See script/format_parameters.py. - if ((product.low <= 1) && (q >= binary::min_exponent_round_to_even()) && + if (binary::subnormal_ties_possible() && (product.low <= 1) && + (q >= binary::min_exponent_round_to_even()) && (q <= binary::max_exponent_round_to_even()) && ((answer.mantissa & 3) == 1)) { if (((answer.mantissa << subnormal_shift) << shift) == product.high) { diff --git a/include/fast_float/float_common.h b/include/fast_float/float_common.h index 77858da..76d94b3 100644 --- a/include/fast_float/float_common.h +++ b/include/fast_float/float_common.h @@ -225,12 +225,16 @@ using parse_options = parse_options_t; #ifndef FASTFLOAT_ASSERT #define FASTFLOAT_ASSERT(x) \ - { static_cast(x); } + { \ + static_cast(x); \ + } #endif #ifndef FASTFLOAT_DEBUG_ASSERT #define FASTFLOAT_DEBUG_ASSERT(x) \ - { static_cast(x); } + { \ + static_cast(x); \ + } #endif // rust style `try!()` macro, or `?` operator @@ -662,6 +666,7 @@ template struct binary_format : binary_format_lookup_tables { static constexpr uint64_t max_mantissa_fast_path(); // used when fegetround() == FE_TONEAREST static constexpr bool fast_path_can_overflow(); + static constexpr bool subnormal_ties_possible(); static constexpr int largest_power_of_ten(); static constexpr int smallest_power_of_ten(); static constexpr T exact_power_of_ten(int64_t power); @@ -1110,6 +1115,15 @@ inline constexpr bool binary_format::fast_path_can_overflow() { double((std::numeric_limits::max)()); } +// A subnormal needs w * 10^q < 2^(minimum_exponent() + 1), so q is at most +// (minimum_exponent() + 1) * log10(2), with 1233/4096 < log10(2). Only +// std::float16_t has such q in its round-to-even range. +template +inline constexpr bool binary_format::subnormal_ties_possible() { + return min_exponent_round_to_even() <= + (((minimum_exponent() + 1) * 1233) >> 12); +} + template <> inline constexpr uint64_t binary_format::max_mantissa_fast_path(int64_t power) { diff --git a/script/format_parameters.py b/script/format_parameters.py index 1fb5cda..e981b8f 100644 --- a/script/format_parameters.py +++ b/script/format_parameters.py @@ -310,6 +310,11 @@ def check_ties(fmt): check(lo <= min(sub), "and the subnormal ties at q in [%d, %d]" % (min(sub), max(sub))) else: note("no subnormal tie has fewer than 20 digits") + # subnormal_ties_possible() in float_common.h: an upper bound on the + # largest q that can give a subnormal, compared with the tie range + q_sub = ((fmt.minimum_exponent + 1) * 1233) >> 12 + check(10**q_sub < 2**fmt.emin < 10 ** (q_sub + 2), "q <= %d bounds the subnormal exponents" % q_sub) + check((lo <= q_sub) == bool(sub), "subnormal_ties_possible() == %s" % bool(sub)) longest = len(str(((1 << (p + 2)) - 1) * 5**fmt.bias)) check(fmt.max_digits >= longest, "max_digits=%d >= %d, the longest tie" % (fmt.max_digits, longest)) From b2e41e8b8807cf200e54a1a8613515a52501c008 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Mar=C3=ADn?= Date: Mon, 21 Sep 2026 19:45:12 +0000 Subject: [PATCH 3/6] Keep chars_format::javascript out of the common hot path 8.3.0 added the ECMAScript leading-zero rule as a runtime test on fmt inside parse_number_string, so unlike basic_json_fmt its error returns and Annex B octal scan land in the parser body that every from_chars instantiation force-inlines. from_chars_caller::call grew from 935 to 1031 instructions and other formats lost about 3% on short inputs. Make the rule a compile-time parameter of the parser body, selected once at the entry point, and take chars_format::javascript out to a cold conversion before anything else is live so the branch is a tail call. parse_number_string keeps its signature and behaviour. benchmarks/benchmark.cpp, Intel Xeon 6975P-C, clang 22.1.8, cycles per float, best of 7: canada.txt mesh.txt 8.2.10 47.03 24.78 8.3.0 47.34 26.08 this 46.28 24.86 --- include/fast_float/ascii_number.h | 43 ++++++++++++++++++++++--- include/fast_float/float_common.h | 11 +++++++ include/fast_float/parse_number.h | 52 ++++++++++++++++++++++++++++--- 3 files changed, 97 insertions(+), 9 deletions(-) diff --git a/include/fast_float/ascii_number.h b/include/fast_float/ascii_number.h index 52f1e84..e814f12 100644 --- a/include/fast_float/ascii_number.h +++ b/include/fast_float/ascii_number.h @@ -339,10 +339,11 @@ report_parse_error(UC const *p, parse_error error) { // spans (read only by the rare digit_comp slow path) are not materialized, // which keeps the fat parsed_number_string_t off the hot path. The caller // re-parses with store_spans=true if the slow path is actually reached. -template +template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 parsed_number_string_t -parse_number_string(UC const *p, UC const *pend, parse_options_t options, - bool store_spans = true) noexcept { +parse_number_string_impl(UC const *p, UC const *pend, + parse_options_t options, + bool store_spans) noexcept { chars_format const fmt = detail::adjust_for_feature_macros(options.format); UC const decimal_point = options.decimal_point; @@ -424,7 +425,7 @@ parse_number_string(UC const *p, UC const *pend, parse_options_t options, parse_error::leading_zeros_in_integer_part); } } - else if (uint64_t(fmt & detail::basic_javascript_fmt)) { + else FASTFLOAT_IF_CONSTEXPR17(basic_javascript_fmt) { // ECMAScript DecimalIntegerLiteral is "0" or a non-zero digit followed by // digits: no leading zeros. Unlike JSON, the integer part may be empty // (".5"); the no_digits_in_mantissa check below still rejects ".". @@ -587,6 +588,40 @@ parse_number_string(UC const *p, UC const *pend, parse_options_t options, return answer; } +// Cold instantiation of the parser: the ECMAScript integer-part rule costs two +// error returns plus the Annex B octal scan, and parse_number_string_impl is +// force-inlined, so an inlined javascript body would enlarge the frame of every +// caller that never asks for it. Out of line, it costs those callers nothing. +template +fastfloat_never_inline FASTFLOAT_CONSTEXPR20 parsed_number_string_t +parse_number_string_javascript(UC const *p, UC const *pend, + parse_options_t options, + bool store_spans) noexcept { + return parse_number_string_impl(p, pend, options, + store_spans); +} + +// Public entry point, behaviour unchanged: chars_format::javascript is still +// honoured, it is just selected here once instead of being re-tested inside the +// parser loop. Callers that have already ruled the format out (see +// from_chars_float_advanced) should call parse_number_string_impl directly so +// that not even this test reaches their hot path. +template +fastfloat_really_inline FASTFLOAT_CONSTEXPR20 parsed_number_string_t +parse_number_string(UC const *p, UC const *pend, parse_options_t options, + bool store_spans = true) noexcept { + // JSON and JavaScript are mutually exclusive, so only the non-JSON + // instantiation has to look at the flag. + FASTFLOAT_IF_CONSTEXPR17(!basic_json_fmt) { + if fastfloat_unlikely (uint64_t(options.format & + detail::basic_javascript_fmt)) { + return parse_number_string_javascript(p, pend, options, store_spans); + } + } + return parse_number_string_impl(p, pend, options, + store_spans); +} + template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t parse_int_string(UC const *p, UC const *pend, T &value, diff --git a/include/fast_float/float_common.h b/include/fast_float/float_common.h index 87c72b0..3769972 100644 --- a/include/fast_float/float_common.h +++ b/include/fast_float/float_common.h @@ -217,6 +217,17 @@ using parse_options = parse_options_t; #define fastfloat_really_inline inline __attribute__((always_inline)) #endif +// Opposite of fastfloat_really_inline. Used for a rare, format-specific variant +// of a force-inlined function, so that its body does not land in the frame of +// every caller that will never execute it. +#ifdef FASTFLOAT_VISUAL_STUDIO +#define fastfloat_never_inline __declspec(noinline) +#elif defined(__GNUC__) || defined(__clang__) +#define fastfloat_never_inline __attribute__((noinline)) +#else +#define fastfloat_never_inline +#endif + // Branch-probability hint marking the rare slow-path branches as cold, so the // optimizer keeps the out-of-line slow-path re-parse off the hot path (and does // not duplicate the force-inlined hot scanner into the caller, which bloated diff --git a/include/fast_float/parse_number.h b/include/fast_float/parse_number.h index 58cdafd..14d077b 100644 --- a/include/fast_float/parse_number.h +++ b/include/fast_float/parse_number.h @@ -306,8 +306,41 @@ FASTFLOAT_CONSTEXPR20 from_chars_result_t parse_number_slow_path(UC const *first, UC const *last, T &value, parse_options_t options, bool bjf) noexcept { parsed_number_string_t pns = - bjf ? parse_number_string(first, last, options, true) - : parse_number_string(first, last, options, true); + bjf ? parse_number_string_impl(first, last, options, + true) + : parse_number_string_impl(first, last, options, + true); + return from_chars_advanced(pns, value); +} + +// Cold: the whole chars_format::javascript conversion. Kept out of line and out +// of from_chars_float_advanced so the common frame holds neither the javascript +// parser body nor a call that would force the parsed number string onto the +// stack. Mirrors the main path, only with the javascript parser. +template +fastfloat_never_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t +from_chars_float_javascript(UC const *first, UC const *last, T &value, + parse_options_t options) noexcept { + chars_format const fmt = detail::adjust_for_feature_macros(options.format); + if (uint64_t(fmt & chars_format::skip_white_space)) { + while ((first != last) && fast_float::is_space(*first)) { + first++; + } + } + from_chars_result_t answer; + answer.ec = std::errc::invalid_argument; + answer.ptr = first; + if (first == last) { + return answer; + } + parsed_number_string_t pns = + parse_number_string_javascript(first, last, options, true); + if (!pns.valid) { + if (uint64_t(fmt & chars_format::no_infnan)) { + return answer; + } + return detail::parse_infnan(first, last, value, fmt); + } return from_chars_advanced(pns, value); } @@ -323,6 +356,13 @@ from_chars_float_advanced(UC const *first, UC const *last, T &value, chars_format const fmt = detail::adjust_for_feature_macros(options.format); + // Leave for the javascript conversion before anything else is live, so this + // compiles to a tail call and the common path keeps its registers. The cold + // function repeats the leading-whitespace and empty-input handling below. + if fastfloat_unlikely (uint64_t(fmt & detail::basic_javascript_fmt)) { + return from_chars_float_javascript(first, last, value, options); + } + from_chars_result_t answer; if (uint64_t(fmt & chars_format::skip_white_space)) { while ((first != last) && fast_float::is_space(*first)) { @@ -339,10 +379,12 @@ from_chars_float_advanced(UC const *first, UC const *last, T &value, // Fast path: parse WITHOUT materializing the integer/fraction spans (read // only by the rare slow paths). Skipping their stores keeps the fat // parsed_number_string_t off the hot path. store_spans is a runtime argument, - // so this reuses the single parse_number_string instantiation. + // so this reuses the single parse_number_string_impl instantiation. parsed_number_string_t pns = - bjf ? parse_number_string(first, last, options, false) - : parse_number_string(first, last, options, false); + bjf ? parse_number_string_impl(first, last, options, + false) + : parse_number_string_impl(first, last, options, + false); if (!pns.valid) { if (uint64_t(fmt & chars_format::no_infnan)) { answer.ec = std::errc::invalid_argument; From 7e45de0c3b7ce1d8bbb131482ce18d0978753c7b Mon Sep 17 00:00:00 2001 From: Daniel Lemire Date: Mon, 21 Sep 2026 22:05:34 -0400 Subject: [PATCH 4/6] Restore the simple loop in fastfloat_strncasecmp PR #356 replaced the 3/5-character case-insensitive compare used by parse_infnan with SWAR helpers (fastfloat_strncasecmp3/5 plus a generic memcpy-based fastfloat_strncasecmp). That code only runs for "nan", "inf" and "infinity" inputs, so it cannot help ordinary parsing, but it grew the inlined inf/nan tail of the parser: on x86-64 (GCC 14 and clang 21) the per-commit benchmarks dropped by 1.5-2.5% because the extra dead code changed inlining decisions and register allocation on the hot path (+7 instructions/float on canada.txt). Go back to the plain loop, which the compiler unrolls for the constant lengths 3 and 5, and drop the now-unused generic SWAR function. The `actual < 256` guard of the original is unnecessary: OR-ing 0x20 into a value can only equal an ASCII lowercase letter when the value is that letter or its uppercase form, so the plain OR is exact for every character type. --- include/fast_float/float_common.h | 145 +++--------------------------- include/fast_float/parse_number.h | 6 +- 2 files changed, 13 insertions(+), 138 deletions(-) diff --git a/include/fast_float/float_common.h b/include/fast_float/float_common.h index 3769972..1b2594e 100644 --- a/include/fast_float/float_common.h +++ b/include/fast_float/float_common.h @@ -325,147 +325,22 @@ struct is_supported_char_type > { }; -template -inline FASTFLOAT_CONSTEXPR14 bool -fastfloat_strncasecmp3(UC const *actual_mixedcase, - UC const *expected_lowercase) { - uint64_t mask{0}; - FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 1) { mask = 0x2020202020202020; } - else FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 2) { - mask = 0x0020002000200020; - } - else FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 4) { - mask = 0x0000002000000020; - } - else { - return false; - } - - uint64_t val1{0}, val2{0}; - if (cpp20_and_in_constexpr()) { - for (size_t i = 0; i < 3; i++) { - if ((actual_mixedcase[i] | 32) != expected_lowercase[i]) { - return false; - } - } - return true; - } else { - FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 1 || sizeof(UC) == 2) { - ::memcpy(&val1, actual_mixedcase, 3 * sizeof(UC)); - ::memcpy(&val2, expected_lowercase, 3 * sizeof(UC)); - val1 |= mask; - val2 |= mask; - return val1 == val2; - } - else FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 4) { - ::memcpy(&val1, actual_mixedcase, 2 * sizeof(UC)); - ::memcpy(&val2, expected_lowercase, 2 * sizeof(UC)); - val1 |= mask; - if (val1 != val2) { - return false; - } - return (actual_mixedcase[2] | 32) == (expected_lowercase[2]); - } - else { - return false; - } - } -} - -template -inline FASTFLOAT_CONSTEXPR14 bool -fastfloat_strncasecmp5(UC const *actual_mixedcase, - UC const *expected_lowercase) { - uint64_t mask{0}; - uint64_t val1{0}, val2{0}; - if (cpp20_and_in_constexpr()) { - for (size_t i = 0; i < 5; i++) { - if ((actual_mixedcase[i] | 32) != expected_lowercase[i]) { - return false; - } - } - return true; - } else { - FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 1) { - mask = 0x2020202020202020; - ::memcpy(&val1, actual_mixedcase, 5 * sizeof(UC)); - ::memcpy(&val2, expected_lowercase, 5 * sizeof(UC)); - val1 |= mask; - val2 |= mask; - return val1 == val2; - } - else FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 2) { - mask = 0x0020002000200020; - ::memcpy(&val1, actual_mixedcase, 4 * sizeof(UC)); - ::memcpy(&val2, expected_lowercase, 4 * sizeof(UC)); - val1 |= mask; - if (val1 != val2) { - return false; - } - return (actual_mixedcase[4] | 32) == (expected_lowercase[4]); - } - else FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 4) { - mask = 0x0000002000000020; - ::memcpy(&val1, actual_mixedcase, 2 * sizeof(UC)); - ::memcpy(&val2, expected_lowercase, 2 * sizeof(UC)); - val1 |= mask; - if (val1 != val2) { - return false; - } - ::memcpy(&val1, actual_mixedcase + 2, 2 * sizeof(UC)); - ::memcpy(&val2, expected_lowercase + 2, 2 * sizeof(UC)); - val1 |= mask; - if (val1 != val2) { - return false; - } - return (actual_mixedcase[4] | 32) == (expected_lowercase[4]); - } - else { - return false; - } - } -} - -// Compares two ASCII strings in a case insensitive manner. +// Compares two ASCII strings in a case insensitive manner. The expected +// string is lowercase ASCII, so OR-ing 0x20 into each actual character maps +// 'A'..'Z' onto 'a'..'z' and leaves everything else mismatched. The lengths +// used are tiny constants (3 and 5), so the compiler unrolls this loop; keep +// it small so that the (rarely executed) inf/nan path does not bloat the hot +// parser it is inlined into. template inline FASTFLOAT_CONSTEXPR14 bool fastfloat_strncasecmp(UC const *actual_mixedcase, UC const *expected_lowercase, size_t length) { - uint64_t mask{0}; - FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 1) { mask = 0x2020202020202020; } - else FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 2) { - mask = 0x0020002000200020; - } - else FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 4) { - mask = 0x0000002000000020; - } - else { - return false; - } - - if (cpp20_and_in_constexpr()) { - for (size_t i = 0; i < length; i++) { - if ((actual_mixedcase[i] | 32) != expected_lowercase[i]) { - return false; - } + for (size_t i = 0; i < length; ++i) { + if ((actual_mixedcase[i] | 32) != expected_lowercase[i]) { + return false; } - return true; - } else { - uint64_t val1{0}, val2{0}; - size_t sz{8 / (sizeof(UC))}; - for (size_t i = 0; i < length; i += sz) { - val1 = val2 = 0; - sz = sz < (length - i) ? sz : length - i; - ::memcpy(&val1, actual_mixedcase + i, sz * sizeof(UC)); - ::memcpy(&val2, expected_lowercase + i, sz * sizeof(UC)); - val1 |= mask; - val2 |= mask; - if (val1 != val2) { - return false; - } - } - return true; } + return true; } #ifndef FLT_EVAL_METHOD diff --git a/include/fast_float/parse_number.h b/include/fast_float/parse_number.h index 14d077b..febfdc7 100644 --- a/include/fast_float/parse_number.h +++ b/include/fast_float/parse_number.h @@ -35,7 +35,7 @@ from_chars_result_t ++first; } if (last - first >= 3) { - if (fastfloat_strncasecmp3(first, str_const_nan())) { + if (fastfloat_strncasecmp(first, str_const_nan(), 3)) { answer.ptr = (first += 3); value = minusSign ? -std::numeric_limits::quiet_NaN() : std::numeric_limits::quiet_NaN(); @@ -54,9 +54,9 @@ from_chars_result_t } return answer; } - if (fastfloat_strncasecmp3(first, str_const_inf())) { + if (fastfloat_strncasecmp(first, str_const_inf(), 3)) { if ((last - first >= 8) && - fastfloat_strncasecmp5(first + 3, str_const_inf() + 3)) { + fastfloat_strncasecmp(first + 3, str_const_inf() + 3, 5)) { answer.ptr = first + 8; } else { answer.ptr = first + 3; From b57a12270e44529dd3bd71d4320ca13aaeddb813 Mon Sep 17 00:00:00 2001 From: Daniel Lemire Date: Mon, 21 Sep 2026 22:19:35 -0400 Subject: [PATCH 5/6] Fold the format at compile time under clang, mark cold checks unlikely Clang generated ~35% more instructions per float than GCC on identical code (canada.txt, 64-bit: 276 vs 200 i/f on a Xeon Gold 6548N). Two causes, confirmed with exact instruction traces: 1. Clang declines to inline the parser (from_chars_caller::call) into its callers, so parse_options stays a runtime value and every format flag is re-tested on every conversion: javascript, skip_white_space, allow_leading_plus, fixed/scientific, the decimal point, the JSON dispatch. GCC inlines the whole parser into each call site, where chars_format::general is a constant, and all of it folds away. Fix: from_chars dispatches chars_format::general to a from_chars_fixed_format instantiation, so the format is a compile-time constant inside the parser body whether or not the user's call is inlined. The call forwarder gets fastfloat_clang_really_inline so that it folds into that instantiation. 2. Clang if-converts the rare over/underflow fix-ups at the end of compute_float and the result_out_of_range test into cmov chains that every conversion executes. Marking them fastfloat_clang_unlikely keeps them as never-taken branches. Both are applied under clang only, and GCC's generated code is identical to before (verified on the object code). That is on purpose: forcing always_inline on from_chars, or even on the trivial call forwarder, regressed GCC by up to 14% on mesh.txt by changing its inlining order; dispatching to the fixed-format instantiation made it stop inlining into the loop; and the unlikely hints alone cost it 2-6% on mesh.txt by reordering blocks (GCC already emits branches there). realbenchmark, cycles per float, 5 interleaved rounds, medians: clang 21, Xeon Gold 6548N before after canada.txt ASCII (64) 49.7 44.6 -10% canada.txt UTF-16 (64) 57.4 52.0 -9% mesh.txt ASCII (64) 26.5 22.4 -16% mesh.txt UTF-16 (64) 28.1 24.0 -15% (32-bit: -8% to -14%) gcc 14, same machine: generated code unchanged. Apple clang 17, arm64: +3% to +18% Mfloat/s. --- include/fast_float/decimal_to_binary.h | 19 ++++++++++-- include/fast_float/float_common.h | 21 +++++++++++++ include/fast_float/parse_number.h | 42 ++++++++++++++++++++------ 3 files changed, 71 insertions(+), 11 deletions(-) diff --git a/include/fast_float/decimal_to_binary.h b/include/fast_float/decimal_to_binary.h index 9487682..5c3b5d1 100644 --- a/include/fast_float/decimal_to_binary.h +++ b/include/fast_float/decimal_to_binary.h @@ -194,16 +194,31 @@ compute_float(int64_t q, uint64_t w) noexcept { answer.mantissa += (answer.mantissa & 1); // round up answer.mantissa >>= 1; - if (answer.mantissa >= (uint64_t(2) << binary::mantissa_explicit_bits())) { + // Both fix-ups below are rare. They are marked unlikely so that clang keeps + // them as branches instead of folding them into conditional moves that + // every conversion pays for. +#ifdef __clang__ +#pragma clang diagnostic push +#if (!defined(__APPLE_CC__) && __clang_major__ >= 10) || (__clang_major__ >= 13) +#pragma clang diagnostic ignored "-Wc++20-extensions" +#endif +#endif + if fastfloat_clang_unlikely (answer.mantissa >= + (uint64_t(2) + << binary::mantissa_explicit_bits())) { answer.mantissa = (uint64_t(1) << binary::mantissa_explicit_bits()); answer.power2++; // undo previous addition } answer.mantissa &= ~(uint64_t(1) << binary::mantissa_explicit_bits()); - if (answer.power2 >= binary::infinite_power()) { // infinity + if fastfloat_clang_unlikely (answer.power2 >= binary::infinite_power()) { + // infinity answer.power2 = binary::infinite_power(); answer.mantissa = 0; } +#ifdef __clang__ +#pragma clang diagnostic pop +#endif return answer; } diff --git a/include/fast_float/float_common.h b/include/fast_float/float_common.h index 1b2594e..9a84383 100644 --- a/include/fast_float/float_common.h +++ b/include/fast_float/float_common.h @@ -228,6 +228,27 @@ using parse_options = parse_options_t; #define fastfloat_never_inline #endif +// fastfloat_really_inline under clang only, a no-op elsewhere. Clang declines +// to inline the parser into its callers, so the parser instantiation with a +// compile-time format (from_chars_fixed_format) must force the one thin +// forwarder between it and the parser body. GCC inlines the chain on its own, +// and forcing it there changes its inlining order for the worse. +#ifdef __clang__ +#define fastfloat_clang_really_inline fastfloat_really_inline +#else +#define fastfloat_clang_really_inline +#endif + +// fastfloat_unlikely under clang only, a plain condition elsewhere. Clang +// if-converts rare checks into chains of conditional moves that every +// conversion executes; the hint keeps them as branches. GCC already emits +// branches there, and the hint only reorders its blocks, for the worse. +#ifdef __clang__ +#define fastfloat_clang_unlikely(x) fastfloat_unlikely(x) +#else +#define fastfloat_clang_unlikely(x) (x) +#endif + // Branch-probability hint marking the rare slow-path branches as cold, so the // optimizer keeps the out-of-line slow-path re-parse off the hot path (and does // not duplicate the force-inlined hot scanner into the caller, which bloated diff --git a/include/fast_float/parse_number.h b/include/fast_float/parse_number.h index febfdc7..315a438 100644 --- a/include/fast_float/parse_number.h +++ b/include/fast_float/parse_number.h @@ -139,9 +139,10 @@ fastfloat_really_inline bool rounds_to_nearest() noexcept { template struct from_chars_caller { template - FASTFLOAT_CONSTEXPR20 static from_chars_result_t - call(UC const *first, UC const *last, T &value, - parse_options_t options) noexcept { + fastfloat_clang_really_inline + FASTFLOAT_CONSTEXPR20 static from_chars_result_t + call(UC const *first, UC const *last, T &value, + parse_options_t options) noexcept { return from_chars_advanced(first, last, value, options); } }; @@ -180,10 +181,29 @@ template <> struct from_chars_caller { }; #endif +#ifdef __clang__ +// Parser instantiated for a format fixed at compile time, so that every test +// on the format folds away inside it. GCC gets the same effect by inlining the +// whole parser into each caller, where the format is a constant; clang keeps +// it out of line and would otherwise re-test each format flag per conversion. +template +FASTFLOAT_CONSTEXPR20 from_chars_result_t +from_chars_fixed_format(UC const *first, UC const *last, T &value) noexcept { + return from_chars_caller::call(first, last, value, + parse_options_t(Fmt)); +} +#endif + template FASTFLOAT_CONSTEXPR20 from_chars_result_t from_chars(UC const *first, UC const *last, T &value, chars_format fmt /*= chars_format::general*/) noexcept { +#ifdef __clang__ + if (fmt == chars_format::general) { + return from_chars_fixed_format(first, last, + value); + } +#endif return from_chars_caller::call(first, last, value, parse_options_t(fmt)); } @@ -428,15 +448,19 @@ from_chars_float_advanced(UC const *first, UC const *last, T &value, if fastfloat_unlikely (am.power2 < 0) { return parse_number_slow_path(first, last, value, options, bjf); } + to_float(pns.negative, am, value); + // Test for over/underflow. Marked unlikely so that clang keeps it as a + // branch instead of folding it into a chain of conditional moves that + // every conversion pays for. + if fastfloat_clang_unlikely ((pns.mantissa != 0 && am.mantissa == 0 && + am.power2 == 0) || + am.power2 == + binary_format::infinite_power()) { + answer.ec = std::errc::result_out_of_range; + } #ifdef __clang__ #pragma clang diagnostic pop #endif - to_float(pns.negative, am, value); - // Test for over/underflow. - if ((pns.mantissa != 0 && am.mantissa == 0 && am.power2 == 0) || - am.power2 == binary_format::infinite_power()) { - answer.ec = std::errc::result_out_of_range; - } return answer; } From 82623d83c50048c5b74771e2545886df6a9042f1 Mon Sep 17 00:00:00 2001 From: Daniel Lemire Date: Tue, 22 Sep 2026 13:57:31 -0400 Subject: [PATCH 6/6] Avoid right-shifting a negative value in subnormal_ties_possible() --- include/fast_float/float_common.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/include/fast_float/float_common.h b/include/fast_float/float_common.h index 76d94b3..bcef8d8 100644 --- a/include/fast_float/float_common.h +++ b/include/fast_float/float_common.h @@ -1117,11 +1117,12 @@ inline constexpr bool binary_format::fast_path_can_overflow() { // A subnormal needs w * 10^q < 2^(minimum_exponent() + 1), so q is at most // (minimum_exponent() + 1) * log10(2), with 1233/4096 < log10(2). Only -// std::float16_t has such q in its round-to-even range. +// std::float16_t has such q in its round-to-even range. We compare +// 4096 * q with (minimum_exponent() + 1) * 1233 to avoid right-shifting a +// negative value (implementation-defined before C++20). template inline constexpr bool binary_format::subnormal_ties_possible() { - return min_exponent_round_to_even() <= - (((minimum_exponent() + 1) * 1233) >> 12); + return min_exponent_round_to_even() * 4096 <= (minimum_exponent() + 1) * 1233; } template <>