Skip to content

Build with -fzero-call-used-regs=used-gpr - #127995

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:build-fzero-call-used-regs
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:build-fzero-call-used-regs

Conversation

@groeneai

@groeneai groeneai commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #127959

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

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

Build with -fzero-call-used-regs=used-gpr on x86-64 and AArch64, so that a function clears the general purpose registers it used before it returns, and its epilogue cannot hand their values to a return-oriented programming chain.

Description

This is the first of the three items of #127959; the other two are handled separately, so that each one is measured on its own.

-fzero-call-used-regs=used-gpr goes into COMPILER_FLAGS after -fstack-clash-protection, so it reaches src/, programs/, base/ and contrib (except contrib/compiler-rt-cmake, which resets flags to an allowlist). It is set only for x86-64 and AArch64: clang 22 rejects it for powerpc64le, riscv64, s390x, loongarch64 and wasm64. Builds with SANITIZE or ENABLE_FUZZING set do not get it: they are not shipped, and the MSan and fuzzer images are already close to the 2 GiB reach of 32-bit PC-relative references.

Every return path now zeroes all the caller-saved general purpose registers that the function uses anywhere, and many functions that returned from several places now branch to one shared exit. src/Common/remapExecutable.cpp only gains xors before its rets, and the memcpy dispatch stays a frameless tail jmp. No query can observe the change, so no test is added; in a 5% slice of the stateless tests, no test fails with the flag and passes without it.

Performance Comparison (b4fae47 plus this change against b4fae47): arm_release geomean +0.78% over 4,190 queries (+0.67% to +1.00% per shard), slower encrypt_decrypt #2 +17%, general_purpose_hashes_on_UUID #7 +16%, bigint_formatting #4 +16%, json_to_string #1 +69% (noisy: 142 other PRs in 30 days); amd_release +0.57% over 4,186 queries (+0.43% to +0.71%), slower set_in_clustered_keys #0 +26%, uint64_to_string #2 +20%, trim_numbers #2 +18%, faster uint64_to_string #5 -25%. Except json_to_string, all reproduce locally with the CI x86-64 binaries (+7% to +21%, and -25%); perf puts the difference in per-row functions whose returns now zero registers, mostly at one shared exit: OpenSSL EVP, farmHash64, itoa/toChars, bcmp, and pow for the faster one.

CI binary size: compressed +0.17% (x86-64) and +0.31% (AArch64), .text +0.78% and +2.29%.

Per-function zeroing, local numbers, largest slowdowns
  • Zeroing before the shared ret on AArch64 (CI binaries): farmhashxo::Hash64 17 mov xN, #0 (7 returns merged into 1), itoa(UInt128) 15 (9 into 1), CityHash64 17 (7 into 1; its 9 to 16 byte path is 22 instructions), OpenSSL CRYPTO_ctr128_encrypt_ctr32 16, evp_cipher_init_internal 12, EVP_EncryptUpdate 6. On x86-64, farmhashxo::Hash64, itoa(UInt128) and CityHash64 get 6 to 8 xors. The set is computed over the whole function (insertZeroCallUsedRegs in LLVM's PrologEpilogInserter.cpp).
  • Local x86-64, CI binaries, one thread, median of 9 runs: encrypt('aes-128-ctr', ...) +7.0%, farmHash64(generateUUIDv4()) +10.6%, toString(toUInt128(number)) +20.8%, cityHash64(toDecimal128(number, 23)) +22.1%, set_in_clustered_keys #0 +19.4%, uint64_to_string Repair subtree2 #2 +14.3%, trim_numbers Repair subtree2 #2 (100M rows) +13.8%, uint64_to_string Extra include for std::mt19937_64 #5 -24.7%; controls -2.8% to +0.5%. perf: bcmp 821 to 1,596 samples (FixedSizeKeySlices::rowsEqual calls memcmp per row); avx512ifma::toChars (3 returns into 1, 8 xors) +18% to +41%, itoa(UInt64) (7 into 1) +50% to +65%; pow 2,935 to 1,733 (2 returns into 1, 9 xors; I have not established why it is faster).
  • Five largest slowdowns, flagged or not: arm_release json_to_string Repair subtree2 #1 +69%, index_bulk_filtering Repair subtree2 #2 +29%, consistent_hashes #0 +27% (unstable), array_compact Repair subtree2 #2 +26%, consistent_hashes Repair subtree2 #2 +26% (unstable); amd_release set_in_clustered_keys #0 +26%, distinct_in_order doc: fix typo #4 +25%, split_filter #0 +24%, uint64_to_string Repair subtree2 #2 +20%, general_purpose_hashes_on_UUID Repair subtree2 #1 +19%. A re-run of four arm_release shards gave +0.90% over 2,695 queries; it flagged general_purpose_hashes_on_UUID fix docs #6 +25% (farmHash64 again).

