Skip to content

Faster conversion of Float32 and Float64 to 128- and 256-bit integers and decimals - #129274

Merged
Algunenano merged 2 commits into
ClickHouse:masterfrom
groeneai:wide-integer-from-float-keep-result-in-registers
Nov 13, 2026
Merged

Algunenano merged 2 commits into
ClickHouse:masterfrom
groeneai:wide-integer-from-float-keep-result-in-registers

Conversation

@groeneai

@groeneai groeneai commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Faster conversion of Float64 values to Int128, UInt128, Int256, UInt256, Decimal128 and Decimal256. For example, toDecimal128(x, 6) of a Float64 column is about 4x faster on x86-64.

Description

Asked on #119542: decimal_casts query #7 (toFloat32(x) to Decimal32/64/128) was 19.9% slower in Performance Comparison (arm_release, master_head, 2/6). That PR is not the cause. Master itself got about 8% slower on ARM at #126191, and some builds 13-20%.

Since #126191, a float of magnitude >= 2^63 goes through wide_integer_from_builtin(self, double), which passes self by reference to set_multiplier, a recursive function that is never inlined. When this is inlined into a column loop (convertToDecimalBatch, ConvertImpl), every row's result goes through a stack temporary: it is zeroed, written with two 8-byte stores and reloaded. The double overload already did this for Float64, and on aarch64 its long double range check also called __extenddftf2 and __lttf2 for every row.

Now the double overload checks the Int64 range in double and converts in-range values directly. This accepts the same values as the old long double check, because no double lies in [2^63 - 1, 2^63). Other values go to a NO_INLINE helper that holds the old code and returns the integer by value. Float32 and BFloat16 go through the double overload.

Results are byte-identical to master for all 2^32 Float32 and 2^16 BFloat16 bit patterns and about 4.7e9 Float64 inputs, checked on x86-64 and on aarch64 under qemu. In the codegen of both architectures, the in-range path stores the result straight from registers. On x86-64 (8 threads, 200M rows), toDecimal128(toFloat64(x), 6) goes from 0.33 to 0.07 s, toInt128(toFloat32(x)) from 0.31 to 0.07 s, and query #8 from 0.37 to 0.20 s. Values that are >= 2^63 after the decimal scale is applied (for example Decimal(38, 18) from 9.23 up) are 5-8% slower on x86-64, with the same instruction count.


Workflow [PR]
Sync PR [sync-upstream/pr/129274]

Version info

  • Merged into: 26.11.1.2194-master (included in 26.11 and later)

groeneai and others added 2 commits November 4, 2026 12:24
Since ClickHouse#126191, `wide_integer_from_builtin(self, float)` falls back to the
`double` overload for |x| >= 2^63. That overload passes `self` by reference
to `set_multiplier`, which is recursive and never inlined, so wherever it is
inlined into a batch loop (`convertToDecimalBatch`, `ConvertImpl`) the result
of every row goes through a stack temporary: zeroed, written with two 8-byte
stores and read back with a 16-byte load. On arm that made `decimal_casts`
query ClickHouse#7 (Float32 -> Decimal128) about 8% slower on master, and 13-20% slower
in builds where that temporary lands at 24 mod 64 (16 of 16 such CI builds).

The `double` overload now checks the int64 range in `double` and converts the
in-range value directly; the rest goes to a `NO_INLINE` helper that returns
the integer by value, so the caller's result stays in registers. The range
check accepts exactly the same set of `double` values as the old
`long double` one (no `double` lies in [2^63 - 1, 2^63)), and on aarch64 it
no longer calls `__extenddftf2` + `__lttf2` per row. `float` and `BFloat16`
now go through `double`, which converts them like the same value as
`Float64` by construction.

Results are unchanged: all 2^32 Float32 patterns, all BFloat16 patterns and
~4.7e9 Float64 inputs (6.5e8 on aarch64) convert to the same
Int128/UInt128/Int256/UInt256 bytes as before, on x86-64 and aarch64.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Say that the in-range cast truncates rather than converts exactly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings, both nits) plus my own review (3 nits, two of them the same).

