lance-core 14.0.1

Lance Columnar Format -- Core Library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors

//! CPU feature detection and runtime kernel selection.
//!
//! [`CpuFeatures`] is the set of features the host supports, detected once.
//! Kernels declare the features they need with [`target_kernel!`](crate::target_kernel),
//! and a [`Dispatch`] picks the first candidate the host supports.

use std::fmt;
use std::sync::LazyLock;

mod dispatch;

pub use dispatch::{Candidate, Dispatch, Kernel, Selection};

/// A set of CPU features, named after rustc `target_feature`s.
///
/// Unlike [`SimdSupport`], this is not a ladder: a kernel can require any
/// combination, such as AVX-512 without FMA or F16C on an AVX host.
///
/// ```
/// use lance_core::utils::cpu::CpuFeatures;
///
/// // Implied features are included: AVX2 brings AVX along with it.
/// let needed = CpuFeatures::from_target_features(&["avx2", "fma"]);
/// assert!(needed.contains(CpuFeatures::AVX));
///
/// // A kernel can run here if the host has every feature it needs, and can
/// // be called directly, without dispatch, if the build baseline does.
/// let runnable = CpuFeatures::host().contains(needed);
/// let inlinable = CpuFeatures::baseline().contains(needed);
/// assert!(runnable || !inlinable);
/// ```
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct CpuFeatures(u32);

impl CpuFeatures {
    pub const SSE2: Self = Self(1 << 0);
    pub const SSE3: Self = Self(1 << 1);
    pub const SSSE3: Self = Self(1 << 2);
    pub const SSE4_1: Self = Self(1 << 3);
    pub const SSE4_2: Self = Self(1 << 4);
    pub const POPCNT: Self = Self(1 << 5);
    pub const AVX: Self = Self(1 << 6);
    pub const AVX2: Self = Self(1 << 7);
    pub const FMA: Self = Self(1 << 8);
    pub const F16C: Self = Self(1 << 9);
    pub const BMI1: Self = Self(1 << 10);
    pub const BMI2: Self = Self(1 << 11);
    pub const AVX512F: Self = Self(1 << 12);
    pub const AVX512BW: Self = Self(1 << 13);
    pub const AVX512CD: Self = Self(1 << 14);
    pub const AVX512DQ: Self = Self(1 << 15);
    pub const AVX512VL: Self = Self(1 << 16);
    pub const AVX512FP16: Self = Self(1 << 17);
    pub const NEON: Self = Self(1 << 18);
    pub const FP16: Self = Self(1 << 19);
    pub const LSX: Self = Self(1 << 20);
    pub const LASX: Self = Self(1 << 21);

    /// The set with no features, which every host supports.
    pub const fn empty() -> Self {
        Self(0)
    }

    /// Whether the set has no features.
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// The features in either set.
    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// Whether every feature in `other` is also in `self`.
    pub const fn contains(self, other: Self) -> bool {
        self.0 & other.0 == other.0
    }

    /// Features supported by the host, detected once per process.
    pub fn host() -> Self {
        *HOST_FEATURES
    }

    /// Features the build enables for all code, e.g. via `-C target-cpu`.
    ///
    /// A kernel whose features are all in the baseline can be called directly
    /// and inlined; see [`Dispatch`].
    pub const fn baseline() -> Self {
        BASELINE
    }

    /// The feature set for one rustc `target_feature` name, including the
    /// features rustc enables along with it. `None` if the name is unknown.
    ///
    /// Implied features matter for soundness: `#[target_feature(enable =
    /// "avx512f")]` also lets codegen use AVX2, FMA and F16C, so a kernel
    /// declaring it must not run on a host that lacks any of them.
    pub const fn from_target_feature(name: &str) -> Option<Self> {
        let mut i = 0;
        while i < FEATURE_TABLE.len() {
            if str_eq(FEATURE_TABLE[i].name, name) {
                return Some(FEATURE_TABLE[i].feature.with_implied());
            }
            i += 1;
        }
        None
    }

    /// Union of [`Self::from_target_feature`] over `names`.
    ///
    /// # Panics
    ///
    /// Panics if a name is unknown. [`target_kernel!`](crate::target_kernel)
    /// evaluates this in a `const`, so a typo is a compile error there.
    pub const fn from_target_features(names: &[&str]) -> Self {
        let mut features = Self::empty();
        let mut i = 0;
        while i < names.len() {
            match Self::from_target_feature(names[i]) {
                Some(feature) => features = features.union(feature),
                None => panic!("unknown target feature; add it to CpuFeatures"),
            }
            i += 1;
        }
        features
    }

    /// Every known feature, one per set.
    #[cfg(test)]
    pub fn all() -> impl Iterator<Item = Self> {
        FEATURE_TABLE.iter().map(|info| info.feature)
    }

    /// The `target_feature` names of the features in this set.
    pub fn names(self) -> impl Iterator<Item = &'static str> {
        FEATURE_TABLE
            .iter()
            .filter(move |info| self.contains(info.feature))
            .map(|info| info.name)
    }

    fn x86_names(self) -> impl Iterator<Item = &'static str> {
        FEATURE_TABLE
            .iter()
            .filter(move |info| info.is_x86 && self.contains(info.feature))
            .map(|info| info.name)
    }

    const fn with_implied(self) -> Self {
        let mut features = self;
        loop {
            let mut expanded = features;
            let mut i = 0;
            while i < FEATURE_TABLE.len() {
                if features.contains(FEATURE_TABLE[i].feature) {
                    expanded = expanded.union(FEATURE_TABLE[i].implies);
                }
                i += 1;
            }
            if expanded.0 == features.0 {
                return features;
            }
            features = expanded;
        }
    }
}

impl fmt::Debug for CpuFeatures {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_set().entries(self.names()).finish()
    }
}

struct FeatureInfo {
    feature: CpuFeatures,
    name: &'static str,
    is_x86: bool,
    /// Features rustc enables along with this one. Transitive implications
    /// are resolved by [`CpuFeatures::with_implied`].
    implies: CpuFeatures,
}

const fn x86(feature: CpuFeatures, name: &'static str, implies: CpuFeatures) -> FeatureInfo {
    FeatureInfo {
        feature,
        name,
        is_x86: true,
        implies,
    }
}

const fn other(feature: CpuFeatures, name: &'static str, implies: CpuFeatures) -> FeatureInfo {
    FeatureInfo {
        feature,
        name,
        is_x86: false,
        implies,
    }
}

/// Ordered as [`SimdInfo::host_features`] reports them.
const FEATURE_TABLE: &[FeatureInfo] = {
    use CpuFeatures as F;
    &[
        x86(F::SSE2, "sse2", F::empty()),
        x86(F::SSE3, "sse3", F::SSE2),
        x86(F::SSSE3, "ssse3", F::SSE3),
        x86(F::SSE4_1, "sse4.1", F::SSSE3),
        x86(F::SSE4_2, "sse4.2", F::SSE4_1),
        x86(F::POPCNT, "popcnt", F::empty()),
        x86(F::AVX, "avx", F::SSE4_2),
        x86(F::AVX2, "avx2", F::AVX),
        x86(F::FMA, "fma", F::AVX),
        x86(F::F16C, "f16c", F::AVX),
        x86(F::BMI1, "bmi1", F::empty()),
        x86(F::BMI2, "bmi2", F::empty()),
        x86(F::AVX512F, "avx512f", F::AVX2.union(F::FMA).union(F::F16C)),
        x86(F::AVX512BW, "avx512bw", F::AVX512F),
        x86(F::AVX512CD, "avx512cd", F::AVX512F),
        x86(F::AVX512DQ, "avx512dq", F::AVX512F),
        x86(F::AVX512VL, "avx512vl", F::AVX512F),
        x86(
            F::AVX512FP16,
            "avx512fp16",
            F::AVX512BW.union(F::AVX512DQ).union(F::AVX512VL),
        ),
        other(F::NEON, "neon", F::empty()),
        other(F::FP16, "fp16", F::NEON),
        other(F::LSX, "lsx", F::empty()),
        other(F::LASX, "lasx", F::LSX),
    ]
};

const fn str_eq(a: &str, b: &str) -> bool {
    let (a, b) = (a.as_bytes(), b.as_bytes());
    if a.len() != b.len() {
        return false;
    }
    let mut i = 0;
    while i < a.len() {
        if a[i] != b[i] {
            return false;
        }
        i += 1;
    }
    true
}

const BASELINE: CpuFeatures = {
    // `cfg!` needs a literal feature name, so this cannot loop over the table.
    let enabled = [
        (cfg!(target_feature = "sse2"), CpuFeatures::SSE2),
        (cfg!(target_feature = "sse3"), CpuFeatures::SSE3),
        (cfg!(target_feature = "ssse3"), CpuFeatures::SSSE3),
        (cfg!(target_feature = "sse4.1"), CpuFeatures::SSE4_1),
        (cfg!(target_feature = "sse4.2"), CpuFeatures::SSE4_2),
        (cfg!(target_feature = "popcnt"), CpuFeatures::POPCNT),
        (cfg!(target_feature = "avx"), CpuFeatures::AVX),
        (cfg!(target_feature = "avx2"), CpuFeatures::AVX2),
        (cfg!(target_feature = "fma"), CpuFeatures::FMA),
        (cfg!(target_feature = "f16c"), CpuFeatures::F16C),
        (cfg!(target_feature = "bmi1"), CpuFeatures::BMI1),
        (cfg!(target_feature = "bmi2"), CpuFeatures::BMI2),
        (cfg!(target_feature = "avx512f"), CpuFeatures::AVX512F),
        (cfg!(target_feature = "avx512bw"), CpuFeatures::AVX512BW),
        (cfg!(target_feature = "avx512cd"), CpuFeatures::AVX512CD),
        (cfg!(target_feature = "avx512dq"), CpuFeatures::AVX512DQ),
        (cfg!(target_feature = "avx512vl"), CpuFeatures::AVX512VL),
        (cfg!(target_feature = "avx512fp16"), CpuFeatures::AVX512FP16),
        (cfg!(target_feature = "neon"), CpuFeatures::NEON),
        (cfg!(target_feature = "fp16"), CpuFeatures::FP16),
        (cfg!(target_feature = "lsx"), CpuFeatures::LSX),
        (cfg!(target_feature = "lasx"), CpuFeatures::LASX),
    ];
    let mut features = CpuFeatures::empty();
    let mut i = 0;
    while i < enabled.len() {
        if enabled[i].0 {
            features = features.union(enabled[i].1);
        }
        i += 1;
    }
    features
};

// Runtime detection checks only some features per target, and none on
// targets without a detector, so it can miss features the build already
// assumes. `Dispatch` relies on the host set containing the baseline, so add
// it explicitly.
static HOST_FEATURES: LazyLock<CpuFeatures> =
    LazyLock::new(|| detect_host_features().union(BASELINE));

#[cfg(target_arch = "x86_64")]
fn detect_host_features() -> CpuFeatures {
    let mut features = CpuFeatures::empty();
    let mut add = |is_detected: bool, feature: CpuFeatures| {
        if is_detected {
            features = features.union(feature);
        }
    };
    // Each call must be inline: `is_x86_feature_detected!` does its own custom
    // input parsing and rejects feature names received via a `macro_rules!`
    // `:literal` metavariable on some toolchains.
    add(is_x86_feature_detected!("sse2"), CpuFeatures::SSE2);
    add(is_x86_feature_detected!("sse3"), CpuFeatures::SSE3);
    add(is_x86_feature_detected!("ssse3"), CpuFeatures::SSSE3);
    add(is_x86_feature_detected!("sse4.1"), CpuFeatures::SSE4_1);
    add(is_x86_feature_detected!("sse4.2"), CpuFeatures::SSE4_2);
    add(is_x86_feature_detected!("popcnt"), CpuFeatures::POPCNT);
    add(is_x86_feature_detected!("avx"), CpuFeatures::AVX);
    add(is_x86_feature_detected!("avx2"), CpuFeatures::AVX2);
    add(is_x86_feature_detected!("fma"), CpuFeatures::FMA);
    add(is_x86_feature_detected!("f16c"), CpuFeatures::F16C);
    add(is_x86_feature_detected!("bmi1"), CpuFeatures::BMI1);
    add(is_x86_feature_detected!("bmi2"), CpuFeatures::BMI2);
    add(is_x86_feature_detected!("avx512f"), CpuFeatures::AVX512F);
    add(is_x86_feature_detected!("avx512bw"), CpuFeatures::AVX512BW);
    add(is_x86_feature_detected!("avx512cd"), CpuFeatures::AVX512CD);
    add(is_x86_feature_detected!("avx512dq"), CpuFeatures::AVX512DQ);
    add(is_x86_feature_detected!("avx512vl"), CpuFeatures::AVX512VL);
    add(
        is_x86_feature_detected!("avx512fp16"),
        CpuFeatures::AVX512FP16,
    );
    features
}

#[cfg(target_arch = "aarch64")]
fn detect_host_features() -> CpuFeatures {
    #[cfg(any(target_os = "ios", target_os = "tvos"))]
    let has_fp16 = true;
    #[cfg(not(any(target_os = "ios", target_os = "tvos")))]
    let has_fp16 = aarch64::has_neon_f16_support();

    if has_fp16 {
        CpuFeatures::NEON.union(CpuFeatures::FP16)
    } else {
        CpuFeatures::NEON
    }
}

#[cfg(target_arch = "loongarch64")]
fn detect_host_features() -> CpuFeatures {
    let mut features = CpuFeatures::empty();
    if loongarch64::has_lsx_support() {
        features = features.union(CpuFeatures::LSX);
    }
    if loongarch64::has_lasx_support() {
        features = features.union(CpuFeatures::LASX);
    }
    features
}

#[cfg(not(any(
    target_arch = "aarch64",
    target_arch = "x86_64",
    target_arch = "loongarch64"
)))]
fn detect_host_features() -> CpuFeatures {
    CpuFeatures::empty()
}

/// A level of SIMD support for some feature.
///
/// `#[non_exhaustive]` so future tiers (e.g. AVX-512 BF16, AMX) can be added
/// without breaking external `match` consumers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SimdSupport {
    None,
    Neon,
    Sse,
    /// AVX (256-bit float ops) without FMA.
    ///
    /// This tier does not imply that AVX2 is absent: selecting [`Self::Avx2`]
    /// requires both AVX2 and FMA, so a host with AVX2 but no FMA selects this
    /// tier. Intel Sandy Bridge / Ivy Bridge are the typical hosts.
    Avx,
    /// AVX + FMA but no AVX2.
    /// AMD Piledriver / Steamroller / FX-7500.
    AvxFma,
    /// AVX2 + FMA. Intel Haswell / AMD Excavator and later.
    ///
    /// Selecting this tier asserts FMA is present: the kernels it dispatches to
    /// are `#[target_feature(enable = "avx,fma")]`.
    Avx2,
    Avx512,
    Avx512FP16,
    Lsx,
    Lasx,
}

impl fmt::Display for SimdSupport {
    /// Formats the tier name in lowercase, matching pyarrow's
    /// `runtime_info().simd_level` convention.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            Self::None => "none",
            Self::Neon => "neon",
            Self::Sse => "sse",
            Self::Avx => "avx",
            Self::AvxFma => "avx_fma",
            Self::Avx2 => "avx2",
            Self::Avx512 => "avx512",
            Self::Avx512FP16 => "avx512_fp16",
            Self::Lsx => "lsx",
            Self::Lasx => "lasx",
        };
        f.write_str(name)
    }
}

/// Snapshot of the SIMD tier lance dispatches to on the current host, plus the
/// raw CPU features detected for diagnostic purposes.
///
/// Mirrors the role of `pyarrow.runtime_info()`: a single, cheap call users can
/// make to verify which SIMD tier the runtime selected and what underlying
/// features the host advertises. Obtain one with [`simd_info()`].
#[derive(Debug, Clone)]
pub struct SimdInfo {
    /// The SIMD tier lance dispatches to at runtime on this host.
    pub tier: SimdSupport,
    /// The architecture name (e.g. "x86_64", "aarch64", "loongarch64").
    pub target_arch: &'static str,
    /// Raw CPU feature flags detected on this host (x86_64 only; empty on
    /// other architectures). Each entry is a feature name like "avx2",
    /// "fma", "avx512f", "popcnt", etc.
    pub host_features: Vec<&'static str>,
}

/// Returns a snapshot of the SIMD tier lance is using on this host along with
/// the raw CPU feature flags that drove the decision.
///
/// Useful for performance debugging and giving users a way to verify which
/// dispatch tier they are hitting without rebuilding lance. See [`SimdInfo`]
/// for the meaning of each field and [`SimdSupport`] for the tier values.
///
/// # Examples
///
/// ```
/// use lance_core::utils::cpu::simd_info;
///
/// let info = simd_info();
/// println!("dispatching to {} on {}", info.tier, info.target_arch);
/// ```
pub fn simd_info() -> SimdInfo {
    SimdInfo {
        tier: *SIMD_SUPPORT,
        target_arch: std::env::consts::ARCH,
        host_features: CpuFeatures::host().x86_names().collect(),
    }
}

