Repository navigation
Add compiler and linker flags for section-based optimizations - #99474
Conversation
…-icf=all` These were previously only set for contrib libraries but not for the main ClickHouse code. Together with the already-present `-Wl,--gc-sections`, this enables the linker to remove unused functions/data and fold identical sections, reducing binary size. - `-ffunction-sections` / `-fdata-sections`: place each function and data item into its own ELF section. - `-faddrsig`: emit an address-significance table so the linker can safely distinguish address-taken symbols during ICF. - `-Wl,--icf=all` (lld only): fold identical code and data sections. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
It's unclear what the effect will be. Please check and compare the resulting binary size. |
|
Workflow [PR], commit [1ceaf35] Summary: ✅ AI ReviewSummaryThis PR adds section-based linker/compiler optimizations ( Missing context
Findings
ClickHouse Rules
Performance & Safety
Final Verdict
|
| # remove unused ones (--gc-sections) and fold identical ones (--icf). | ||
| # -faddrsig emits an address-significance table that lets the linker's ICF | ||
| # distinguish address-taken symbols from non-address-taken ones. | ||
| set(COMPILER_FLAGS "${COMPILER_FLAGS} -ffunction-sections -fdata-sections -faddrsig") |
There was a problem hiding this comment.
-faddrsig is added unconditionally to COMPILER_FLAGS, but GCC does not support this flag (g++: error: unrecognized command-line option -faddrsig\). This will break non-Clang builds. Please gate it behind a compiler check (e.g. check_cxx_compiler_flag("-faddrsig" HAS_FADDRSIG) and append only when supported), or restrict it to the Clang/lld path.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Sanitizer builds do not benefit from `-ffunction-sections`, `-fdata-sections`, `-faddrsig`, and `--icf=all` (binary size is irrelevant), and the increased number of ELF sections hurts instruction-cache locality. This caused `ConfigProcessorManyElements` to exceed its 300 s timeout under UBSan (444 s) and `ResolvePoolTest.StillBannedAfterSuccess` to blow its 5 ms timing budget. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The `amd_llvm_coverage` unit tests fail with a timeout in `CoordinationTest_TestStateMachineAndLogStore_Test` because the extra ELF sections from `-ffunction-sections`/`-fdata-sections` hurt instruction-cache locality in instrumented builds, same as sanitizers. Also exclude coverage from `--icf=all` since ICF could merge functions with distinct coverage counters. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
|
||
| if (LINKER_NAME MATCHES "lld" AND NOT SANITIZE AND NOT SANITIZE_COVERAGE AND NOT WITH_COVERAGE) | ||
| # Fold identical code and data sections to reduce binary size. | ||
| set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--icf=all") |
There was a problem hiding this comment.
Using --icf=all here can silently change pointer-identity semantics unless all object files provide reliable address-significance metadata. In this PR, -faddrsig is currently unsupported on GCC (already noted separately), so once that is gated, a GCC+lld build could still enable --icf=all without addrsig coverage and risk incorrect function/object address comparisons.
Please either:
- downgrade to
-Wl,--icf=safe, or - gate
--icf=allon confirmed-faddrsigsupport for all compiled objects in this target.
There was a problem hiding this comment.
We don't use gcc.
Binary Size ImpactThis PR adds Stripped binary comparison (
|
| Architecture | Master | PR | Delta |
|---|---|---|---|
| amd64 | 226,743,608 (216.2 MB) | 212,480,540 (202.6 MB) | -14.3 MB (-6.3%) |
| aarch64 | 208,993,618 (199.3 MB) | 196,217,900 (187.1 MB) | -12.8 MB (-6.1%) |
Debug symbols (clickhouse-common-static-dbg .deb)
Reported as ~87% smaller, though this dramatic reduction may partly reflect changes in how debug info is structured when using -ffunction-sections + ICF, rather than pure size savings.
Bottom line: The PR achieves a meaningful ~6% reduction (~13-14 MB) in the stripped release binary on both architectures. The raw binary sizes between master and PR are not directly comparable due to differences in how debug info is split/packaged.
What were you comparing against? PRs build without symbols because linking with LTO without it is much faster, and we only build them in master. |
| # -faddrsig emits an address-significance table that lets the linker's ICF | ||
| # distinguish address-taken symbols from non-address-taken ones. | ||
| # Sanitizer and coverage builds do not benefit from these size optimizations | ||
| # and the extra sections hurt instruction-cache locality in hot loops, |
There was a problem hiding this comment.
These three flags are applied without an OS_LINUX guard, so they also affect the macOS Darwin cross-compilation builds (which use Apple's ld64 via cctools-port, not lld).
On Darwin:
--gc-sectionsis not added (correctly guarded insideif (OS_LINUX))--icf=allis not added (correctly guarded insideif (OS_LINUX)+LINKER_NAME MATCHES "lld")- But
-ffunction-sections/-fdata-sectionshave no effect without-dead_strip, and-faddrsigemits__LLVM,__addrsigsections thatld64does not understand and cannot strip
Empirically verified by comparing Build (amd_darwin) binary sizes between this PR and PR #99662 as a same-master baseline:
amd_darwin/clickhouse: +166 KB (+0.10%) (larger, not smaller)arm_darwin/clickhouse: +114 KB (+0.07%) (larger, not smaller)
The ideal fix would be to also add -Wl,-dead_strip for Darwin (ld64 supports it and it enables dead stripping at the function-atom level using -ffunction-sections), which would unlock the same GC benefit on macOS. Short of that, these three flags should be guarded with OS_LINUX to avoid the small regression on Darwin builds.
Algunenano
left a comment
There was a problem hiding this comment.
Comparing against PR #99662 as a baseline (same master, no flag changes):
┌──────────────────────────────────────────────────────┬────────────────────────┬──────────────────────┬──────────────────┐
│ Artifact │ PR #99474 (with flags) │ PR #99662 (baseline) │ Delta │
├──────────────────────────────────────────────────────┼────────────────────────┼──────────────────────┼──────────────────┤
│ amd_release/clickhouse (raw) │ 233,800,568 B │ 240,752,320 B │ −6.95 MB (−2.9%) │
├──────────────────────────────────────────────────────┼────────────────────────┼──────────────────────┼──────────────────┤
│ amd_release/clickhouse-common-static (stripped deb) │ 212,480,540 B │ 226,474,182 B │ −14.0 MB (−6.2%) │
├──────────────────────────────────────────────────────┼────────────────────────┼──────────────────────┼──────────────────┤
│ amd_release/clickhouse-common-static-dbg (debug deb) │ 111,531,442 B │ 113,502,242 B │ −1.97 MB (−1.7%) │
├──────────────────────────────────────────────────────┼────────────────────────┼──────────────────────┼──────────────────┤
│ arm_release/clickhouse (raw) │ 223,469,514 B │ 229,951,524 B │ −6.48 MB (−2.8%) │
├──────────────────────────────────────────────────────┼────────────────────────┼──────────────────────┼──────────────────┤
│ arm_release/clickhouse-common-static-dbg (debug deb) │ 112,243,752 B │ 114,562,822 B │ −2.32 MB (−2.0%) │
└──────────────────────────────────────────────────────┴────────────────────────┴──────────────────────┴──────────────────┘
The stripped package shrinks ~6% (14 MB) while the raw binary shrinks ~3%. The larger reduction in the stripped binary confirms the
effect is mainly code elimination/folding, not debug info. Real reduction.
Build Time Impact (independently verified)
┌─────────────────────┬───────────┬──────────────────────┬────────────────┐
│ Build job │ PR #99474 │ PR #99662 (baseline) │ Delta │
├─────────────────────┼───────────┼──────────────────────┼────────────────┤
│ Build (amd_binary) │ 707.6s │ 595.5s │ +112s (+18.8%) │
├─────────────────────┼───────────┼──────────────────────┼────────────────┤
│ Build (arm_binary) │ 672.7s │ 422.1s │ +250s (+59.3%) │
├─────────────────────┼───────────┼──────────────────────┼────────────────┤
│ Build (amd_release) │ 1923.4s │ 1688.2s │ +235s (+13.9%) │
├─────────────────────┼───────────┼──────────────────────┼────────────────┤
│ Build (arm_release) │ 1703.4s │ 1661.5s │ +42s (+2.5%) │
└─────────────────────┴───────────┴──────────────────────┴────────────────┘
The arm_binary build time is 59% longer. The amd_release build is 14% longer. ARM has a much larger absolute delta in the non-ThinLTO
binary configuration because --icf=all runs single-threaded during the link step there. While the ThinLTO release builds absorb the cost
better, the non-release configurations used for integration tests are materially slower to link.
Since the build times are highly depending on hitting cache or not, and this introduced new flags (which are obviously not cached) I don't think this is critical. We can check again a new run to confirm.
Performance Impact (from CI)
Only ARM performance tests ran (AMD perf comparisons were skipped):
- 18 queries faster, 3 slower (2,103 total) — no statistically significant regression
- The 3 slower queries (apply_patch_parts_join, 4–7ms range) are at timescales where ±50% variance is normal noise
- Several queries improved 10–64%: rand, general_purpose_hashes, aggregation_external, array_fill — consistent with smaller icache
footprint from ICF
No AMD performance data — the PR claims a binary size/performance win but only ARM data is present to support it.
Let's tag this as a performance PR and make some change so it reruns and does both AMD and ARM performance comparison to confirm the impact it might have.
So my recommendation: Change the PR to a Performance improvement, push the change to improve Darwin too, and we can check performance and build time in the new commit
- Add `-Wl,-dead_strip` for Darwin builds (equivalent of `--gc-sections` on Linux) so that `-ffunction-sections`/`-fdata-sections` actually enable dead code elimination on macOS. - Guard `-faddrsig` with `OS_LINUX` in both the main build and contrib, since the address-significance tables are only consumed by lld's `--icf=all` and Darwin's ld64 does not understand them (causing a small binary size increase). #99474 (review) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
As expected, the CI builds normalized once ccache had any effect. I expect Darwin would do the same PerformanceIn general it looks good. We might want to look into some of the regressions just in case. |
Prefer `ld64.lld` over Apple's `ld` (cctools-port ld64) for macOS builds. This should significantly reduce Darwin link times, as cctools-port's ld64 is very slow with `-ffunction-sections` and `-dead_strip`. Falls back to `ld` if `ld64.lld` is not available. Works for both native macOS builds and cross-compiled builds from Linux. #99474 (comment) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Switched to LLD.
The AArch64 build has only some random regression. The AMD64 build has more random regressions - just in case, I checked all these regressions on an AArch64 server, and none of them were confirmed. |
| endif () | ||
|
|
||
| if (OS_DARWIN) | ||
| # Remove unreachable functions/data (Darwin equivalent of --gc-sections). |
There was a problem hiding this comment.
-Wl,-dead_strip) together with global -ffunction-sections/-fdata-sections, and in this PR discussion it already showed a large Darwin build-time regression (amd_darwin about 12 -> 37 min, arm_darwin about 10 -> 27 min).
For ClickHouse, compilation time regressions are a required review check. Please gate this optimization off on Darwin for now (or behind an opt-in setting) until we have clear CI evidence that linker-time impact is acceptable.
`-Wl,--icf=all` (ClickHouse#99474) lets lld fold byte-identical functions even when their address is taken, which breaks the guarantee that different functions have different addresses. In ThinLTO builds `gpr_free` is inlined into gRPC's zlib free callback `zfree_gpr`, which becomes `mov %rsi,%rdi; jmp free`, byte-identical to zlib-ng's default `zcfree`, so both get one address. Measured with llvm-nm: the official 26.8.10.6 image and a local ThinLTO build of master fold them (12 functions share that address locally); 26.3.33.24 and the no-LTO amd_binary do not. zlib-ng 2.1.7 (`zutil.c`) chooses the buffer layout by comparing the stream's callbacks with its defaults. `alloc_aligned` sees `zalloc_gpr != zcalloc`, allocates 8 + n + 64 bytes and returns the 64-byte aligned pointer with the original one stored below it. `free_aligned` sees `zfree_gpr == zcfree` and frees the aligned pointer itself. jemalloc places a large allocation at a random cache line of the extent's first page (JEMALLOC_CACHE_OBLIVIOUS); when it is the last line (1 in 64), the freed pointer is the extent's second page, which the emap does not register, and `ifree` -> `prof_free` reads `e_prof_tctx` from a NULL `edata_t`: `Address: 0x50`, as in the CI crashes. Otherwise an interior pointer is freed. Every gRPC call with transport compression goes through this path: `deflateEnd` for the result and `inflateEnd` for a compressed request. In CI only the WeeklyCFI integration jobs showed it, because amd_cfi is the only integration build with ThinLTO. In safe mode lld does not fold functions whose address is significant according to the `-faddrsig` tables the build already emits. Virtual methods, constructors and destructors (`unnamed_addr`) and functions whose address is never taken are still folded; objects without an address-significance table (Rust) are not folded. Measured on a local ThinLTO build of master (clang-22, lld-22, -g0): - `zfree_gpr` and `zcfree`: one address before, two after. - `lea F; cmp` sites where F is shared by different functions: 87 before (20 are zlib-ng's `zfree == zcfree` test inlined into rdkafka, rocksdb, arrow, orc, libarchive, minizip, gRPC and zlib-ng itself), 3 after: the source alias `AES_encrypt`/`asm_AES_encrypt`, and twice a destructor passed to `__cxa_throw`, none an identity test. - gRPC loop with gzip/deflate transport compression: before, the server crashed in 3/3 runs within 6 queries (the official 26.8.10.6 image in 7/7 within 22, 26.3.33.24 ran 2000/2000), the request side alone in 4/4, and 1 KB requests also gave a crash at a wild address in `grpc_core::Arena::~Arena()` and a spurious decompression error. After: 34000 queries without a failure. - Size: `.text` +2.21 MiB (+0.46%), stripped binary +2.97 MiB (+0.45%), zstd -3 of the stripped binary +0.55 MiB (+0.28%). Folded code: 52.0 MiB before, 50.6 MiB after. The new test sends compressed gRPC requests and results. It fails on the ThinLTO build without this change and guards the MasterCI release stateless jobs; PR CI has no ThinLTO build. An alternative with no size cost is to drop the identity shortcuts from our zlib-ng fork (upstream 2.2.0 no longer has `alloc_aligned` / `free_aligned`, zlib-ng#1713), but that leaves the other comparison sites. Closes ClickHouse#115121. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add
-ffunction-sectionsand-fdata-sectionsto compiler flags for the main ClickHouse code (previously only set for contrib libraries). Together with the already-present-Wl,--gc-sectionson Linux and newly added-Wl,-dead_stripon Darwin, this lets the linker strip unused functions and data.Add
-faddrsig(Linux only) to emit address-significance tables, enabling the linker to safely identify which symbols can be folded.Add
-Wl,--icf=all(lld-only, Linux) to fold identical code and data sections, reducing binary size.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Enable linker section-based optimizations (
-ffunction-sections,-fdata-sections,--icf=all) to reduce binary size and improve instruction cache utilization.Documentation entry for user-facing changes
Version info
26.4.1.301