//- simd / bit helpers, one api on both architectures // NOTE: x86-64: sse2 (baseline on every x86-64 cpu), arm64: neon (baseline on every aarch64 cpu). // nothing here needs avx or sve, so release builds stay portable without -march flags. #if ARCH_ARM #include #elif ARCH_X86 || ARCH_x86_64 #include #endif #if COMPILER_MSVC #include #endif internal u32 simd_ctz32(u32 x) { #if COMPILER_MSVC unsigned long index; _BitScanForward(&index, x); return (u32)index; #else return (u32)__builtin_ctz(x); #endif } internal u32 simd_ctz64(u64 x) { #if COMPILER_MSVC unsigned long index; _BitScanForward64(&index, x); return (u32)index; #else return (u32)__builtin_ctzll(x); #endif } // NOTE: index of the first `byte` in data, or size when there is none internal u64 simd_find_byte(u8 *data, u64 size, u8 byte) { u64 index = 0; #if ARCH_ARM uint8x16_t needle = vdupq_n_u8(byte); for(; index + 16 <= size; index += 16) { uint8x16_t eq = vceqq_u8(vld1q_u8(data + index), needle); // NOTE: neon has no movemask. shift-narrow each 16 bit lane by 4 -> one nibble per byte uint8x8_t narrowed = vshrn_n_u16(vreinterpretq_u16_u8(eq), 4); u64 mask = vget_lane_u64(vreinterpret_u64_u8(narrowed), 0); if(mask) return index + (simd_ctz64(mask) >> 2); } #elif ARCH_X86 || ARCH_x86_64 __m128i needle = _mm_set1_epi8((char)byte); for(; index + 16 <= size; index += 16) { __m128i chunk = _mm_loadu_si128((const __m128i *)(data + index)); u32 mask = (u32)_mm_movemask_epi8(_mm_cmpeq_epi8(chunk, needle)); if(mask) return index + simd_ctz32(mask); } #endif for(; index < size; ++index) { if(data[index] == byte) return index; } return size; } // NOTE: count of `byte` in data (newlines in a buffer, say) internal u64 simd_count_byte(u8 *data, u64 size, u8 byte) { u64 count = 0, index = 0; #if ARCH_ARM uint8x16_t needle = vdupq_n_u8(byte); for(; index + 16 <= size; index += 16) { uint8x16_t eq = vceqq_u8(vld1q_u8(data + index), needle); count += vaddvq_u8(vshrq_n_u8(eq, 7)); } #elif ARCH_X86 || ARCH_x86_64 __m128i needle = _mm_set1_epi8((char)byte); for(; index + 16 <= size; index += 16) { __m128i chunk = _mm_loadu_si128((const __m128i *)(data + index)); u32 mask = (u32)_mm_movemask_epi8(_mm_cmpeq_epi8(chunk, needle)); #if COMPILER_MSVC count += __popcnt(mask); #else count += (u64)__builtin_popcount(mask); #endif } #endif for(; index < size; ++index) count += (data[index] == byte); return count; }