Skip to content

Use ARM optimized-routines for aarch64 string functions - #118916

Merged
thevar1able merged 20 commits into
masterfrom
aarch64-arm-optimized-routines
Oct 19, 2026
Merged

thevar1able merged 20 commits into
masterfrom
aarch64-arm-optimized-routines

Conversation

@thevar1able

@thevar1able thevar1able commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

Adds contrib/optimized-routines (upstream ARM-software v26.07, aarch64 only) and links its AdvSIMD/MTE memcpy, memmove, memcmp, memchr, strlen, strcmp, strchr, strnlen with --whole-archive next to libllvmlibc. Sanitized builds keep the libc versions so the interceptors wrap them.

What this replaces depends on the libc. On glibc builds (including arm_release), memcpy, memset and the str*/memchr functions were already taken from glibc, whose aarch64 routines are derived from AOR. There the change is limited to memmove and memcmp (previously llvm-libc), plus dropping the PLT/ifunc indirection, so no large change in the perf suite is expected. On musl builds the previous routines were generic C and 2020-vintage AOR asm. Measured on Graviton4 against those: memcpy +26-37%, memmove ~2x on small sizes, memcmp +50-80%, strlen 2.9x, memchr 3x.

Math is deliberately not taken from AOR: its scalars are 0.5-2.5 ULP instead of correctly rounded and the stateless tests caught per-architecture last-digit differences. The SVE variants are not used since they are up to 3x slower on 128-bit-SVE cores.

Related: #118910
Related: #109239

Changelog category (leave one):

  • Performance Improvement

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

Use the ARM optimized-routines string functions (memcpy, memmove, memcmp, memchr, strlen, strcmp, strchr, strnlen) on aarch64.


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

Version info

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

thevar1able and others added 6 commits September 9, 2026 00:52
Under ThinLTO (enabled in CI release builds via ENABLE_THINLTO=1) the
reference archives liblibllvmlibc.a and libmusl.a contain LLVM bitcode
members, for which llvm-nm prints dashes instead of a hex address. The
defined-globals regex required a hex address, so the reference symbol
set came out empty, nothing was localized in the Rust archives, and the
cbrt from Rust compiler_builtins (baseline x86-64, musl-ported soft
implementation) shadowed the llvm-libc one in the linked binary. This
showed up as a 1.5x cbrt regression in the perf comparison of the
static-binary PR:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109239

Local non-LTO builds were unaffected, which is why the problem only
reproduced in CI artifacts.

Co-Authored-By: Claude Fable 5 <[email protected]>
(cherry picked from commit 0b7bbbf)
(cherry picked from commit 9678062)
Archive symbol resolution is first-definition-wins in command-line
order, and the Rust static libraries precede liblibllvmlibc.a on the
link line. Whenever symbol localization is bypassed (as happened under
ThinLTO due to the llvm-nm bitcode output format), the libm functions
Rust's compiler_builtins exports (cbrt, fmod, fma - built for baseline
x86-64) silently win over the llvm-libc ones. Loading every llvm-libc
member ahead of all objects and archives makes the resolution
structural instead of order-dependent: a later archive can never supply
an already-defined symbol. compiler_builtins keeps each function in its
own archive member, so no duplicate definitions arise.

This also covers the mem functions, previously forced per-symbol with
-u; those flags are kept as a backstop.

Confirmed by the perf report for the static-binary PR (1.5x cbrt
regression on amd):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109239

Co-Authored-By: Claude Fable 5 <[email protected]>
(cherry picked from commit 2e3f2f1)
(cherry picked from commit 5fc022d)
llvm-libc's hypot is a correctly-rounded digit-recurrence loop that
ignores LIBC_MATH_HAS_SKIP_ACCURATE_PASS and measures ~22x slower than
the platform implementation (91 ns vs 4.2 ns per call on Neoverse-V2,
confirmed end-to-end: sum(hypot(x, 1.5)) drops from 17 ns to 3.9 ns per
row). With it omitted from the source list, hypot resolves to the libc
one - musl in static builds, glibc in dynamic ones.