🤖 Generated with Claude Code


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

A function now clears the general purpose registers it used before it
returns, so its epilogue cannot hand their values to a return-oriented
programming chain. The flag goes into COMPILER_FLAGS next to the stack
protector, so it reaches src/, programs/, base/ and contrib, including
libc++, libunwind and the glibc compatibility layer.

It is set only for x86-64 and AArch64: clang 22 rejects it for
powerpc64le, riscv64, s390x, loongarch64 and wasm64. Sanitizer and fuzzer
builds do not get it: they are not shipped, and their images are already
close to the 2 GiB reach of 32-bit PC-relative references.
contrib/compiler-rt-cmake resets inherited flags to an allowlist, so the
builtins stay out, as they do for the stack protector.

In a local build with the amd_release PR configuration, 17285 of 17643
compile commands carry the flag (the rest are compiler-rt and the NASM
sources of isa-l), and the MSan, ASan+UBSan, fuzzer and riscv64
configurations carry it nowhere. In the linked ThinLTO binary 72.9% of
`ret` instructions follow a register-zeroing `xor`, against 1.2% without
the flag. Return blocks that grow past LLVM's tail-duplication threshold
are no longer copied into their predecessors, so some functions (for
example `memcmp` and `bcmp`) now reach one shared exit through a `jmp`.
`.text` grows by 4.1 MB (+0.78%), the compressed binary by 0.46 MB
(+0.16%).

Related: ClickHouse#127959

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

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 runs on this tree, the second after the description was narrowed) plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ No Performance Comparison numbers yet (CMakeLists.txt:450) DISAGREE The numbers come from this PR's own CI (amd_release and arm_release), which is why it is a draft; they go into the description before it can leave draft.
2 💡 amd_cfi (no SANITIZE) gets the flag, so "sanitizer builds are not affected" was imprecise AGREE, description fixed The description now names the SANITIZE/ENABLE_FUZZING condition and amd_cfi; the condition is unchanged.
3 💡 Only the MSan and fuzzer images are measured close to the 2 GiB reach AGREE, description fixed The description names those two.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-48:20261027-184000

@groeneai
groeneai marked this pull request as draft October 27, 2026 19:12
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? N/A for a defect: a requested hardening flag. The deterministic observable is codegen: the compile_commands.json census and the share of ret instructions that follow a register-zeroing xor (1.2% without the flag, 72.9% with it), both reproducible on every build.
b Root cause explained? Clang sets "zero-call-used-regs"="used-gpr" on every function (it survives ThinLTO), and LLVM's prologue/epilogue inserter zeroes, in each return block, every caller-saved general purpose register the function wrote that is not live out. Side effect: longer return blocks are no longer tail-duplicated, so some return paths jump to one shared exit.
c Fix matches root cause? Yes: the flag goes into COMPILER_FLAGS next to the stack protector, as the issue asks; gated to the two architectures clang supports; sanitizer and fuzzer builds excluded; no per-function opt-outs or layout knobs without a measured slower query.
d Test intent preserved / new tests added? No test: a register's content after ret is not observable by a query. Validation is codegen, a stateless slice A/B, CI and Performance Comparison.
e Both directions demonstrated? Base build: flag in 0 of 17,643 compile commands, 1.2% zeroed returns; flag build: 17,285 of 17,643, 72.9%.
f Fix is general across code paths? Configurations censused: release, debug, arm, musl, MSan, ASan+UBSan, fuzzers, riscv64; Darwin, FreeBSD and amd_cfi get the flag by the same condition and are covered by their CI builds. our_syscall and remapToHugeStep2/3 only gain zeroing before ret; memcpy/memmove/memset/memcmp/bcmp and 49 musl early-init functions add no stack access, call or relocation.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A (no input-dependent behaviour). x86-64 measured locally; AArch64 by the arm_release build and Performance Comparison.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or protocol change.
i Invariants and contracts preserved? Code that depends on its exact frame keeps it, the CPU dispatch stays a frameless tail call, musl early init gains no call or relocation, compiler-rt keeps its flag allowlist, and sanitizer builds are unchanged.

