From 52cb6bd6c7b4eb6d587f7225468caf9274db1c94 Mon Sep 17 00:00:00 2001 From: Maurus Decimus <11444311+mdecimus@users.noreply.github.com> Date: Fri, 2 Oct 2026 17:36:31 +0200 Subject: [PATCH] SSSE3 tier vectorises --- benches/kernels.rs | 76 ++++++++++++++++- src/scan/mod.rs | 19 ++++- src/scan/neon.rs | 100 ++++++++++++++-------- src/scan/simd.rs | 120 +++++++++++++++++++------- src/scan/x86.rs | 207 ++++++++++++++++++++++++++++++++------------- 5 files changed, 390 insertions(+), 132 deletions(-) diff --git a/benches/kernels.rs b/benches/kernels.rs index 655e95a..b8dd87e 100644 --- a/benches/kernels.rs +++ b/benches/kernels.rs @@ -9,9 +9,9 @@ mod corpus; use corpus::{LineEnding, Sample}; use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; -use mail_parser::scan::Kernel; +use mail_parser::{HeaderValue, Message, MessageParser, scan::Kernel}; use memchr::{memchr_iter, memmem}; -use std::{hint::black_box, time::Duration}; +use std::{fmt::Write, hint::black_box, time::Duration}; fn body_of(sample: &Sample) -> &[u8] { memmem::find(&sample.bytes, b"\n\n") @@ -182,6 +182,76 @@ fn field_split(c: &mut Criterion) { group.finish(); } +const ADDRESS_LIST_SIZES: [usize; 3] = [8, 64, 512]; + +fn address_list(mailboxes: usize) -> Vec { + let mut out = String::from("From: \"Release Bot (automated)\" \r\n"); + for (header, offset) in [("To", 0), ("Cc", 1)] { + let _ = write!(out, "{header}: "); + for index in 0..mailboxes { + if index > 0 { + out.push_str(",\r\n "); + } + let _ = write!( + out, + "\"Recipient {index} (team {})\" ", + index % 5, + (index + offset) % 7 + ); + } + out.push_str("\r\n"); + } + out.push_str("Subject: Weekly release\r\nDate: Tue, 3 Sep 2024 10:00:00 +0000\r\n\r\nbody\r\n"); + out.into_bytes() +} + +fn addresses_of(message: &Message<'_>) -> usize { + let mut total = 0; + for part in message.parts() { + for header in part.headers().iter() { + if let HeaderValue::Address(list) = header.value() { + total += list + .mailboxes() + .map(|mailbox| { + mailbox.name().map_or(0, str::len) + mailbox.address().map_or(0, str::len) + }) + .sum::(); + } + } + } + total +} + +fn header_values(c: &mut Criterion) { + let parser = MessageParser::new(); + let mut group = c.benchmark_group("header_values"); + let mut inputs: Vec<(String, Vec>)> = ADDRESS_LIST_SIZES + .iter() + .map(|&size| (format!("address-list-{size}"), vec![address_list(size)])) + .collect(); + inputs.push(( + "modern-headers".to_string(), + header_messages(LineEnding::Crlf), + )); + for (name, messages) in inputs { + if messages.is_empty() { + continue; + } + let bytes: usize = messages.iter().map(Vec::len).sum(); + group.throughput(Throughput::Bytes(bytes as u64)); + group.bench_function(BenchmarkId::new(Kernel::best().name(), name), |b| { + b.iter(|| { + messages + .iter() + .filter_map(|raw| parser.parse_headers(black_box(raw))) + .map(|message| addresses_of(&message)) + .sum::() + }) + }); + } + group.finish(); +} + fn config() -> Criterion { Criterion::default() .warm_up_time(Duration::from_millis(500)) @@ -192,6 +262,6 @@ fn config() -> Criterion { criterion_group! { name = benches; config = config(); - targets = delimiter_scan, blank_line, field_split + targets = delimiter_scan, blank_line, field_split, header_values } criterion_main!(benches); diff --git a/src/scan/mod.rs b/src/scan/mod.rs index 6dbe0d0..1114eea 100644 --- a/src/scan/mod.rs +++ b/src/scan/mod.rs @@ -55,6 +55,8 @@ enum Backend { #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] Sse2, #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + Ssse3, + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] Avx2, } @@ -66,7 +68,8 @@ impl Kernel { pub const MEMCHR: Kernel = Kernel(Backend::Memchr); /// The fastest back end supported by the running CPU: NEON on aarch64, - /// AVX2 when detected or else SSE2 on x86_64, `memchr` elsewhere. + /// AVX2 or else SSSE3 when detected or else SSE2 on x86_64, `memchr` + /// elsewhere. pub fn best() -> Self { #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] { @@ -76,6 +79,8 @@ impl Kernel { { if std::is_x86_feature_detected!("avx2") { Kernel(Backend::Avx2) + } else if std::is_x86_feature_detected!("ssse3") { + Kernel(Backend::Ssse3) } else { Kernel(Backend::Sse2) } @@ -99,6 +104,8 @@ impl Kernel { #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] Some(Kernel(Backend::Sse2)), #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + std::is_x86_feature_detected!("ssse3").then_some(Kernel(Backend::Ssse3)), + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] std::is_x86_feature_detected!("avx2").then_some(Kernel(Backend::Avx2)), ] .into_iter() @@ -115,6 +122,8 @@ impl Kernel { #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] Backend::Sse2 => "sse2", #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + Backend::Ssse3 => "ssse3", + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] Backend::Avx2 => "avx2", } } @@ -129,7 +138,7 @@ impl Kernel { #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] Backend::Neon => neon::dash_line(hay, from), #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] - Backend::Sse2 => x86::sse2_dash_line(hay, from), + Backend::Sse2 | Backend::Ssse3 => x86::sse2_dash_line(hay, from), #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] Backend::Avx2 => x86::avx2_dash_line(hay, from), } @@ -145,7 +154,7 @@ impl Kernel { #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] Backend::Neon => neon::field_end(hay, from), #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] - Backend::Sse2 => x86::sse2_field_end(hay, from), + Backend::Sse2 | Backend::Ssse3 => x86::sse2_field_end(hay, from), #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] Backend::Avx2 => x86::avx2_field_end(hay, from), } @@ -166,6 +175,8 @@ impl Kernel { #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] Backend::Sse2 => set.sse2_first_in(hay, from, end), #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + Backend::Ssse3 => set.ssse3_first_in(hay, from, end), + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] Backend::Avx2 => set.avx2_first_in(hay, from, end), } } @@ -179,6 +190,8 @@ impl Kernel { #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] Backend::Sse2 => set.sse2_stop_in(hay, from, end), #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + Backend::Ssse3 => set.ssse3_stop_in(hay, from, end), + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] Backend::Avx2 => set.avx2_stop_in(hay, from, end), } } diff --git a/src/scan/neon.rs b/src/scan/neon.rs index 0f3c493..e54ecca 100644 --- a/src/scan/neon.rs +++ b/src/scan/neon.rs @@ -8,10 +8,12 @@ use super::{ set::{ByteSet, Stop}, - simd::{self, Vector}, + simd::{self, Table, Vector}, }; use core::arch::aarch64::*; +const NIBBLE: u8 = 0x0f; + impl Vector for uint8x16_t { const BYTES: usize = 16; const BITS_PER_BYTE: u32 = 4; @@ -77,6 +79,42 @@ impl Vector for uint8x16_t { } } +impl Table for uint8x16_t { + #[inline(always)] + unsafe fn table(entries: &[u8; 16]) -> Self { + // SAFETY: the module is built only with `target_feature = "neon"`, so + // NEON is part of the compilation target and present at run time. + // `entries` is 16 bytes, exactly what the load reads. + unsafe { vld1q_u8(entries.as_ptr()) } + } + + #[inline(always)] + unsafe fn lookup_low(self, table: Self) -> Self { + // SAFETY: the module is built only with `target_feature = "neon"`, so + // NEON is part of the compilation target and present at run time. The + // intrinsics work on registers only, and the mask keeps every index + // below 16, so no lane selects outside `table`. + unsafe { vqtbl1q_u8(table, vandq_u8(self, vdupq_n_u8(NIBBLE))) } + } + + #[inline(always)] + unsafe fn lookup_high(self, table: Self) -> Self { + // SAFETY: the module is built only with `target_feature = "neon"`, so + // NEON is part of the compilation target and present at run time. The + // intrinsics work on registers only, and shifting a byte right by four + // leaves every index below 16, so no lane selects outside `table`. + unsafe { vqtbl1q_u8(table, vshrq_n_u8::<4>(self)) } + } + + #[inline(always)] + unsafe fn test_mask(self, mask: Self) -> u64 { + // SAFETY: the module is built only with `target_feature = "neon"`, so + // NEON is part of the compilation target and present at run time. The + // intrinsics work on registers only. + unsafe { vtstq_u8(self, mask).mask() } + } +} + #[inline] pub(crate) fn dash_line(hay: &[u8], from: usize) -> Option { // SAFETY: NEON is enabled at compile time (the module is built only @@ -96,50 +134,38 @@ pub(crate) fn field_end(hay: &[u8], from: usize) -> Option { impl ByteSet { #[inline] pub(super) fn neon_first_in(&self, hay: &[u8], from: usize, end: usize) -> Option { - // SAFETY: NEON is enabled at compile time (the module is built only with - // `target_feature = "neon"`). `self.low` and `self.high` are `[u8; 16]`, so - // their loads read exactly their 16 bytes. `ByteSet::simd_first_in` passes the - // closure only pointers with `SET_WIDTH` (16) bytes of `hay` behind them, - // and the closure reads those 16 bytes with one `vld1q_u8`. + // SAFETY: NEON is enabled at compile time (the module is built only + // with `target_feature = "neon"`), which is what `uint8x16_t` needs as + // both a `Vector` and a `Table`. `self.low` and `self.high` are + // `[u8; 16]`, the size `Table::table` reads, and the closure reads the + // `V::BYTES` bytes that `simd_first_in` guarantees behind the pointer it + // gets. unsafe { - let low = vld1q_u8(self.low.as_ptr()); - let high = vld1q_u8(self.high.as_ptr()); - let nibble = vdupq_n_u8(0x0f); - let stops = vdupq_n_u8(self.stops); - self.simd_first_in(hay, from, end, uint8x16_t::BITS_PER_BYTE, |at| { - let bytes = vld1q_u8(at); - let buckets = vandq_u8( - vqtbl1q_u8(low, vandq_u8(bytes, nibble)), - vqtbl1q_u8(high, vshrq_n_u8::<4>(bytes)), - ); - vtstq_u8(buckets, stops).mask() + let low = uint8x16_t::table(&self.low); + let high = uint8x16_t::table(&self.high); + let stops = uint8x16_t::splat(self.stops); + self.simd_first_in::(hay, from, end, |at| { + simd::buckets::(at, low, high).test_mask(stops) }) } } #[inline] pub(super) fn neon_stop_in(&self, hay: &[u8], from: usize, end: usize) -> Stop { - // SAFETY: NEON is enabled at compile time (the module is built only with - // `target_feature = "neon"`). `self.low` and `self.high` are `[u8; 16]`, so - // their loads read exactly their 16 bytes. `ByteSet::simd_stop_in` passes the - // closure only pointers with `SET_WIDTH` (16) bytes of `hay` behind them, - // and the closure reads those 16 bytes with one `vld1q_u8`. + // SAFETY: NEON is enabled at compile time (the module is built only + // with `target_feature = "neon"`), which is what `uint8x16_t` needs as + // both a `Vector` and a `Table`. `self.low` and `self.high` are + // `[u8; 16]`, the size `Table::table` reads, and the closure reads the + // `V::BYTES` bytes that `simd_stop_in` guarantees behind the pointer it + // gets. unsafe { - let low = vld1q_u8(self.low.as_ptr()); - let high = vld1q_u8(self.high.as_ptr()); - let nibble = vdupq_n_u8(0x0f); - let stops = vdupq_n_u8(self.stops); - let marks = vdupq_n_u8(self.marks); - self.simd_stop_in(hay, from, end, uint8x16_t::BITS_PER_BYTE, |at| { - let bytes = vld1q_u8(at); - let buckets = vandq_u8( - vqtbl1q_u8(low, vandq_u8(bytes, nibble)), - vqtbl1q_u8(high, vshrq_n_u8::<4>(bytes)), - ); - ( - vtstq_u8(buckets, stops).mask(), - vtstq_u8(buckets, marks).mask(), - ) + let low = uint8x16_t::table(&self.low); + let high = uint8x16_t::table(&self.high); + let stops = uint8x16_t::splat(self.stops); + let marks = uint8x16_t::splat(self.marks); + self.simd_stop_in::(hay, from, end, |at| { + let buckets = simd::buckets::(at, low, high); + (buckets.test_mask(stops), buckets.test_mask(marks)) }) } } diff --git a/src/scan/simd.rs b/src/scan/simd.rs index d1d6a64..0fcd35b 100644 --- a/src/scan/simd.rs +++ b/src/scan/simd.rs @@ -73,10 +73,51 @@ pub(crate) trait Vector: Copy { unsafe fn mask(self) -> u64; } +/// Byte-table lookup, used to classify bytes by the buckets of a [`ByteSet`]. +/// +/// An implementation can need a larger instruction set than [`Vector`] asks +/// for the same type: `__m128i` needs SSSE3 here where [`Vector`] needs only +/// SSE2. +pub(crate) trait Table: Vector { + /// Loads a 16-entry byte table into every 128-bit lane. + /// + /// # Safety + /// + /// The running CPU must support the table instruction set of the + /// implementing type. + unsafe fn table(entries: &[u8; 16]) -> Self; + + /// Replaces every byte of `self` with the `table` entry its low nibble + /// selects. + /// + /// # Safety + /// + /// The running CPU must support the table instruction set of the + /// implementing type. + unsafe fn lookup_low(self, table: Self) -> Self; + + /// Replaces every byte of `self` with the `table` entry its high nibble + /// selects. + /// + /// # Safety + /// + /// The running CPU must support the table instruction set of the + /// implementing type. + unsafe fn lookup_high(self, table: Self) -> Self; + + /// Packs the lanes where `self & mask` is non-zero into [`Vector::mask`] + /// form. + /// + /// # Safety + /// + /// The running CPU must support the table instruction set of the + /// implementing type. + unsafe fn test_mask(self, mask: Self) -> u64; +} + const UNROLL: usize = 4; const DASH_LOOKAHEAD: usize = 2; const FOLD_LOOKAHEAD: usize = 1; -const SET_WIDTH: usize = 16; #[inline(always)] fn first(mask: u64) -> usize { @@ -211,21 +252,20 @@ pub(crate) unsafe fn field_end(tail: &[u8]) -> Option { } impl ByteSet { - /// First byte of the set in `hay[from..end]`, testing `SET_WIDTH` bytes per + /// First byte of the set in `hay[from..end]`, testing `V::BYTES` bytes per /// call of `mask_at`. /// /// # Safety /// - /// `mask_at` must read at most `SET_WIDTH` bytes from the pointer it gets + /// `mask_at` must read at most `V::BYTES` bytes from the pointer it gets /// and must otherwise be sound to call on the running CPU: this function - /// passes it only pointers with `SET_WIDTH` bytes of `hay` behind them. + /// passes it only pointers with `V::BYTES` bytes of `hay` behind them. #[inline(always)] - pub(super) unsafe fn simd_first_in( + pub(super) unsafe fn simd_first_in( &self, hay: &[u8], from: usize, end: usize, - bits_per_byte: u32, mask_at: impl Fn(*const u8) -> u64, ) -> Option { let end = end.min(hay.len()); @@ -234,13 +274,13 @@ impl ByteSet { } let ptr = hay.as_ptr(); let first = |offset: usize, mask: u64| { - let hit = offset + (mask.trailing_zeros() / bits_per_byte) as usize; + let hit = offset + (mask.trailing_zeros() / V::BITS_PER_BYTE) as usize; (hit < end).then_some(hit) }; let mut offset = from; - while offset + SET_WIDTH <= hay.len() { - // SAFETY: the loop condition keeps `offset + SET_WIDTH` within - // `hay.len()`, so `ptr + offset` and the `SET_WIDTH` bytes that + while offset + V::BYTES <= hay.len() { + // SAFETY: the loop condition keeps `offset + V::BYTES` within + // `hay.len()`, so `ptr + offset` and the `V::BYTES` bytes that // `mask_at` reads from it lie inside `hay`. `offset` starts below // `end <= hay.len()` and the loop returns once it reaches `end`, so // the addition cannot overflow. @@ -248,18 +288,18 @@ impl ByteSet { if mask != 0 { return first(offset, mask); } - offset += SET_WIDTH; + offset += V::BYTES; if offset >= end { return None; } } - match hay.len().checked_sub(SET_WIDTH) { + match hay.len().checked_sub(V::BYTES) { Some(base) => { - let skipped = (offset - base) as u32 * bits_per_byte; - // SAFETY: `base` is `hay.len() - SET_WIDTH` and the subtraction - // did not underflow, so the `SET_WIDTH` bytes at `ptr + base` are + let skipped = (offset - base) as u32 * V::BITS_PER_BYTE; + // SAFETY: `base` is `hay.len() - V::BYTES` and the subtraction + // did not underflow, so the `V::BYTES` bytes at `ptr + base` are // the last ones of `hay`. The loop exited with - // `offset + SET_WIDTH > hay.len()`, so `offset > base` and the + // `offset + V::BYTES > hay.len()`, so `offset > base` and the // shift drops the bytes before `offset`. let mask = mask_at(unsafe { ptr.add(base) }) >> skipped; if mask != 0 { first(offset, mask) } else { None } @@ -269,30 +309,29 @@ impl ByteSet { } /// First byte of the stop set in `hay[from..end]`, and whether a marked byte - /// comes before it, testing `SET_WIDTH` bytes per call of `masks_at`. + /// comes before it, testing `V::BYTES` bytes per call of `masks_at`. /// /// # Safety /// - /// `masks_at` must read at most `SET_WIDTH` bytes from the pointer it gets + /// `masks_at` must read at most `V::BYTES` bytes from the pointer it gets /// and must otherwise be sound to call on the running CPU: this function - /// passes it only pointers with `SET_WIDTH` bytes of `hay` behind them. + /// passes it only pointers with `V::BYTES` bytes of `hay` behind them. #[inline(always)] - pub(super) unsafe fn simd_stop_in( + pub(super) unsafe fn simd_stop_in( &self, hay: &[u8], from: usize, end: usize, - bits_per_byte: u32, masks_at: impl Fn(*const u8) -> (u64, u64), ) -> Stop { let end = end.min(hay.len()); let mut marked = false; let mut offset = from; while offset < end { - let base = if offset + SET_WIDTH <= hay.len() { + let base = if offset + V::BYTES <= hay.len() { offset } else { - match hay.len().checked_sub(SET_WIDTH) { + match hay.len().checked_sub(V::BYTES) { Some(base) => base, None => { let rest = self.stop_in(hay, offset, end); @@ -303,31 +342,48 @@ impl ByteSet { } } }; - let skipped = (offset - base) as u32 * bits_per_byte; - // SAFETY: `base` is `offset` when `offset + SET_WIDTH <= hay.len()`, - // else `hay.len() - SET_WIDTH` when that does not underflow (a + let skipped = (offset - base) as u32 * V::BITS_PER_BYTE; + // SAFETY: `base` is `offset` when `offset + V::BYTES <= hay.len()`, + // else `hay.len() - V::BYTES` when that does not underflow (a // shorter `hay` returned through the safe `ByteSet::stop_in` above), - // so the `SET_WIDTH` bytes that `masks_at` reads from + // so the `V::BYTES` bytes that `masks_at` reads from // `hay.as_ptr() + base` lie inside `hay`. `offset < end <= hay.len()` - // keeps `offset + SET_WIDTH` from overflowing. + // keeps `offset + V::BYTES` from overflowing. let (stops, marks) = masks_at(unsafe { hay.as_ptr().add(base) }); - let valid = low_bits(end - offset, bits_per_byte); + let valid = low_bits(end - offset, V::BITS_PER_BYTE); let stops = (stops >> skipped) & valid; let marks = (marks >> skipped) & valid; if stops != 0 { - let first = stops.trailing_zeros() / bits_per_byte; + let first = stops.trailing_zeros() / V::BITS_PER_BYTE; return Stop { at: Some(offset + first as usize), - marked: marked || marks & low_bits(first as usize, bits_per_byte) != 0, + marked: marked || marks & low_bits(first as usize, V::BITS_PER_BYTE) != 0, }; } marked |= marks != 0; - offset = base + SET_WIDTH; + offset = base + V::BYTES; } Stop { at: None, marked } } } +/// The bucket byte of every byte at `at`, to be tested against the `stops` and +/// `marks` of the [`ByteSet`] the tables come from. +/// +/// # Safety +/// +/// `at` must be valid for reads of `V::BYTES` bytes, and the running CPU must +/// support the [`Vector`] and [`Table`] instruction sets of `V`. +#[inline(always)] +pub(super) unsafe fn buckets(at: *const u8, low: V, high: V) -> V { + // SAFETY: our caller guarantees `at` is readable for `V::BYTES` bytes and + // that the running CPU supports `V` as both a `Vector` and a `Table`. + unsafe { + let bytes = V::load(at); + bytes.lookup_low(low).and(bytes.lookup_high(high)) + } +} + #[inline(always)] fn low_bits(bytes: usize, bits_per_byte: u32) -> u64 { match u32::try_from(bytes).map(|bytes| bytes.saturating_mul(bits_per_byte)) { diff --git a/src/scan/x86.rs b/src/scan/x86.rs index 75783cc..f9a2929 100644 --- a/src/scan/x86.rs +++ b/src/scan/x86.rs @@ -8,10 +8,12 @@ use super::{ set::{ByteSet, Stop}, - simd::{self, Vector}, + simd::{self, Table, Vector}, }; use core::arch::x86_64::*; +const NIBBLE: i8 = 0x0f; + impl Vector for __m128i { const BYTES: usize = 16; const BITS_PER_BYTE: u32 = 1; @@ -74,6 +76,51 @@ impl Vector for __m128i { } } +impl Table for __m128i { + #[inline(always)] + unsafe fn table(entries: &[u8; 16]) -> Self { + // SAFETY: the module is built only with `target_feature = "sse2"`, so + // SSE2 is part of the compilation target and present at run time. + // `entries` is 16 bytes, exactly what the unaligned load reads. + unsafe { _mm_loadu_si128(entries.as_ptr().cast()) } + } + + #[inline(always)] + unsafe fn lookup_low(self, table: Self) -> Self { + // SAFETY: our caller guarantees the CPU supports SSSE3, which + // `_mm_shuffle_epi8` needs; the other intrinsics need only SSE2. All + // three work on registers only, and the mask keeps every shuffle index + // below 16, so no lane selects outside `table`. + unsafe { _mm_shuffle_epi8(table, _mm_and_si128(self, _mm_set1_epi8(NIBBLE))) } + } + + #[inline(always)] + unsafe fn lookup_high(self, table: Self) -> Self { + // SAFETY: our caller guarantees the CPU supports SSSE3, which + // `_mm_shuffle_epi8` needs; the other intrinsics need only SSE2. All + // four work on registers only, and the mask keeps every shuffle index + // below 16, so no lane selects outside `table`. + unsafe { + _mm_shuffle_epi8( + table, + _mm_and_si128(_mm_srli_epi16::<4>(self), _mm_set1_epi8(NIBBLE)), + ) + } + } + + #[inline(always)] + unsafe fn test_mask(self, mask: Self) -> u64 { + // SAFETY: the module is built only with `target_feature = "sse2"`, so + // SSE2 is part of the compilation target and present at run time. The + // intrinsics work on registers only. + unsafe { + let hits = _mm_and_si128(self, mask); + let zeros = _mm_movemask_epi8(_mm_cmpeq_epi8(hits, _mm_setzero_si128())); + u64::from(!(zeros as u32) & 0xffff) + } + } +} + impl Vector for __m256i { const BYTES: usize = 32; const BITS_PER_BYTE: u32 = 1; @@ -201,10 +248,10 @@ impl ByteSet { // SAFETY: the module is built only with `target_feature = "sse2"`, so // SSE2 is present, and the closure uses only SSE2 intrinsics and the // `__m128i` methods. `ByteSet::simd_first_in` passes the closure only - // pointers with `SET_WIDTH` (16) bytes of `hay` behind them, and - // `__m128i::load` reads those 16 bytes. + // pointers with `__m128i::BYTES` bytes of `hay` behind them, and + // `__m128i::load` reads those bytes. unsafe { - self.simd_first_in(hay, from, end, __m128i::BITS_PER_BYTE, |at| { + self.simd_first_in::<__m128i>(hay, from, end, |at| { let bytes = __m128i::load(at); self.members() .iter() @@ -216,43 +263,66 @@ impl ByteSet { } } + /// # Safety + /// + /// The running CPU must support SSSE3. + #[target_feature(enable = "ssse3")] + unsafe fn ssse3_first_in_impl(&self, hay: &[u8], from: usize, end: usize) -> Option { + // SAFETY: our caller guarantees the CPU supports SSSE3 and this + // function enables it, which covers what `__m128i` needs: SSE2 as a `Vector` and SSSE3 as a `Table`. + // The closure is defined here so that it inherits the enabled feature, + // and reads the `V::BYTES` bytes that `simd_first_in` guarantees behind the + // pointer it gets. + unsafe { + let low = __m128i::table(&self.low); + let high = __m128i::table(&self.high); + let stops = __m128i::splat(self.stops); + self.simd_first_in::<__m128i>(hay, from, end, |at| { + simd::buckets::<__m128i>(at, low, high).test_mask(stops) + }) + } + } + + #[inline] + pub(super) fn ssse3_first_in(&self, hay: &[u8], from: usize, end: usize) -> Option { + // SAFETY: the CPU supports SSSE3. This method is reached only from + // the `Kernel` dispatch in `scan/mod.rs` on `Backend::Ssse3`: it is + // `pub(super)` in `x86`, a private module of `scan`, `Backend` and the + // field of `Kernel` are private to `scan`, and `Kernel::best` and + // `Kernel::available` build that back end only after + // `is_x86_feature_detected!("ssse3")` returned true. + unsafe { self.ssse3_first_in_impl(hay, from, end) } + } + /// # Safety /// /// The running CPU must support AVX2. #[target_feature(enable = "avx2")] unsafe fn avx2_first_in_impl(&self, hay: &[u8], from: usize, end: usize) -> Option { - // SAFETY: our caller guarantees the CPU supports AVX2, and this function - // enables it; AVX2 implies SSSE3 (`_mm_shuffle_epi8`) and SSE2, the only - // instruction sets used here. `self.low` and `self.high` are `[u8; 16]`, so - // their unaligned 16-byte loads stay inside them. `ByteSet::simd_first_in` - // passes the closure only pointers with `SET_WIDTH` (16) bytes of `hay` - // behind them, and the closure reads those 16 bytes with one unaligned - // load. + // SAFETY: our caller guarantees the CPU supports AVX2 and this + // function enables it, which implies both instruction sets `__m128i` + // needs: SSE2 as a `Vector` and SSSE3 as a `Table`. Enabling AVX2 keeps + // these 128-bit operations VEX-encoded, so they do not pay an AVX to SSE + // transition. The closure is defined here so that it inherits the + // enabled feature, and reads the `V::BYTES` bytes that `simd_first_in` + // guarantees behind the pointer it gets. unsafe { - let low = _mm_loadu_si128(self.low.as_ptr().cast()); - let high = _mm_loadu_si128(self.high.as_ptr().cast()); - let nibble = _mm_set1_epi8(0x0f); - let stops = _mm_set1_epi8(self.stops as i8); - let zero = _mm_setzero_si128(); - self.simd_first_in(hay, from, end, __m128i::BITS_PER_BYTE, |at| { - let bytes = _mm_loadu_si128(at.cast()); - let buckets = _mm_and_si128( - _mm_shuffle_epi8(low, _mm_and_si128(bytes, nibble)), - _mm_shuffle_epi8(high, _mm_and_si128(_mm_srli_epi16::<4>(bytes), nibble)), - ); - let hits = _mm_and_si128(buckets, stops); - u64::from(!(_mm_movemask_epi8(_mm_cmpeq_epi8(hits, zero)) as u32) & 0xffff) + let low = __m128i::table(&self.low); + let high = __m128i::table(&self.high); + let stops = __m128i::splat(self.stops); + self.simd_first_in::<__m128i>(hay, from, end, |at| { + simd::buckets::<__m128i>(at, low, high).test_mask(stops) }) } } #[inline] pub(super) fn avx2_first_in(&self, hay: &[u8], from: usize, end: usize) -> Option { - // SAFETY: the CPU supports AVX2. This method is reached only from the - // `Kernel` dispatch in `scan/mod.rs` on `Backend::Avx2`: it is + // SAFETY: the CPU supports AVX2. This method is reached only from + // the `Kernel` dispatch in `scan/mod.rs` on `Backend::Avx2`: it is // `pub(super)` in `x86`, a private module of `scan`, `Backend` and the // field of `Kernel` are private to `scan`, and `Kernel::best` and - // `Kernel::available` build `Backend::Avx2` only after + // `Kernel::available` build that back end only after // `is_x86_feature_detected!("avx2")` returned true. unsafe { self.avx2_first_in_impl(hay, from, end) } } @@ -265,10 +335,10 @@ impl ByteSet { // SAFETY: the module is built only with `target_feature = "sse2"`, so // SSE2 is present, and the closure uses only SSE2 intrinsics and the // `__m128i` methods. `ByteSet::simd_stop_in` passes the closure only - // pointers with `SET_WIDTH` (16) bytes of `hay` behind them, and - // `__m128i::load` reads those 16 bytes. + // pointers with `__m128i::BYTES` bytes of `hay` behind them, and + // `__m128i::load` reads those bytes. unsafe { - self.simd_stop_in(hay, from, end, __m128i::BITS_PER_BYTE, |at| { + self.simd_stop_in::<__m128i>(hay, from, end, |at| { let bytes = __m128i::load(at); let any = |members: &[u8]| { members @@ -283,47 +353,70 @@ impl ByteSet { } } + /// # Safety + /// + /// The running CPU must support SSSE3. + #[target_feature(enable = "ssse3")] + unsafe fn ssse3_stop_in_impl(&self, hay: &[u8], from: usize, end: usize) -> Stop { + // SAFETY: our caller guarantees the CPU supports SSSE3 and this + // function enables it, which covers what `__m128i` needs: SSE2 as a `Vector` and SSSE3 as a `Table`. + // The closure is defined here so that it inherits the enabled feature, + // and reads the `V::BYTES` bytes that `simd_stop_in` guarantees behind the + // pointer it gets. + unsafe { + let low = __m128i::table(&self.low); + let high = __m128i::table(&self.high); + let stops = __m128i::splat(self.stops); + let marks = __m128i::splat(self.marks); + self.simd_stop_in::<__m128i>(hay, from, end, |at| { + let buckets = simd::buckets::<__m128i>(at, low, high); + (buckets.test_mask(stops), buckets.test_mask(marks)) + }) + } + } + + #[inline] + pub(super) fn ssse3_stop_in(&self, hay: &[u8], from: usize, end: usize) -> Stop { + // SAFETY: the CPU supports SSSE3. This method is reached only from + // the `Kernel` dispatch in `scan/mod.rs` on `Backend::Ssse3`: it is + // `pub(super)` in `x86`, a private module of `scan`, `Backend` and the + // field of `Kernel` are private to `scan`, and `Kernel::best` and + // `Kernel::available` build that back end only after + // `is_x86_feature_detected!("ssse3")` returned true. + unsafe { self.ssse3_stop_in_impl(hay, from, end) } + } + /// # Safety /// /// The running CPU must support AVX2. #[target_feature(enable = "avx2")] unsafe fn avx2_stop_in_impl(&self, hay: &[u8], from: usize, end: usize) -> Stop { - // SAFETY: our caller guarantees the CPU supports AVX2, and this function - // enables it; AVX2 implies SSSE3 (`_mm_shuffle_epi8`) and SSE2, the only - // instruction sets used here. `self.low` and `self.high` are `[u8; 16]`, so - // their unaligned 16-byte loads stay inside them. `ByteSet::simd_stop_in` - // passes the closure only pointers with `SET_WIDTH` (16) bytes of `hay` - // behind them, and the closure reads those 16 bytes with one unaligned - // load. + // SAFETY: our caller guarantees the CPU supports AVX2 and this + // function enables it, which implies both instruction sets `__m128i` + // needs: SSE2 as a `Vector` and SSSE3 as a `Table`. Enabling AVX2 keeps + // these 128-bit operations VEX-encoded, so they do not pay an AVX to SSE + // transition. The closure is defined here so that it inherits the + // enabled feature, and reads the `V::BYTES` bytes that `simd_stop_in` + // guarantees behind the pointer it gets. unsafe { - let low = _mm_loadu_si128(self.low.as_ptr().cast()); - let high = _mm_loadu_si128(self.high.as_ptr().cast()); - let nibble = _mm_set1_epi8(0x0f); - let stops = _mm_set1_epi8(self.stops as i8); - let marks = _mm_set1_epi8(self.marks as i8); - let zero = _mm_setzero_si128(); - self.simd_stop_in(hay, from, end, __m128i::BITS_PER_BYTE, |at| { - let bytes = _mm_loadu_si128(at.cast()); - let buckets = _mm_and_si128( - _mm_shuffle_epi8(low, _mm_and_si128(bytes, nibble)), - _mm_shuffle_epi8(high, _mm_and_si128(_mm_srli_epi16::<4>(bytes), nibble)), - ); - let bits = |mask| { - let hits = _mm_and_si128(buckets, mask); - u64::from(!(_mm_movemask_epi8(_mm_cmpeq_epi8(hits, zero)) as u32) & 0xffff) - }; - (bits(stops), bits(marks)) + let low = __m128i::table(&self.low); + let high = __m128i::table(&self.high); + let stops = __m128i::splat(self.stops); + let marks = __m128i::splat(self.marks); + self.simd_stop_in::<__m128i>(hay, from, end, |at| { + let buckets = simd::buckets::<__m128i>(at, low, high); + (buckets.test_mask(stops), buckets.test_mask(marks)) }) } } #[inline] pub(super) fn avx2_stop_in(&self, hay: &[u8], from: usize, end: usize) -> Stop { - // SAFETY: the CPU supports AVX2. This method is reached only from the - // `Kernel` dispatch in `scan/mod.rs` on `Backend::Avx2`: it is + // SAFETY: the CPU supports AVX2. This method is reached only from + // the `Kernel` dispatch in `scan/mod.rs` on `Backend::Avx2`: it is // `pub(super)` in `x86`, a private module of `scan`, `Backend` and the // field of `Kernel` are private to `scan`, and `Kernel::best` and - // `Kernel::available` build `Backend::Avx2` only after + // `Kernel::available` build that back end only after // `is_x86_feature_detected!("avx2")` returned true. unsafe { self.avx2_stop_in_impl(hay, from, end) } }