fix, enh: add ability to swap std::sort with other routines, lock ISA #247
All Vouch review confidence checks passed
Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #247"
general
weight: 0.35
r-devulap
Keep the std::sort fallback's instantiations local to each ISA build
Summary
qsort_andqselect_fall back tostd::sort(..., comparator::STDSortComparator)when quicksort stops makingprogress. The comparator is passed as a function pointer,
bool ()(const T &, const T &), whose type is the same inevery build of the header. So when a project compiles the header for several ISAs and links them into one binary,
which is what
lib/and NumPy do, each ISA's object file defines the same weakstd::symbols(
std::__introsort_loop<float , ..., bool ()(const float &, const float &)>and the rest). The linker keeps onecopy for all callers, so the AVX-512 code path can run the AVX2 build of these functions, or the AVX2 path the
AVX-512 build, depending on link order. Nothing currently crashes, because the copies built for AVX-512 contain no
AVX-512 instructions, but nothing guarantees that.
This change passes the comparator through a lambda. Its type is local to
qsort_<zmm_vector<float>, ...>(or<avx2_vector<float>, ...>), so each ISA'sstd::sortinstantiation gets its own name and local linkage, and thereis nothing for the linker to merge. As a side effect, the comparator is now inlined in the fallback, which makes it
17-32% faster for n >= 10k.
It also routes the four
std::sortcalls (the two fallbacks and the two instd_argsort/std_argsort_withnan) through anXSS_STD_SORTmacro that defaults tostd::sort, so a project can substitute itsown sort, e.g. one templated on the ISA, as oneDAL's
introSort<cpu>is.What goes wrong
A template instantiated with the same arguments in several object files is emitted in each as a weak (COMDAT)
symbol. Under the one-definition rule the copies are interchangeable, so the linker keeps one (the first in link
order for GNU ld and gold) and drops the rest. Object files don't record which
-mflags a function was compiledwith, so it has no way to tell them apart.
When this header is built once per ISA,
x86simdsort-avx2.cppandx86simdsort-skx.cppinlib/for example,everything in it has internal linkage (
X86_SIMD_SORT_INLINEand_FINLINEarestatic) or is templated on anISA-specific vector type, except the standard library templates it instantiates with ISA-independent arguments.
The fallback's
std::sortwith a function-pointer comparator is one of them.Runtime dispatch only selects the entry point (
avx512_qsortoravx2_qsort, NumPy'sQSort_X86_V4orQSort_X86_V3). Below it, the call to the sharedstd::symbol goes to whichever copy the linker kept:If the kept copy is the AVX-512 build and the compiler used AVX-512 instructions in it, an AVX2-only CPU gets SIGILL
the first time an input reaches the fallback.
Observed
GCC 13.3, release builds, symbols compared with
check_isa_weak_symbols.sh. "Different" means the two copiesdisassemble to different instructions.
| Build | Objects compared | Shared weak symbols | Different | Kept by the linker |
|---|---|---|---|---|
|
lib/,main(7521047) |x86simdsort-avx2.cpp.o,-skx,-icl,-spr| 21 (avx2 vs skx) | 8 | the AVX2 copy, all 8 ||
lib/, v7.0 | same | 21 (avx2 vs skx) | 8 | the AVX2 copy, all 8 || NumPy
main(31a42ae, x86-simd-sortfa944ef) | qsortX86_V3,X86_V4| 12 | 2 | theX86_V3copy || NumPy | 16-bit qsort
AVX512_ICL,AVX512_SPR| 8 | 0 | || NumPy | argsort
X86_V3,X86_V4| 0 | | |The shared symbols are
std::__introsort_loop,__insertion_sort,__adjust_heapand__heap_selectfor every keytype, plus, in NumPy's 16-bit pair,
Comparator<zmm_vector<int16_t / uint16_t>, ...>::STDSortComparatoritself: takingits address forces an out-of-line copy, and both 16-bit targets use
zmm_vector. The copies that differ werecompiled from the same source with different instruction scheduling, so they are distinct code under one name. In
NumPy's
_multiarray_umath.sothe single remainingstd::__heap_select<float , ...>is called from bothqsort_<zmm_vector<float>, ...>andqsort_<avx2_vector<float>, ...>, and it is exported in the dynamic symbol table.None of the copies contain AVX-512 instructions with this compiler, so no crash was observed.
Which copy is kept follows link order. With the two builds of the fallback as separate objects:
| Linker | Order | Copy in the binary |
|---|---|---|
| GNU ld 2.42 | AVX2 object first | AVX2 |
| GNU ld 2.42 | AVX-512 object first | AVX-512 |
| gold 1.16 | AVX2 object first | AVX2 |
| gold 1.16 | AVX-512 object first | AVX-512 |
NumPy gets the AVX2 copy because its build happens to put the
X86_V3object beforeX86_V4inlib_multiarray_umath_mtargets.a(members 21 and 36), even thoughmeson.buildlistsX86_V4first.The change
src/xss-common-qsort.h:qsort_andqselect_pass[](const type_t &a, const type_t &b) { return comparator::STDSortComparator(a, b); }instead ofcomparator::STDSortComparator. A lambda in a function template has a unique closure type that belongs to thatinstantiation, and it has no linkage because
qsort_isstatic(qselect_isX86_SIMD_SORT_INLINE, alsostatic). So thestd::sortinternals become, for example,std::__introsort_loop<..., qsort_<zmm_vector<float>, ...>::{lambda(float const &, float const &)#1}>, a localsymbol in each object.
src/xss-common-includes.h:XSS_STD_SORT, defaulting tostd::sort, used by those two calls and bystd_argsortand
std_argsort_withnan(whose comparators were already lambdas). A project can define it before including theheaders to a sort taking
(first, last, comp). oneDAL, for instance, could define it todaal::algorithms::internal::introSort<DAAL_CPU>, which carries the ISA in its name at every optimization level.+32/-9 over three files. No API or behavior change when
XSS_STD_SORTis not defined.After the change:
| Build | Shared weak symbols |
|---|---|
|
lib/,main| 3, all ISA-independent:DW.ref.__gxx_personality_v0(exception-handling data) andstd::vector<size_t>::~vector()(D1/D2) fromlib/'s argsort wrappers, which only null-checks and callsoperator delete|| NumPy qsort
X86_V3/X86_V4| 0 || NumPy 16-bit
AVX512_ICL/AVX512_SPR| 0 || NumPy argsort | 0 |
Performance
bench_std_sort_fallback.cpptimesqsort_withmax_iters = 0, i.e. the fallback itself, on random keys, builtagainst
mainbefore and after the change. One core of a Xeon Platinum 8480+,-O3, best of 15-300 runs.after/before, below 1 is faster:
| Compiler | -march | n >= 10k | n <= 1000 |
|---|---|---|---|
| GCC 13.3 | haswell | 0.68-0.76 | 0.20-0.42 |
| GCC 13.3 | skylake-avx512 | 0.68-0.76 | 0.22-0.39 |
| Clang 18.1 | haswell | 0.75-0.83 | 0.34-0.55 |
| Clang 18.1 | skylake-avx512 | 0.74-0.82 | 0.29-0.56 |
With the function pointer, neither compiler inlines the comparator into the
std::sortinternals: in thisbenchmark's v7.0 build (
-march=haswell), GCC has 7 indirect calls (call %reg) in__introsort_loop<float , ...>and 2 each in
__insertion_sortand__adjust_heap, and Clang 52 across thestd::internals. With the lambda thereare none. The fallback only runs when quicksort makes no progress, so this does
not affect typical sorts. Code size of a translation unit instantiating qsort, argsort and keyvalue_qsort for several
types changes by -0.1% to +1.0% of
.text, and a linked binary keeps one copy of the fallback per ISA instead ofone in total.
<details><summary>All results (ns per sort)</summary>
See
bench_results.md.</details>
Not fixed here
-O0the standard library helpers that don't take the comparator (std::iter_swap<float , float >,std::move_backward,std::reverse,std::min<float>, ...) are not inlined and are still shared between ISA builds:76 weak symbols in a test translation unit. With optimization they are inlined. Projects that need ISA isolation in
unoptimized builds can define
XSS_STD_SORT, butstd::reverseandstd::swapelsewhere in the headers wouldremain.
std::vector<size_t>destructor shared bylib/'s per-ISA argsort wrappers (ISA-independent code).check_isa_weak_symbols.shcould run onlib/'s objects after the meson build; it needsnm,objdumpandc++filt. Left out of this change to keep it to the headers.Context
Found while integrating x86-simd-sort into oneDAL, which compiles
x86simdsort-static-incl.honce per ISA(
-march=haswelland-march=skylake-avx512translation units) and links them into one library. oneDAL only callskeyvalue_qsort, whose fallback isheap_sort, so it is not affected today; it would be throughqsort,qselector
argsort. Its own kernels avoid the problem by templating every helper on the CPU type, which is whatXSS_STD_SORTlets it do for this sort.