Session id: cron:clickhouse-impl-slot-5:20261027-183000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Algunenano @pamarcos, could you review this and add the can be tested and pr-performance labels, so that CI and Performance Comparison on both amd_release and arm_release run? It adds -fzero-call-used-regs=used-gpr to COMPILER_FLAGS on x86-64 and AArch64 (not in sanitizer or fuzzer builds), so each function clears the general purpose registers it used before it returns; the PR stays a draft until the Performance Comparison numbers are in the description.

@clickhouse-gh

clickhouse-gh Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f2cd0fc]

Summary: ❌

job_name test_name status info comment
Fast test (arm_darwin) FAIL
05227_mutate_part_ahead_of_table_metadata_version_mergetree FAIL cidb
Performance Comparison (amd_release, master_head, 2/6) FAIL Performance dashboard
set_in_clustered_keys #0 FAIL dashboard
Performance Comparison (amd_release, master_head, 4/6) FAIL Performance dashboard
uint64_to_string #3 FAIL dashboard
trim_urls #3 unstable query history
uint64_to_string #2 slower query history
Performance Comparison (arm_release, master_head, 1/6) FAIL Performance dashboard
general_purpose_hashes_on_UUID #1 FAIL dashboard
array_join_filter_fusion #6 unstable query history
general_purpose_hashes_on_UUID #6 slower query history
json_to_string #0 unstable query history
json_to_string #1 slower query history
Build profile diff ERROR

AI Review

Summary

This enables -fzero-call-used-regs=used-gpr throughout x86-64 and AArch64 builds where SANITIZE and ENABLE_FUZZING are disabled, to reduce return-oriented programming opportunities. ❌ Block: unconditional enablement exceeds the linked issue's performance budget: ordinary hashing, integer formatting, and encryption queries have repeatable slowdowns of approximately 16–17%.

Findings

❌ Blockers

  • CMakeLists.txt:451: The global flag imposes significant overhead on per-row functions, violating the requirement to enable only hardening whose cost is within noise. ARM results show encrypt_decrypt #2 +17.3%, general_purpose_hashes_on_UUID #7 +15.7%, and bigint_formatting #4 +15.7%. Hashing and formatting remain +15.9% and +11.6% slower after server restart; none has a slower result in the queried master history. Keep the flag opt-in, mitigate the measured hot paths, or obtain explicit maintainer acceptance of this performance tradeoff before unconditional enablement.
Missing context / blind spots
  • ⚠️ Fresh machine-readable ARM artifacts cover shards 1, 2, 4, and 6 (2,697 queries); shards 3 and 5 were reused from cache and were not independently included in this analysis. Their source artifacts would complete the independent aggregate measurement. The available four shards have a +0.84% geomean increase, consistent with the description's +0.78% across all six.
Tests
  • ⚠️ The requested amd_release performance comparison did not run, and its metric artifacts are absent. Run it against the same reference, and repeat both architecture comparisons for any revised configuration. The description's local x86-64 measurements already indicate +7–21% on the three affected queries.
Performance & Safety

The current Praktika reports and machine-readable metrics contain these ARM changes exceeding 10% that are classified as changed or unstable, plus the separately confirmed uint64_to_string regression. Master counts below come from default.checks, restricted to master ARM performance runs from 2026-09-28 through 2026-10-28.

Test / query Shard Slower Master slower / runs Assessment
json_to_string #1 1 69.1% 26 / 1,286 Recurrent on master; not used to establish the blocker
consistent_hashes #0 2 26.2% 0 / 1,284 Classified unstable in this run; needs verification
consistent_hashes #2 2 25.8% 0 / 1,284 Classified unstable in this run; needs verification
consistent_hashes #4 2 25.4% 0 / 1,284 Classified unstable in raw metrics, but dashboard confirmation reproduces +25.0% after restart
uint64_to_string #3 4 18.5% 0 / 1,283 Dashboard confirmation reproduces +10.0% after restart
encrypt_decrypt #2 4 17.3% 0 / 932 New regression; author also attributes it to register clearing
general_purpose_hashes_on_UUID #7 1 15.7% 0 / 192 New regression; +15.9% after restart
bigint_formatting #4 6 15.7% 0 / 1,065 New regression; +11.6% after restart