Co-Authored-By: Claude Fable 5 <[email protected]>
(cherry picked from commit accc9c0)
(cherry picked from commit 704a8f3)
New contrib optimized-routines (upstream ARM-software/optimized-routines,
no fork needed - built as-is): on aarch64, scalar exp, exp2, log, log10,
atan, atan2 replace the llvm-libc generic implementations (excluded from
libllvmlibc there), and the AdvSIMD/MTE string routines - memcpy,
memmove, memcmp, memchr, strlen, strcmp, strchr, strnlen - replace the
mix of musl generic C, musl's vendored 2020 AOR asm, and llvm-libc weak
definitions. Both archives are linked with --whole-archive, so the
definitions win the link structurally.

Measured on Graviton4 (Neoverse-V2) against the previous static-binary
state: exp 2.1x, exp2 2.2x, atan 1.7x, atan2 1.6x, memcpy +26-37%,
memmove ~2x on small sizes, memcmp +50-80%, strlen 2.9x, memchr 3x.
This closes the gap to glibc, whose aarch64 libm and ifunc-selected
string routines derive from the same upstream. The SVE string variants
are deliberately not used: on 128-bit-SVE cores they measure up to 3x
slower than the NEON/MTE ones. AOR math scalars are 0.5-2.5 ULP instead
of llvm-libc's correct rounding, matching glibc's accuracy class.

Motivated by the h3ToGeoBoundary regression in the perf comparison:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109239

Verified under qemu-aarch64 with a static test binary: exp/exp2/log/
log10/atan/atan2 exact on reference points; strlen/memcmp/memchr/strcmp
correct incl. the MTE variants. x86_64 builds are unaffected.

Co-Authored-By: Claude Fable 5 <[email protected]>
(cherry picked from commit e687278)
The AOR scalar math (exp, exp2, log, log10, atan, atan2) added in
e687278 is 0.5-2.5 ULP instead of correctly rounded. x86_64 keeps
llvm-libc's correctly-rounded implementations, so the same query started
printing different last digits per architecture, which the stateless
tests caught on arm: 02224_s2_test_const_columns, 01849_geoToS2 and
01851_s2_to_geo (s2 calls atan2 internally), 04092_kql_conformance_baby_kusto
(log10(0.1) returned -0.9999999999999999 instead of -1) and
03233_dynamic_in_functions:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109239&sha=e687278fb9fc24b2a96e90201410f3c5b7758f29&name_0=PR

Correct rounding is what makes results architecture-independent, so the
math goes back to llvm-libc everywhere; the h3 trig cost on aarch64
(~10-16% on three h3 perf queries) is the accepted price. The AOR
AdvSIMD/MTE string routines stay - byte semantics have no rounding, and
they are the larger win (memcpy +26-37%, memcmp +50-80%, strlen 2.9x).

Co-Authored-By: Claude Fable 5 <[email protected]>
(cherry picked from commit bf8c209)
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9269fc4]

Summary: ✅


AI Review

Summary

This PR imports Arm optimized-routines v26.07 for string and memory operations in nonsanitized AArch64 builds, with capability-based selection for memcpy and memmove. The latest code fixes the previously reported startup and SVE2 strchr faults; native AdvSIMD and emulated SVE guard-page checks passed. No new inline findings. The existing glibc performance concern remains unresolved.

Findings

⚠️ Majors

  • cmake/linux/default_libs.cmake:30: The process-wide glibc overrides still need performance verification, continuing the existing finding. The latest completed ARM comparison reports json_to_string query 1 increasing from 1.3909 s to 1.9290 s (38.6%). Seven old/new measurements show a broad shift, with a conservative slowdown estimate of 35.9% versus 1.6% recent master noise. Earlier PR runs include 27.7% and 41.6% slowdowns, interspersed with near-neutral results, so attribution remains uncertain. This is a serious performance signal requiring verification, not a confirmed regression at the updated head. Re-run this query on the current arm_release build; if it persists, isolate the responsible override and fix it or preserve glibc for that function.