impl SimdSupport {
    /// The tier lance reports for a feature set. Each architecture only sets
    /// its own feature bits, so checking every architecture in turn is safe.
    fn from_features(features: CpuFeatures) -> Self {
        use CpuFeatures as F;
        if features.contains(F::AVX512F) {
            if features.contains(F::AVX512FP16) {
                Self::Avx512FP16
            } else {
                Self::Avx512
            }
        } else if features.contains(F::AVX2.union(F::FMA)) {
            Self::Avx2
        } else if features.contains(F::AVX.union(F::FMA)) {
            // AMD Piledriver / Steamroller / FX-7500: 256-bit float ops + FMA but no AVX2.
            Self::AvxFma
        } else if features.contains(F::AVX) {
            // This includes a possible AVX2 host without FMA because the Avx2
            // tier above requires both features.
            Self::Avx
        } else if features.contains(F::FP16) {
            Self::Neon
        } else if features.contains(F::LASX) {
            Self::Lasx
        } else if features.contains(F::LSX) {
            Self::Lsx
        } else {
            Self::None
        }
    }
}

/// Support for SIMD operations, derived from [`CpuFeatures::host`].
pub static SIMD_SUPPORT: LazyLock<SimdSupport> =
    LazyLock::new(|| SimdSupport::from_features(CpuFeatures::host()));

// Inspired by https://github.com/RustCrypto/utils/blob/master/cpufeatures/src/aarch64.rs
// aarch64 doesn't have userspace feature detection built in, so we have to call
// into OS-specific functions to check for features.

#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
mod aarch64 {
    pub fn has_neon_f16_support() -> bool {
        // Maybe we can assume it's there?
        true
    }
}

#[cfg(all(target_arch = "aarch64", target_os = "linux"))]
mod aarch64 {
    pub fn has_neon_f16_support() -> bool {
        // See: https://github.com/rust-lang/libc/blob/7ce81ca7aeb56aae7ca0237ef9353d58f3d7d2f1/src/unix/linux_like/linux/gnu/b64/aarch64/mod.rs#L533
        let flags = unsafe { libc::getauxval(libc::AT_HWCAP) };
        flags & libc::HWCAP_FPHP != 0
    }
}

#[cfg(all(target_arch = "aarch64", target_os = "windows"))]
mod aarch64 {
    pub fn has_neon_f16_support() -> bool {
        // https://github.com/lance-format/lance/issues/2411
        false
    }
}

#[cfg(target_arch = "loongarch64")]
mod loongarch64 {
    pub fn has_lsx_support() -> bool {
        // See: https://github.com/rust-lang/libc/blob/7ce81ca7aeb56aae7ca0237ef9353d58f3d7d2f1/src/unix/linux_like/linux/gnu/b64/loongarch64/mod.rs#L263
        let flags = unsafe { libc::getauxval(libc::AT_HWCAP) };
        flags & libc::HWCAP_LOONGARCH_LSX != 0
    }
    pub fn has_lasx_support() -> bool {
        // See: https://github.com/rust-lang/libc/blob/7ce81ca7aeb56aae7ca0237ef9353d58f3d7d2f1/src/unix/linux_like/linux/gnu/b64/loongarch64/mod.rs#L264
        let flags = unsafe { libc::getauxval(libc::AT_HWCAP) };
        flags & libc::HWCAP_LOONGARCH_LASX != 0
    }
}

#[cfg(all(target_arch = "aarch64", target_os = "android"))]
mod aarch64 {
    pub fn has_neon_f16_support() -> bool {
        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rstest::rstest;

    #[test]
    fn simd_info_exposes_tier() {
        let info = simd_info();
        assert_eq!(info.target_arch, std::env::consts::ARCH);
        // Tier should match the detected SIMD support.
        assert_eq!(info.tier, *SIMD_SUPPORT);
    }

    #[cfg(target_arch = "x86_64")]
    #[test]
    fn simd_info_features_include_baseline() {
        let info = simd_info();
        // The x86_64 ABI mandates SSE2, so it must always be present on this
        // architecture.
        assert!(info.host_features.contains(&"sse2"));
    }

    #[cfg(not(target_arch = "x86_64"))]
    #[test]
    fn simd_info_features_empty_off_x86_64() {
        let info = simd_info();
        assert!(info.host_features.is_empty());
    }

    /// The `Avx2` and `AvxFma` tiers both dispatch to kernels declared
    /// `#[target_feature(enable = "avx,fma")]`, so neither may be selected on a
    /// host without FMA. AVX2 does not imply FMA in the ISA, so the detection
    /// checks it explicitly.
    #[cfg(target_arch = "x86_64")]
    #[test]
    fn avx_fma_tiers_are_only_selected_when_fma_is_detected() {
        if matches!(*SIMD_SUPPORT, SimdSupport::Avx2 | SimdSupport::AvxFma) {
            assert!(
                is_x86_feature_detected!("fma"),
                "tier {} dispatches to avx,fma kernels but the host has no FMA",
                *SIMD_SUPPORT
            );
        }
    }

    #[test]
    fn host_features_include_build_baseline() {
        assert!(CpuFeatures::host().contains(CpuFeatures::baseline()));
    }

    /// The mask a kernel declares must cover every feature rustc enables for
    /// it, including implied ones, or a host lacking an implied feature could
    /// select a kernel that uses it.
    #[rstest]
    #[case::sse_chain("avx", CpuFeatures::SSE2.union(CpuFeatures::SSE4_2))]
    #[case::fma_implies_avx("fma", CpuFeatures::AVX)]
    #[case::avx512f(
        "avx512f",
        CpuFeatures::AVX2.union(CpuFeatures::FMA).union(CpuFeatures::F16C)
    )]
    #[case::avx512fp16("avx512fp16", CpuFeatures::AVX512BW.union(CpuFeatures::AVX512F))]
    #[case::fp16("fp16", CpuFeatures::NEON)]
    #[case::lasx("lasx", CpuFeatures::LSX)]
    fn target_feature_mask_includes_implied_features(
        #[case] name: &str,
        #[case] implied: CpuFeatures,
    ) {
        let features = CpuFeatures::from_target_feature(name).unwrap();
        assert!(
            features.contains(implied),
            "{name} -> {features:?} is missing {implied:?}"
        );
    }

    #[test]
    fn unknown_target_feature_is_rejected() {
        assert_eq!(CpuFeatures::from_target_feature("avx9000"), None);
    }

    #[rstest]
    #[case::none(&[], SimdSupport::None)]
    #[case::avx(&["avx"], SimdSupport::Avx)]
    #[case::avx2_without_fma(&["avx2"], SimdSupport::Avx)]
    #[case::avx_fma(&["fma"], SimdSupport::AvxFma)]
    #[case::avx2(&["avx2", "fma"], SimdSupport::Avx2)]
    #[case::avx512(&["avx512f"], SimdSupport::Avx512)]
    #[case::avx512_fp16(&["avx512fp16"], SimdSupport::Avx512FP16)]
    #[case::neon_without_fp16(&["neon"], SimdSupport::None)]
    #[case::neon(&["fp16"], SimdSupport::Neon)]
    #[case::lsx(&["lsx"], SimdSupport::Lsx)]
    #[case::lasx(&["lasx"], SimdSupport::Lasx)]
    fn simd_support_is_derived_from_features(
        #[case] names: &[&str],
        #[case] expected: SimdSupport,
    ) {
        let features = CpuFeatures::from_target_features(names);
        assert_eq!(SimdSupport::from_features(features), expected);
    }

    #[rstest]
    #[case::none(SimdSupport::None, "none")]
    #[case::neon(SimdSupport::Neon, "neon")]
    #[case::sse(SimdSupport::Sse, "sse")]
    #[case::avx(SimdSupport::Avx, "avx")]
    #[case::avx_fma(SimdSupport::AvxFma, "avx_fma")]
    #[case::avx2(SimdSupport::Avx2, "avx2")]
    #[case::avx512(SimdSupport::Avx512, "avx512")]
    #[case::avx512_fp16(SimdSupport::Avx512FP16, "avx512_fp16")]
    #[case::lsx(SimdSupport::Lsx, "lsx")]
    #[case::lasx(SimdSupport::Lasx, "lasx")]
    fn simd_support_display_matches_lowercase_convention(
        #[case] tier: SimdSupport,
        #[case] expected: &str,
    ) {
        assert_eq!(tier.to_string(), expected);
    }
}