No changed-query improvements appear in the four fresh ARM shards. The additional confirmations strengthen the same global-overhead finding; they do not warrant separate inline comments.

Final Verdict

❌ Block. Address the repeatable hot-path regressions or obtain explicit maintainer acceptance of the revised performance budget, and complete the requested x86-64 and AArch64 measurements for the final configuration.

@clickhouse-gh clickhouse-gh Bot added pr-build Pull request with build/testing/packaging improvement comp-build-system Build system (CMake, compilation, platform builds). labels Oct 27, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 27, 2026
@motsc motsc added the pr-performance Pull request with some performance improvements label Oct 27, 2026
Comment thread CMakeLists.txt
# fuzzer builds: they are not shipped, and their images are already close to the 2 GiB reach of 32-bit PC-relative
# references. contrib/compiler-rt-cmake resets it like the flags above.
if ((ARCH_AMD64 OR ARCH_AARCH64) AND NOT SANITIZE AND NOT ENABLE_FUZZING)
set (COMPILER_FLAGS "${COMPILER_FLAGS} -fzero-call-used-regs=used-gpr")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ Avoid enabling register clearing unconditionally with these hot-path regressions

Adding this to COMPILER_FLAGS makes the overhead mandatory in production builds, including per-row hashing, formatting, and OpenSSL calls. The ARM comparison reports encrypt_decrypt #2 at +17.3%, general_purpose_hashes_on_UUID #7 at +15.7%, and bigint_formatting #4 at +15.7%; the latter two still regress by +15.9% and +11.6% after restarting the servers. Master history for 2026-09-28 through 2026-10-28 has zero slower results for these cases in 932, 192, and 1,065 runs respectively. This exceeds the linked issue's requirement to enable only hardening whose cost is within noise.

Please keep this behind an opt-in build option, or mitigate the measured hot paths before enabling it globally, then measure the final configuration on both architectures. Accepting these regressions instead needs an explicit maintainer decision to change that performance budget.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f2cd0fc

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
Build profile diff infra, not from this PR: the CI logs cluster never passed the readiness probe, so the job ended with LogClusterNotReady: the endpoint never became ready before comparing anything. 409 of 413 runs since 2026-10-26 22:00 UTC are red, on 277 PRs #126200 (mine, open)
Fast test (arm_darwin) / 05227_mutate_part_ahead_of_table_metadata_version_mergetree flaky, not from this PR (it changes only CMakeLists.txt flags): the rewrite dropped the column: 1 instead of 0, failing on 74 PRs in 14 days #127925 (mine, open)
Performance Comparison (amd_release, master_head, 2/6) / set_in_clustered_keys #0 from this PR, the measured cost of -fzero-call-used-regs=used-gpr (+26%, the shared bcmp exit) PR-caused by design and owned by this PR (#127995): the resolution is the requester's decision in #127959, keep the flag or exempt the hot functions
Performance Comparison (amd_release, master_head, 4/6) / uint64_to_string #2 from this PR, the same measured cost (+20%, itoa and toChars return paths) PR-caused by design and owned by this PR (#127995): the resolution is the same decision
Performance Comparison (arm_release, master_head, 1/6) / general_purpose_hashes_on_UUID #6, json_to_string #1 from this PR for general_purpose_hashes_on_UUID #6 (+25%, farmHash64); json_to_string #1 is slower on 142 other PRs in 30 days PR-caused by design and owned by this PR (#127995): the resolution is the same decision
Mergeable Check, PR praktika rollups of the rows above #126200, #127925, #127995 (the owners of the rows above)
Sync - CH Inc sync (private, not actionable by me)

The per-arch geomean (+0.57% amd, +0.78% arm) and the attribution are in the PR description; this PR stays a draft until that decision. The first run of this head stopped at Config Workflow / Pre Hooks because the can be tested label was not set yet. CIDB has no other FAIL or ERROR row in the run above.

Session id: cron:our-pr-ci-monitor:20261028-073003

@motsc

motsc commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

Closing as rejected: +0.57% amd64 and +0.78% arm64 geomean cost, with reproducible individual regressions up to 26%. The other two proposals in #127959 merged; no hot-function exemptions proposed here.

@motsc

motsc commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

Closed as rejected; see outcome above.

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-build-system Build system (CMake, compilation, platform builds). pr-build Pull request with build/testing/packaging improvement pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants