Skip to content

Inline divide into the signed wide-integer division operators - #127761

Merged
Algunenano merged 2 commits into
ClickHouse:masterfrom
groeneai:wide-integer-narrow-division-in-registers
Nov 4, 2026
Merged

Algunenano merged 2 commits into
ClickHouse:masterfrom
groeneai:wide-integer-narrow-division-in-registers

Conversation

@groeneai

@groeneai groeneai commented Oct 25, 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):

Integer division of signed 256-bit integers (for example intDiv on Int256 values) is faster when both operands fit in 64 bits.

Description

Related: #112928 (comment)

bigint_arithm #7 (intDiv(toInt256(number + 1), number + 1)) runs at one of several per-binary speeds on arm_release: 0.15 s or 0.18-0.20 s with the same machine code (84 of 1580 arm binaries in 30 days were always slow, master itself twice with unrelated commits), which makes the performance check red on unrelated PRs (example).

The signed 256-bit operator_slash / operator_percent are out of line, and divide was a second out-of-line call below them. So even a division whose operands fit in one limb passed its three 32-byte operands through the stack, and its speed followed the stack placement: in the pairs I measured, a slow binary differs from its fast reference only in the TLS size or in one caller's frame size, and the whole gap is self time of divide<256>.

The call to divide in the signed operators now carries [[clang::always_inline]], so a narrow signed division stays in registers and the general path calls divide_knuth directly. divide itself, the unsigned operators (inlined into their callers, and too large for that if they carried the division) and 128-bit division are unchanged, with machine code identical to master on x86. SQL % on Int256 divides unsigned magnitudes (ModuloImpl), so it keeps master's code too.

Validation: x86 microbenchmark, ratio to master: Int256 narrow / 0.50, narrow % 0.50, 4-limb by 1-limb 0.28, 4-limb by 2-limb 0.64; unsigned 256/512-bit and 128-bit kernels 0.99-1.005. In aarch64 objects the narrow paths of the signed operators touch no stack slot beyond the prologue and epilogue. The arm effect on bigint_arithm #7 can only be shown by this PR's own performance check. No test change: every result still comes from master's divide body, which the existing exact-oracle sweeps in gtest_wide_integer.cpp cover; bigint_arithm query #7 is the performance test.

🤖 Generated with Claude Code


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

Version info

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

The signed 256-bit `/` and `%` operators (`operator_slash` / `operator_percent`
of `wide::integer<256, signed>`) are out of line in release builds (the arm CI
binary of ClickHouse#112928 has 812 and 61 call sites), and `divide` was a second
out-of-line call below them. So even a division whose operands fit in one limb,
which `divide` does with one native division, passed its three 32-byte operands
(numerator by reference, denominator by value, quotient through the result
pointer) through the stack, at 8 mod 16 in the operator's frame. On arm the speed
of `bigint_arithm` query ClickHouse#7 (`intDiv(toInt256(number + 1), number + 1)`)
followed the stack placement: the same machine code ran at 0.15 s or at
0.18-0.20 s depending on the binary (84 of 1580 arm binaries in 30 days were
always slow; master d5bdd58 and 6a36363 differ only in the size of
PT_TLS, by 64 bytes; on ClickHouse#112928 the ThreadPool worker frame is 32 bytes larger),
and the whole difference was self time of `divide<256>` (978 -> 3069 samples).

Now the call to `divide` in the signed operators carries
`[[clang::always_inline]]`, so `divide`'s body, narrow branches included, is
part of the operator: a narrow division stays in registers, and the general
path calls `divide_knuth` directly. The unsigned operators and `divide` itself
are unchanged: the unsigned operators are inlined into their callers and keep
their plain call to the out-of-line `divide`, because carrying the division
makes them too large to inline (measured +45% for a 1-limb by 2-limb `UInt256`
division).

Measured on x86 (microbenchmark, 2^24 divisions per kernel, median of 3 runs of
11 interleaved rounds, ratio to master): `Int256` narrow `/` 0.500, narrow `%`
0.501, 4-limb by 1-limb 0.281, 4-limb by 2-limb 0.637, 1-limb by multi-limb `%`
0.541; the `UInt256`, `UInt512`, `Int128` and `UInt128` kernels 0.990-1.005,
and the unsigned `divide<256>` / `divide<512>` and the 128-bit kernels are
machine-code identical to master. aarch64 objects (`intDiv.cpp.o`,
`modulo.cpp.o`): the narrow paths of the signed operators touch no stack slot
beyond the prologue/epilogue pairs and the stack guard, the call sites of the
operators are unchanged, `.text` grows by 696 and 740 bytes.

Related: ClickHouse#112928

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)
Finding Verdict
⚠️ The added exact-oracle sweep passes on master and on a revert (the change only affects inlining) AGREE, fixed: the sweep is removed; the PR is header-only, the existing sweeps cover the results and bigint_arithm #7 measures the speed
💡 PR description did not say that SQL % on Int256 (unsigned magnitudes) keeps master's code AGREE, fixed in the description

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? No arm host, so the oracle is static plus x86 timing: in aarch64 objects built like CI, the narrow path of operator_slash<Int256> calls divide<256> with its operands in 8-mod-16 stack slots before the change and stays in registers after it; x86 narrow Int256 division 0.365 s -> 0.182 s per 2^24 calls.
b Root cause explained? A narrow signed Int256 division made a second out-of-line call (operator_slash -> divide) with three 32-byte operands on the stack; on arm the cost of those accesses follows the stack placement, which unrelated changes (TLS size, a caller frame) move.
c Fix matches root cause? Yes: the call is inlined into the signed operators, so the narrow case makes no call. No bound, tag or harness change.
d Test intent preserved / new tests added? No test added or changed: results are bit-identical by construction (master's divide body, inlined) and covered by the existing exact-oracle sweeps; bigint_arithm.xml query #7 measures the speed.
e Both directions demonstrated? Static and timing before/after as in (a); WideInteger.* passes.
f Fix is general across code paths? Both signed operators (/, %); 128-bit and unsigned 256/512-bit keep master's machine code on purpose (unsigned operators must stay inlinable); there is no signed 512-bit type.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured over 13 kernels (128/256/512 bits, signed and unsigned, narrow to multi-limb, both signs).
h Backward compatible? (maintainer-approved exception only) Yes: no setting or format change, results are bit-identical (same function body).
i Invariants and contracts preserved? divide's body is unchanged (zero divisor throws first, remainder left in the numerator); constant evaluation still compiles; the attribute adds no symbol.

Session id: cron:clickhouse-impl-slot-4:20261025-004200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @thevar1able @Algunenano, could you review this and add the can be tested label so CI runs? The signed Int256 / and % operators are out of line and called divide as a second out-of-line call, so even a one-limb division passed three 32-byte operands through the stack and its speed on arm followed the stack placement (bigint_arithm #7); the call is now inlined into the signed operators only, and unsigned and 128-bit code is unchanged.

@clickhouse-gh

clickhouse-gh Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e5c2767]

Summary: ✅


AI Review

Summary

PR #127761 forces divide to inline into signed wide-integer division and remainder operators, preserving the arithmetic algorithm and unsigned paths. No actionable findings at head e5c27677b9e284f22e8e8d7473490f98b4508782. The performance run from 2026-10-25 uses an identical wide_integer_impl.h and measures query 7 improving from 0.1525 s to 0.1141 s on ARM and from 0.3968 s to 0.2403 s on x86. Existing arithmetic and constant-evaluation coverage is appropriate for this inlining-only change.

Final Verdict

✅ Approve. No new inline findings to post.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 25, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d0023b1

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (arm_binary, 3/4) / test_scheduler_cpu_parking/test.py::test_parking_fires_on_idle_worker flaky, not from this PR (it changes only signed wide-integer division in base/base/wide_integer_impl.h): expected parks > 0, got 0, the idle-worker park never fired during the sleepEachRow serial phase a fix task is created (investigating at full effort, fixing-PR link to follow here)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / Some queries hung not from this PR: the parallel-replicas secondary query of 04117_detach_database_kill_query (sleepEachRow(3), is_cancelled = 0, 175 s) outlived the KILL of its initial query, the same hung query as on many unrelated PRs since 2026-10-21 #127149 (mine, open)
Upgrade check (amd_release) / Changed settings are not reflected in the settings changes history (see changed_settings.txt) not from this PR (it does not touch settings): v26.10.2.103-stable ships use_query_condition_cache_for_time_conditions = false after #127632, while the master this head was tested on still says its default became true in 26.10. The fix merged at 11:26Z, after this run started, and is absent from the tested merge commit #127687 (mine, merged)
Mergeable Check, PR praktika rollups of the rows above #127149, #127687 and a fix task is created for the first row (the owners of the rows above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261025-133007

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for test_scheduler_cpu_parking::test_parking_fires_on_idle_worker created: #127780

opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Oct 26, 2026
The test needs a serial sleepEachRow(0.5) phase in which the other
pipeline workers have no task and park their CPU lease in the idle
wait. The outer aggregate was count(), which reads no column, so the
analyzer's RemoveUnusedProjectionColumnsPass removed both sleepEachRow
projections and the query read 90 numbers in a few milliseconds. The
test then passed only when a second worker happened to reach the idle
wait before the query ended, and failed with 0 parks otherwise
(Integration tests (arm_binary, 3/4) on PR ClickHouse#127761). CIDB: 5391 OK
runs in 30 days with a median test time of 437 ms, so the sleeps never
ran in CI.

Read the sleep column with sum(s) so the sleeps are kept (about 7 s,
the idle window the comment describes), and assert SleepFunctionCalls
== 90 before the parks asserts so the test fails if the premise is
ever optimized away again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Algunenano Algunenano self-assigned this Oct 26, 2026
@Algunenano
Algunenano enabled auto-merge November 4, 2026 16:06
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e5c27677b with master 989ecd896 (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

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

Translation units without a recent master baseline:

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

Job report

@Algunenano
Algunenano added this pull request to the merge queue Nov 4, 2026
Merged via the queue into ClickHouse:master with commit 9556805 Nov 4, 2026
185 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 4, 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 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.

4 participants