Missing context / blind spots
  • ⚠️ The newest completed performance comparison tests 8ab99a236bc6, whereas the reviewed head is 9269fc49fc36, which also incorporates newer master code. Current build/CI checks are pending. A focused comparison at the reviewed head would establish whether the JSON conversion slowdown remains.
  • ⚠️ Local checks covered startup before the dispatch constructor, AdvSIMD, and SVE with 48- and 96-byte vectors. Static musl startup and MOPS execution rely on the author's reported validation; neither was independently executed here.
Final Verdict

⚠️ Request changes — verify the ARM JSON conversion performance signal at the current head and address it if reproduced. The two fixed runtime findings were resolved; no new inline review was submitted.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements submodule changed At least one submodule changed in this PR. comp-external-dependencies Third-party deps updates in contrib/, vendored code, and platform base libraries. labels Sep 8, 2026
Comment thread cmake/linux/default_libs.cmake Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 31 analysed

One query was flagged: clickbench Q20 is -41.4% faster (220 ms to 129 ms). CPU time dropped by about the same share, so less work is being done, and the shift is large enough that the verdict stands as reported. This PR replaces memcpy, memmove, memcmp, memchr, strlen, strchr and strnlen with ARM optimized-routines, on aarch64 non-sanitizer builds only. A query that scans a lot of string data is the kind of workload that would benefit. The dossier does not say which architecture the runner uses. If it is x86_64 the PR does not change the binary, so the gain could not come from this PR. It is also odd that no other ClickBench or TPC-H query moved, given how widely memcpy is used.

clickbench

🟢 1 improved

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 20 improvement 220 129 -41.4% <0.0001 cpu: -41.4%, and CPU time fell from 2901 ms to 1544 ms. That fits faster aarch64 memcpy/memchr/memcmp on a string-scan query, but only holds if this runner is aarch64.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 256fa605-191f-436f-8ef1-f88df875c59e
  • MIRAI run: 5e16255e-6a61-4982-9feb-ebacef3bdab2
  • PR check IDs:
    • clickbench_62963_1791932802
    • clickbench_62969_1791932802
    • clickbench_62994_1791932802
    • tpch_adapted_1_official_63024_1791932802
    • tpch_adapted_1_official_63045_1791932802
    • tpch_adapted_1_official_63067_1791932803

@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 9269fc49fc361ac1d8750595a066e498eb81d2f4 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

# AdvSIMD/MTE string routines from ARM's optimized-routines
# (see contrib/optimized-routines-cmake).
link_directories("${CMAKE_BINARY_DIR}/contrib/optimized-routines-cmake")
target_link_libraries(global-libs INTERFACE aor)

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.

aor is wired into every ARCH_AARCH64 build here, not just the static/USE_MUSL binaries that currently need to replace libc. That means dynamic glibc builds stop using glibc's runtime ifunc selection and get the fixed file list from contrib/optimized-routines-cmake instead (memcpy-advsimd.S, memchr-mte.S, strlen-mte.S, strcmp.S, strchr-mte.S, strnlen.S). The same AOR tree also ships alternatives such as memcpy-mops.S, memcpy-sve.S, and strchr-sve2.S, so this is not actually "the same code minus the ifunc indirection" on those machines.

The only measurements in the PR are against the previous static-binary state on Graviton4. Before we take these symbols away from glibc on every dynamic aarch64 build too, we need either evidence that this still wins on the supported glibc surface, or a narrower scope (for example only the static/USE_MUSL configurations).

Comment thread contrib/optimized-routines Resolved
thevar1able and others added 3 commits October 1, 2026 14:36
The previous pointer was two commits past `v26.07` (editor configuration
files and comments in `strchr-sve2.S`); none of the routines built here
change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The `aor` definitions are strong. Under sanitizers the interceptors stay in
effect only because every routine in the archive happens to be intercepted
and the sanitizer runtimes are `--whole-archive`d ahead of the lazy `-laor`,
so no member is ever extracted. Adding a routine or reordering the link would
silently bypass the interceptors. Sanitized builds gain nothing from AOR, so
leave these functions with the libc there.

The target is also not defined when it is not linked (sanitizers, or
`ENABLE_LLVM_LIBC_MATH` off), so the Rust symbol localization in
`contrib/corrosion-cmake` does not use it as a reference archive.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread contrib/CMakeLists.txt Resolved
thevar1able and others added 6 commits October 2, 2026 14:22
The AdvSIMD `memcpy` from optimized-routines replaced glibc 2.39's
ifunc-selected `__memcpy_sve` on Graviton 3/4 and was 12-17% slower in
is_valid_utf8, lower_upper_utf8_mixed_ascii, parquet_read,
parquet_read_with_index and orc_tuple_field_prune. On glibc builds the
`memcpy` entry point of memcpy-advsimd.S now gets a private name so
`memcpy` stays undefined and binds to glibc; `memmove` is still exported
and replaces llvm-libc's weak generic one. Musl builds keep both.

Perf report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118916&sha=latest&name_0=PR
PR: #118916

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…en.S

Replaces the previous commit's approach of leaving `memcpy` to glibc.
Both `memcpy-sve.S` and `memcpy-advsimd.S` are built and the public
`memcpy`/`memmove` are trampolines in `memcpy_dispatch.c` that resolve on
first call from the kernel-emulated `ID_AA64PFR0_EL1` SVE field. A
function pointer is used instead of `ifunc` so the same code works in
static musl binaries, which cannot process `IRELATIVE` relocations, and
the probe does not depend on `getauxval` being initialised.

`strlen` switches from `strlen-mte.S` to `strlen.S`: the MTE variant is
20-40% slower above 512 bytes and about 20% slower on mixed sizes, while
`strlen.S` matches glibc's `__strlen_asimd`. ClickHouse does not enable
MTE.

Perf report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118916&sha=latest&name_0=PR
PR: #118916

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@nickitat

nickitat commented Oct 8, 2026

Copy link
Copy Markdown
Member

let's at least add sve2 and measure. maybe mops as well, for the bright future

Requested in the review of #118916:
add the `sve2` and `mops` variants from optimized-routines and measure.

The trampoline in `dispatch.c` (renamed from `memcpy_dispatch.c`, since it
now also covers `strchr`) selects, in glibc's ifunc order:
- `memcpy`/`memmove`: `__memcpy_aarch64_mops`/`__memmove_aarch64_mops`
  (Armv8.8 `cpyf*`/`cpy*`) when `ID_AA64ISAR2_EL1.MOPS` is set, then the
  SVE variant, then AdvSIMD.
- `strchr`: `__strchr_aarch64_sve2` (built on the SVE2 `match` instruction)
  when `ID_AA64ZFR0_EL1.SVEver >= 1`, otherwise `__strchr_aarch64_mte`.

The ID registers are read by encoding because the assembler only accepts
the names `ID_AA64ZFR0_EL1` and `ID_AA64ISAR2_EL1` with the matching
`-march` extensions. The kernel returns zero for ID registers it does not
know or features it has not enabled for user space, so the probes degrade
to the existing selection on old kernels.

Verified with a freestanding static aarch64 binary under qemu-user
(`neoverse-n1`, `neoverse-v1`, `neoverse-n2`, `max`, SVE vector lengths
256/512/2048 bits): each CPU model picks the expected variant and
`memcpy`/`memmove`/`strchr` agree with reference implementations across
sizes, alignments, overlaps, and strings ending right before an unmapped page.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
thevar1able and others added 2 commits October 14, 2026 15:10
…strchr

Two problems with the runtime dispatch in `dispatch.c`:

- The feature probes read `ID_AA64PFR0_EL1`, `ID_AA64ZFR0_EL1` and
  `ID_AA64ISAR2_EL1` with `mrs`. User space can do that only because the
  kernel traps and emulates the instruction, which it does since 4.11 and
  advertises with `HWCAP_CPUID`. On older kernels the first `memcpy` raised
  `SIGILL` during libc startup. The probes now use `HWCAP_SVE` and
  `HWCAP2_MOPS` from the auxiliary vector, which the kernel sets only when
  it has enabled the feature for user space. Because `getauxval` is not
  usable before `__init_libc` in a static musl binary, the selection runs
  in a constructor instead of lazily on the first call; until then the
  function pointers hold the AdvSIMD variants, which run on every core.