# Sev Finding Verdict Evidence / action
1 💡 On arm64 macOS an in-range float is no longer constant-evaluable (wide_integer_impl.h:598-606, :722-726) AGREE, not blocking Nothing in src/, base/, programs/ constant-evaluates a float to a wide integer; one would fail to compile in Build (arm_darwin).
2 💡 The fast-path comment says "converts exactly", the cast truncates (:728) AGREE Comment reworded.
3 💡 Values >= 2^63 after the decimal scale are 5-8% slower on x86-64 AGREE, accepted Same instructions per query, lower IPC; an isolated microbenchmark is at parity. Stated in the description.

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-9:20261104-132200

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Compiling src/DataTypes/DataTypesDecimal.cpp with the master header shows the per-row stack temporary in convertToDecimalBatch<Float32, Decimal128> on aarch64 (stp xzr, xzr + two stur + ldur q0), the same plus per-row __extenddftf2/__lttf2 for Float64, and an out-of-line call per row for Float64 on x86-64. Timing on x86-64: toDecimal128(toFloat64(x), 6) 0.33 s vs 0.07 s in every round. ARM timing comes from this PR's perf CI.
b Root cause explained? Since #126191, float values >= 2^63 use the double overload, which passes self by reference to the never-inlined set_multiplier, so the inlined column loop keeps every row's result in a stack temporary.
c Fix matches root cause? Yes. The in-range path no longer reaches set_multiplier; the rest goes to an out-of-line helper returning by value. No guard at the call site.
d Test intent preserved / new tests added? No new test: behaviour is unchanged and byte-identical (row e/g). decimal_casts #7 and #8 measure both shapes in the perf CI.
e Both directions demonstrated? Codegen with and without the change on both architectures, and the x86-64 timing A/B with identical build flags.
f Fix is general across code paths? One shared double overload now serves Float32, BFloat16, Float64 and 8-byte long double, for all four wide::integer instantiations and every entry point (integer(T), operator=, initializer lists); convertToDecimalBatch (plain and null-map) and ConvertImpl checked.
g Fix generalizes across inputs (params/datatypes/wrappers)? Same Int128/UInt128/Int256/UInt256 bytes as master for all 2^32 Float32 and 2^16 BFloat16 patterns, specials (+-0, +-2^63 and neighbours, +-inf, NaN, denormals), 3.8e8 inputs around 2^50..2^140 and 2^32 random doubles; aarch64 under qemu too.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or stored data change; results unchanged.
i Invariants and contracts preserved? The range check accepts exactly the old set (no double lies in [2^63 - 1, 2^63), NaN fails); noexcept unchanged; constant evaluability unchanged on x86-64 and aarch64 Linux (on arm64 macOS a float now follows double, which is not constexpr there; nothing constant-evaluates it); set_multiplier untouched.

Session id: cron:clickhouse-impl-slot-7:20261104-104600

@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [44a8f4c]

Summary: ✅


AI Review

Summary

PR #129274, head 44a8f4c33829, speeds up floating-point conversions to wide integers and decimals by keeping ordinary conversions inline and returning large-value conversions by value. No actionable findings were identified in the current diff. The supplied before/after measurements support the performance claim.

Missing context / blind spots
  • ⚠️ Performance measurements and exhaustive equivalence checks are author-reported; they were not independently reproduced. This checkout has no configured ClickHouse build or clickhouse executable, and the performance dashboard currently lists no runs for this PR. Completed performance CI on x86-64 and aarch64 would provide independent confirmation.
Final Verdict

Status: ✅ Approve. No new inline findings to post.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 4, 2026
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @thevar1able, could you review this and add the can be tested label so CI runs? wide_integer_from_builtin(self, double), which Float32 uses since #126191, passes self by reference to the never-inlined set_multiplier, so column loops such as convertToDecimalBatch keep every row's result in a stack temporary; now in-range values convert directly and the rest goes to a NO_INLINE helper that returns by value.

@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). labels Nov 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 44a8f4c33 with master e0f4bac26 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

4281 translation units recompiled, 20910 s compile time in total, 4279 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 8.2 s

Job report

@Algunenano Algunenano self-assigned this Nov 11, 2026
@Algunenano
Algunenano added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit 3f94ba5 Nov 13, 2026
549 of 551 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants