Repository navigation
Vectorize comparison of UUID, IPv4 and IPv6 columns - #120193
Conversation
Same-type comparisons of these columns went through the generic path with one virtual compareAt call per row, because ColumnVector::isNumeric is false for them. Route them through NumComparisonImpl like the numeric types. The IPv6 comparison operators are moved inline so that the loop does not call an out-of-line function per row.
|
Workflow [PR], commit [d88164f] Summary: ❌
AI ReviewSummaryThis PR routes same-type Final Verdict✅ No new findings from this review. LLVM Coverage ReportMeasured on commit d88164f.
Changed lines: Changed C/C++ lines covered: 42/47 (89.36%) · Uncovered code |
|
|
||
| bool operator==(const IPv6 & rhs) const; | ||
| /// Ordered by the network byte representation, not by the little-endian UInt128 value. | ||
| bool operator<(const IPv6 & rhs) const { return std::memcmp(&toUnderType(), &rhs.toUnderType(), sizeof(UnderlyingType)) < 0; } |
There was a problem hiding this comment.
This used to have memcmp16 and now it uses memcmp. Is the assembly any different?
I also see it being used in src/Dictionaries/IPAddressDictionary.cpp which we should probably change too.
There was a problem hiding this comment.
I think I found an even faster one ...
There was a problem hiding this comment.
Per row for IPv6 < IPv6 on x86-64-v3 (branchless = 21861f0):
| Case | std::memcmp |
memcmp16 |
branchless |
|---|---|---|---|
| L1, random | 0.94 ns | 1.02 ns | 0.80 ns |
| L1, all equal | 0.92 ns | 0.57 ns | 0.79 ns |
| L1, random half equal | 1.03 ns | 0.79 ns | 0.80 ns |
| memory-bound, random half equal | 4.34 ns | 4.70 ns | 1.46 ns |
... I will check if this optimization can be made somewhere else too
Drop the table setup and reduce to one query per type. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Keeps IPv6 byte comparison consistent with the IPv6 operators. Both compile to inline code and run at the same speed since the loops are memory-bound. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Load both halves byte-swapped and compare them as one native 128-bit integer. This compiles to movbe, cmp, sbb, setb with no data-dependent branch, so it is not slowed down by unpredictable equality of the values. Measured per row on x86-64-v3 against the std::memcmp version: L1-resident: 0.80 ns vs 0.94 ns on random data, 0.80 ns vs 1.04 ns when half of the pairs are equal. Memory-bound: 1.46 ns vs 4.40 ns when half of the pairs are equal, otherwise equal. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Compare both 16-byte operands as big-endian 128-bit integers instead of locating the first differing byte with SIMD. The three-way result folds into movbe, cmp, sbb, setcc when the caller only needs the sign, so the FixedString(16) comparison kernels no longer have a data-dependent branch on equality. One portable definition replaces the AVX-512, SSE2, NEON and scalar variants. Measured with `clickhouse local`, one thread, 100M rows of FixedString(16) built with `reinterpretAsFixedString(reinterpretAsUUID(...))`: `<` on random pairs 0.69 s -> 0.65 s, `<` when half of the pairs are equal in an unpredictable pattern 1.34 s -> 0.67 s, `<` against a constant 0.41 s -> 0.35 s, `=` (unchanged path) 0.53 s -> 0.51 s. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The binary-search predicates of the ip_trie lookups are unpredictable by nature, so the branchless memcmp16 fits them better than libc memcmp. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…it loads Use `unalignedLoad` instead of declaring `hi` and `lo` uninitialized and filling them with `memcpy` in `IPv6::asBigEndian` and `detail::loadBigEndian128`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120193&sha=a085831eb3aa646a24e35e4e40e750601ce3c577&name_0=PR&name_1=Build%20%28arm_tidy%29 PR: ClickHouse#120193 Co-Authored-By: Claude Opus 5 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: This PR vectorizes equality/ordering comparisons of UUID, IPv4 and IPv6 columns and rewrites the 16-byte compare kernel; its runtime effect is limited to queries that actually compare those types. None of the flagged ClickBench queries do: Q18 groups by UserID/minute/SearchPhrase, Q33 groups by WatchID and ClientIP (which ClickBench stores as a 32-bit integer, not the IPv4/IPv6 type), and Q34 is a URL string group-by. With no changed code path executed, the consistent-looking improvements on these mostly-noisy queries are run-to-run variance, so they were downgraded to not_sure; Q28 stays as-is. The change's real impact would show up in the dedicated UUID/IP comparison tests, not in these ClickBench SELECTs. clickbenchFlagged queries (4 of 43)
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
|
|
🕵 I looked at the generated code before and after this PR, on both default targets, benchmarked the kernels, and prototyped one change that I verified end to end. Method. Compiled only ✅ The core claim holds on the default build
✅ ARM is better in every case
So on ARM the branchless form is already ahead in the common differing case, before counting the mispredictions it removes. The reason the old NEON path is expensive is the mask extraction:
|
| kernel | random data | 50% equal, unpredictable |
|---|---|---|
| master, SIMD + branch | 1.79 | 5.46 |
| this PR | 2.78 | 2.90 |
1.9x better when whole-value equality is unpredictable, which is sorting, ip_trie binary search and joins. About 1.55x worse when values almost always differ, which is the common column vs column and column vs constant predicate. On x86, pmovmskb plus tzcnt is cheap, so master's path is close to single-thread memory bound for random data and hard to beat.
The description says < on random pairs went from 0.69 s to 0.65 s. At 100M rows that is 0.4 ns/row in the other direction from what I measure. In that query the values are generated on the fly and the kernel is a fraction of the runtime, so a single run has more noise than the effect. Could you re-measure that case, and state the trade-off in the description rather than claiming a win in both distributions?
💡 unsigned __int128 leaves AVX-512 builds on the table
unsigned __int128 is the right default. I tried rewriting it into two 64-bit halves unconditionally and that is worse on both default targets: on v3 it measures 3.53 / 3.42 ns/row, and on ARM the function grows from 15 to 139 instructions because the vectorizer engages and builds a rev64 / zip1 / cmhi loop for no gain.
But the two forms are best on different targets. AVX-512 has an unsigned 64-bit vector compare, vpcmpuq, so keeping the halves apart lets the enclosing loop vectorize; without it the vectorizer has no such instruction, extracts every lane back into a general purpose register and ends up slower than the 128-bit form. That is exactly what the existing per-arch #if blocks in memcmpSmall.h are for. Selecting per target costs the default build nothing and is worth about 1.8x on an X86_ARCH_LEVEL=4 or -march=native build. It also removes the duplicated big-endian loader, which currently exists as the same ten lines in both IPv4andIPv6.h and memcmpSmall.h.
Concretely, a new base/base/bigEndianCompare.h:
#pragma once
#include <base/types.h>
#include <base/unaligned.h>
#include <bit>
/** Comparison of 16-byte values that are ordered by their byte representation: `IPv6` addresses,
* `FixedString(16)` and the network-order form of a `UUID`.
*
* Both implementations below produce the same order. They differ only in how the value is handed
* to the optimizer:
*
* - One native 128-bit integer compiles to `movbe`, `cmp`, `sbb`, `setcc` on x86-64 and to `ldp`,
* `rev`, `cmp`, `sbcs`, `cset` on AArch64. Both are branchless and neither needs a vector unit.
* - Two separate 64-bit halves let a loop over these functions vectorize where the target has an
* unsigned 64-bit vector compare, which on x86-64 means AVX-512 `vpcmpuq`. Without it the
* vectorizer has no such instruction, extracts every lane back into a general purpose register
* and the result is slower than the 128-bit form, so that form stays the default.
*/
namespace detail
{
inline UInt64 loadBigEndian64(const void * p)
{
UInt64 v = unalignedLoad<UInt64>(p);
if constexpr (std::endian::native == std::endian::little)
v = std::byteswap(v);
return v;
}
inline unsigned __int128 loadBigEndian128(const void * p)
{
const UInt64 hi = loadBigEndian64(p);
const UInt64 lo = loadBigEndian64(static_cast<const char *>(p) + sizeof(UInt64));
return static_cast<unsigned __int128>(hi) << 64 | lo;
}
}
#if defined(__AVX512F__) && defined(__AVX512VL__)
inline bool lessBigEndian16(const void * a, const void * b)
{
const UInt64 a_hi = detail::loadBigEndian64(a);
const UInt64 b_hi = detail::loadBigEndian64(b);
const UInt64 a_lo = detail::loadBigEndian64(static_cast<const char *>(a) + sizeof(UInt64));
const UInt64 b_lo = detail::loadBigEndian64(static_cast<const char *>(b) + sizeof(UInt64));
return (a_hi < b_hi) | ((a_hi == b_hi) & (a_lo < b_lo));
}
inline int compareBigEndian16(const void * a, const void * b)
{
const UInt64 a_hi = detail::loadBigEndian64(a);
const UInt64 b_hi = detail::loadBigEndian64(b);
const UInt64 a_lo = detail::loadBigEndian64(static_cast<const char *>(a) + sizeof(UInt64));
const UInt64 b_lo = detail::loadBigEndian64(static_cast<const char *>(b) + sizeof(UInt64));
const bool hi_equal = a_hi == b_hi;
const int less = (a_hi < b_hi) | (hi_equal & (a_lo < b_lo));
const int greater = (a_hi > b_hi) | (hi_equal & (a_lo > b_lo));
return greater - less;
}
#else
inline bool lessBigEndian16(const void * a, const void * b)
{
return detail::loadBigEndian128(a) < detail::loadBigEndian128(b);
}
inline int compareBigEndian16(const void * a, const void * b)
{
const unsigned __int128 x = detail::loadBigEndian128(a);
const unsigned __int128 y = detail::loadBigEndian128(b);
return (x > y) - (x < y);
}
#endifbase/base/memcmpSmall.h:
@@ -4,9 +4,9 @@
#include <bit>
#include <cstdint>
+#include <base/bigEndianCompare.h>
#include <base/MemorySanitizer.h>
#include <base/simd.h>
-#include <base/unaligned.h>
namespace detail
{
@@ -21,32 +21,15 @@
return 0;
}
-inline unsigned __int128 loadBigEndian128(const void * p)
-{
- uint64_t hi = unalignedLoad<uint64_t>(p);
- uint64_t lo = unalignedLoad<uint64_t>(static_cast<const char *>(p) + sizeof(hi));
- if constexpr (std::endian::native == std::endian::little)
- {
- hi = std::byteswap(hi);
- lo = std::byteswap(lo);
- }
- return static_cast<unsigned __int128>(hi) << 64 | lo;
-}
-
}
/** Compare memory regions of size 16 exactly.
- * Comparing the operands as big-endian 128-bit integers is branchless (on x86-64: movbe, cmp, sbb, setcc),
- * unlike locating the first differing byte with SIMD, which mispredicts when it is not predictable
- * whether the values are equal.
*/
template <typename Char>
inline int memcmp16(const Char * a, const Char * b)
{
- unsigned __int128 x = detail::loadBigEndian128(a);
- unsigned __int128 y = detail::loadBigEndian128(b);
- return (x > y) - (x < y);
+ return compareBigEndian16(a, b);
}
base/base/IPv4andIPv6.h:
@@ -1,10 +1,8 @@
#pragma once
+#include <base/bigEndianCompare.h>
#include <base/extended_types.h>
#include <base/strong_typedef.h>
-#include <base/unaligned.h>
-
-#include <bit>
namespace DB
@@ -23,28 +21,13 @@
using StrongTypedef::operator=;
/// Ordered by the network byte representation, not by the little-endian UInt128 value.
- /// Comparing the byte-swapped halves as one native 128-bit integer is branchless (cmp + sbb),
- /// which is faster than memcmp16 when it is not predictable whether the values are equal.
- bool operator<(const IPv6 & rhs) const { return asBigEndian() < rhs.asBigEndian(); }
- bool operator>(const IPv6 & rhs) const { return asBigEndian() > rhs.asBigEndian(); }
+ bool operator<(const IPv6 & rhs) const { return lessBigEndian16(&toUnderType(), &rhs.toUnderType()); }
+ bool operator>(const IPv6 & rhs) const { return lessBigEndian16(&rhs.toUnderType(), &toUnderType()); }
bool operator==(const IPv6 & rhs) const { return toUnderType() == rhs.toUnderType(); }
bool operator<=(const IPv6 & rhs) const { return !operator>(rhs); }
bool operator>=(const IPv6 & rhs) const { return !operator<(rhs); }
bool operator!=(const IPv6 & rhs) const { return !operator==(rhs); }
-
- private:
- unsigned __int128 asBigEndian() const
- {
- UInt64 hi = unalignedLoad<UInt64>(&toUnderType());
- UInt64 lo = unalignedLoad<UInt64>(reinterpret_cast<const char *>(&toUnderType()) + sizeof(hi));
- if constexpr (std::endian::native == std::endian::little)
- {
- hi = std::byteswap(hi);
- lo = std::byteswap(lo);
- }
- return static_cast<unsigned __int128>(hi) << 64 | lo;
- }
};
}I applied this on top of c8ca408d0911 and rebuilt src/Functions/less.cpp at each target.
The default v3 build is unchanged, instruction counts per kernel:
| kernel | this PR | with the patch |
|---|---|---|
fixed_string_vector_fixed_string_vector_16 |
117 | 117 |
NumComparisonImpl<IPv6, ...>::vectorVector |
176 | 176 |
NumComparisonImpl<UUID, ...>::vectorVector |
177 | 177 |
ARM is unchanged as well, same ldp / rev / sbcs counts:
| kernel | this PR | with the patch |
|---|---|---|
fixed_string_vector_fixed_string_vector_16 |
30 | 30 |
NumComparisonImpl<IPv6, ...>::vectorVector |
22 | 22 |
NumComparisonImpl<UUID, ...>::vectorVector |
119 | 119 |
At -march=x86-64-v4 the kernels change completely, and all the stack spills disappear:
| kernel | instrs | movbe |
vpcmp*uq |
stack spills | |
|---|---|---|---|---|---|
fixed_string_..._16 |
this PR | 128 | 20 | 0 | 8 |
| with the patch | 169 | 6 | 4 | 0 | |
NumComparisonImpl<IPv6, ...> |
this PR | 303 | 40 | 0 | 30 |
| with the patch | 254 | 0 | 8 | 0 |
Measured, 20M rows per column, ns/row:
| v3 random | v3 50% eq | v4 random | v4 50% eq | |
|---|---|---|---|---|
this PR, memcmp16 three-way |
2.211 | 2.519 | 2.877 | 2.339 |
| with the patch | 2.219 | 2.545 | 1.602 | 1.763 |
this PR, IPv6 operator< |
2.239 | 2.560 | 2.882 | 2.350 |
| with the patch | 2.265 | 2.568 | 1.539 | 1.713 |
One limitation worth knowing: this does not help the default build's AVX-512 runtime clone. NumComparisonImpl's x86_64_v4 clone is generated with __attribute__((target(...))), which changes codegen but not the preprocessor, so the clone still takes the #else branch. I verified that separately: a function carrying the AVX-512 target attribute in a TU compiled at -march=x86-64-v3 does not see __AVX512F__ defined. In that clone the 128-bit form is currently 8 rows per iteration in roughly 145 instructions, about 18 per row, using vpermq / vextracti128 / vpextrq to get lanes out and vpunpcklqdq / vpshufb / vpblendw to put the result bytes back, with stack spills, while the plain scalar loop in the same function is 12 instructions per row with none. Addressing that would need two separately written kernels behind isArchSupported(TargetArch::x86_64_v4), which is a bigger change and reasonable to leave out of this PR.
⚠️ Test coverage for the claimed benefit
tests/performance/uuid_ip_comparison.xml only covers vector vs vector on L1-resident generated data. It does not cover the case this PR improves most, unpredictable equality, nor the constant case, nor =. A query over a materialized column with a controlled fraction of equal pairs would be the smallest thing that demonstrates the actual win.
💡 Nit
src/Core/AccurateComparison.h: instead of weakening the two static_asserts to std::is_same_v<A, B> || is_integer<A>, put the remainder in an else so it is not instantiated for A == B. That keeps the assertion strict and still compiles for UUID. equalsOp has the same shape.
Correctness
I checked the parts that could silently change results and found no problems. asBigEndian orders by byte 0 first, matching memcmp over the 16 stored bytes, so IPv6 ordering is unchanged. The old memcmp16 would have done a signed byte compare for a const char * instantiation, but every caller passes UInt8 or uint8_t, so moving to an unsigned 128-bit compare changes nothing. executeNumRightType returns nullptr for anything that is not a ColumnVector or ColumnConst, so unusual column kinds still fall through to the old generic path. All six operators stay consistent with CompareHelper, which is what sorting uses.
| return 0; | ||
| } | ||
|
|
||
| inline unsigned __int128 loadBigEndian128(const void * p) |
There was a problem hiding this comment.
I think we can move this to a different header and make it faster for AVX512, which is not a requirement and it's not worth dynamic dispatching but it's easy to do. I'll share it in a LLM-assisted comment
| template <typename Char> | ||
| inline int memcmp16(const Char * a, const Char * b) | ||
| { | ||
| unsigned __int128 x = detail::loadBigEndian128(a); |
…e it on AVX-512 `memcmp16` and the `IPv6` ordering operators shared a duplicated big-endian 128-bit loader. Both now call `compareBigEndian16` and `lessBigEndian16` from `base/bigEndianCompare.h`. When the target has AVX-512 (`vpcmpuq`), the two 64-bit halves are compared separately so that the enclosing loop vectorizes. Otherwise one native 128-bit compare stays the default, because without an unsigned 64-bit vector compare the vectorized form is slower. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Put the mixed-type remainder of `lessOp` in an `else` branch so that it is not instantiated for `A == B`, instead of weakening the assertions. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ison performance test Compare materialized columns of a `Memory` table where half of the pairs are equal in an unpredictable pattern, which is the case that the branchless 16-byte comparison improves most. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Stress test failure is unrelated and being worked in #108357 |
dc91926
Comparisons of
UUID,IPv4andIPv6columns with a column or constant of the same type went through the generic path (one virtualcompareAtcall per row), becauseColumnVector::isNumericis false for these types. Now they use the sameNumComparisonImplloop as the numeric types. TheIPv6comparison operators are moved inline so that this loop does not call an out-of-line function per row.memcmp16, which is used forFixedString(16)comparison and by theip_triedictionary, now compares the operands as big-endian 128-bit integers (base/bigEndianCompare.h) instead of locating the first differing byte with SIMD. On x86-64 this is a trade-off, not a pure win: the comparison is branchless, so it is about 2x faster when it is not predictable whether the values are equal (sorting, binary search inip_trie, joins), but the isolated kernel is about 1.5x slower than the SIMD version when the values almost always differ. On AArch64 the branchless form is faster in both cases. With AVX-512 the two 64-bit halves are compared separately so that the loop vectorizes withvpcmpuq.Measured on a 20M-row
Memorytable, single thread, x86-64-v3, best of 3 (seconds, master -> this PR).bis equal toain half of the rows in an unpredictable pattern,cis random:a < ca < ba = ba < constUUIDIPv4IPv6FixedString(16)Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Vectorized comparison of
UUID,IPv4andIPv6columns with a column or constant of the same type, which makes such comparisons several times faster. Comparison ofFixedString(16)values is now branchless, which makes it faster when it is not predictable whether the values are equal.Workflow [PR]
Sync PR [sync-upstream/pr/120193]