From: tureba (@tureba) <noreply+tureba@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] issue #985: Regression on PG 18+ in BitHammingDistanceDefault and BitJaccardDistanceDefault
Date: Thu, 11 Jun 2026 00:11:48 +0000
Message-ID: <gh-pgvector-pgvector-985@github.com> (raw)
PostgreSQL 18 removed the macros `HAVE_LONG_INT_64` and `HAVE_LONG_LONG_INT_64` in [962da90](https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=962da900ac8f0927f1af2fd811ca67fa163c8...).
That means the logic in [bitutils.c:34](https://github.com/pgvector/pgvector/blob/master/src/bitutils.c#L34) resolves differently. This is the spot:
```c
/* Use built-ins when possible for inlining */
#if defined(HAVE__BUILTIN_POPCOUNT) && defined(HAVE_LONG_INT_64)
#define popcount64(x) __builtin_popcountl(x)
#elif defined(HAVE__BUILTIN_POPCOUNT) && defined(HAVE_LONG_LONG_INT_64)
#define popcount64(x) __builtin_popcountll(x)
#elif !defined(_MSC_VER)
/* Fails to resolve with MSVC */
#define popcount64(x) pg_popcount64(x)
#endif
```
In PG<18, it usually resolved to the builtins, but those `defined(HAVE_LONG*INT_64)` won't ever be true anymore. Now it generates code that falls back to the `pg_popcount64` function pointer, which is an indirect call per 64-bit word, that is much slower than the inlined alternatives.
The only case not affected by this is x86 with `AVX512-VPOPCNTDQ`, because of the specific implementations and dispatch. Otherwise, all architectures will see this regression of `<~>` and `<%>` in PG 18 when compared to PG<18.
From my testing, fixing this can be as simple as gating on `HAVE__BUILTIN_POPCOUNT` alone, and using `__builtin_popcountll`, which operates on unsigned long long, ≥64-bit by C99, fits uint64; correct on all ABIs and avoids the latent LLP64 truncation of `__builtin_popcountl`:
```c
#if defined(HAVE__BUILTIN_POPCOUNT)
#define popcount64(x) __builtin_popcountll(x)
#elif !defined(_MSC_VER)
#define popcount64(x) pg_popcount64(x)
#endif
```