- `__strchr_aarch64_sve2` aligns its loop pointer down to the vector
  length and reads whole vectors, which stays inside the page only when
  the vector length is a power of two. The Arm ARM mandates that since
  DDI0487 I.a (known issue C215), but QEMU still offers 48- and 96-byte
  vectors, where a page-aligned string ending right before a `PROT_NONE`
  page makes `strchr` fault instead of returning null (reproduced under
  `qemu-aarch64 -cpu max` with `PR_SVE_SET_VL`; 16, 32, 64 and 256 pass).
  A check in the resolver would not be enough since the length is per
  thread. ClickHouse has two `strchr` call sites, neither of them hot, so
  the variant is dropped and `strchr` is the MTE routine again, as for
  `memchr`.

Verified with a cross-compiled test of `dispatch.c` and the four
`memcpy`/`memmove` variants under `qemu-aarch64` with `-cpu neoverse-n1`
(AdvSIMD), `neoverse-v1` (SVE) and `max` (MOPS): the selection matches the
HWCAP bits, and every variant copies correctly against a `PROT_NONE` guard
page for sizes 0..6000, offsets 0..16 and both overlap directions, the SVE
one also at vector lengths 48, 96, 144 and 256.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@thevar1able

Copy link
Copy Markdown
Member Author

🕵️ Benchmarked 9269fc4 against its merge base 39e45ea on a Neoverse-N1 with glibc 2.41. CPU features: fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm lrcpc dcpop asimddp. There is no SVE, SVE2 or MOPS, so only the AdvSIMD path was tested.

Method: local Release builds, clickhouse local, max_threads=1, pinned to one core, 25 alternating runs per binary, and an A/A run for the noise floor.

  • toFixedString(reinterpretAsString(number), 8) with a filter: 16% faster, from 2.755 s to 2.311 s. Most of this is the dropped memcpy@plt indirection on per-row small copies.
  • FORMAT TSV output: about 3.5% faster. The base is bimodal, so the medians show 10%.
  • Quoted CSV read: 2.5% faster, from 1.583 s to 1.543 s.
  • Regressions: none of practical size. GROUP BY String is +0.4%, a numbers_mt filter is +0.2% and ORDER BY String is +0.1%, all at the A/A noise floor. concat, substring and the string filter are unchanged.

@thevar1able

Copy link
Copy Markdown
Member Author

🕵️ Benchmarked head 9269fc49fc361ac1d8750595a066e498eb81d2f4 on AWS Graviton 4 (Neoverse-V2, 64 cores, Ubuntu 24.04, glibc 2.39, kernel 6.17). CPU features: sve sve2 sveaes svepmull svebitperm svesha3 svei8mm svebf16 bti rng, SVE vector length 128 bits, no MOPS. Same CPU as the ARM perf CI runners.

Verified from live process memory that both PR binaries dispatch memcpy and memmove to __memcpy_aarch64_sve; strchr is the MTE routine. Master gets memcpy/memchr/strchr/strlen/memset from glibc (ifunc → __memcpy_sve) and memmove/memcmp from llvm-libc.

Two binary pairs: PR CI build_arm_release vs master CI b26f4c3, and a local clang-22 None+ThinLTO build vs the merge base 39e45ea1. 134 queries from is_valid_utf8, lower_upper_utf8_mixed_ascii, parquet_read, orc_tuple_field_prune, codecs_float_select, set_index, generate_random_json, sort_string_full, cutURLParameter, url_hits, string_sort plus 20 targeted string/serialization queries; perf.py with alternating servers, ≥7 runs, idle machine; A/A noise band 0.98..1.02.

Result: neutral. Median PR/master 1.002 (CI pair) and 1.001 (local pair), 130/134 and 122/134 within ±3%. The 12–17% regressions of the first revision are gone.

@thevar1able
thevar1able added this pull request to the merge queue Oct 19, 2026
Merged via the queue into master with commit 023b5a8 Oct 19, 2026
349 of 350 checks passed
@thevar1able
thevar1able deleted the aarch64-arm-optimized-routines branch October 19, 2026 20:55
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 19, 2026
@thevar1able thevar1able mentioned this pull request Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-external-dependencies Third-party deps updates in contrib/, vendored code, and platform base libraries. pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants