elem-simd-math 0.1.3

Vectorized elementwise math kernels for f32/f64 over stable-Rust SIMD (port of SLEEF via sleef-rs, on fearless_simd).
Documentation
//! Disassembly check: the kernels compile to the register width of the level they are selected
//! at, and an AVX2 kernel contains no `zmm`.
//!
//! The crate dispatches at run time (`fearless_simd`), never with `-C target-cpu`; this test
//! guards the other half of that contract: that code reached from the AVX2 token is not
//! AVX-512 code (which would fault on a CPU without it), and that the SSE tokens stay 128-bit.
//!
//! Method: the test binary contains one `#[inline(never)]` probe per `(level, kernel)`, built
//! with `Simd::vectorize` so the kernel body is compiled under that level's target features. The
//! test runs `objdump -d` on its own executable, walks the call graph from each probe, and
//! scans every reachable instruction for register classes:
//!
//! | level | `xmm` | `ymm` | `zmm` |
//! |---|---|---|---|
//! | `sse2`, `sse4.2` | yes | **no** | **no** |
//! | `avx2` | yes | yes | **no** |
//! | `avx512` | any | any | yes |
//!
//! The `avx512` probes are never executed (this host may not have AVX-512); they are only
//! disassembled, as the positive control that proves the scanner can see `zmm`. Likewise the
//! `ymm` requirement for `avx2` proves the scan reached real vector code and not a stub.
//!
//! Needs `objdump` (binutils). Without it the test is skipped locally and fails when the `CI`
//! environment variable is set, so the check cannot silently disappear from the gate.

#![cfg(all(target_arch = "x86_64", target_os = "linux", feature = "simd"))]

use std::collections::{HashMap, HashSet};
use std::process::Command;

use elem_simd_math::common::{F32s, F64s};
use elem_simd_math::{f32x, f64x};
use fearless_simd::prelude::*;
use fearless_simd::x86::{Avx2, Avx512, Sse2, Sse4_2};
use fearless_simd::Simd;

macro_rules! probe {
    ($name:ident, $tok:ty, f64, $kernel:expr) => {
        #[inline(never)]
        fn $name(tok: $tok, x: &[f64; 16], y: &[f64; 16], out: &mut [f64; 16]) {
            tok.vectorize(|| {
                let n = F64s::<$tok>::LEN;
                let a = F64s::<$tok>::from_slice(tok, &x[..n]);
                let b = F64s::<$tok>::from_slice(tok, &y[..n]);
                let _ = &b;
                out[..n].copy_from_slice($kernel(tok, a, b).to_array().as_ref());
            })
        }
    };
    ($name:ident, $tok:ty, f32, $kernel:expr) => {
        #[inline(never)]
        fn $name(tok: $tok, x: &[f32; 16], y: &[f32; 16], out: &mut [f32; 16]) {
            tok.vectorize(|| {
                let n = F32s::<$tok>::LEN;
                let a = F32s::<$tok>::from_slice(tok, &x[..n]);
                let b = F32s::<$tok>::from_slice(tok, &y[..n]);
                let _ = &b;
                out[..n].copy_from_slice($kernel(tok, a, b).to_array().as_ref());
            })
        }
    };
}

// Unary kernels are adapted to the binary probe shape; the second operand is ignored.
macro_rules! unary64 {
    ($f:path) => {{
        #[inline(always)]
        fn k<S: Simd>(s: S, a: F64s<S>, _b: F64s<S>) -> F64s<S> {
            $f(s, a)
        }
        k
    }};
}
macro_rules! unary32 {
    ($f:path) => {{
        #[inline(always)]
        fn k<S: Simd>(s: S, a: F32s<S>, _b: F32s<S>) -> F32s<S> {
            $f(s, a)
        }
        k
    }};
}

macro_rules! probes_for_level {
    ($tok:ty, $lvl:ident) => {
        paste_probes!($tok, $lvl);
    };
}

// One probe per (level, kernel). Names are searched for in the symbol table, so they carry the
// level and kernel and are unique.
macro_rules! paste_probes {
    ($tok:ty, sse2) => {
        probe!(probe_sse2_f64_i0e, $tok, f64, unary64!(f64x::special::i0e));
        probe!(probe_sse2_f64_i1e, $tok, f64, unary64!(f64x::special::i1e));
        probe!(probe_sse2_f64_xlogy, $tok, f64, f64x::special::xlogy);
        probe!(probe_sse2_f32_i0e, $tok, f32, unary32!(f32x::special::i0e));
        probe!(probe_sse2_f32_i1e, $tok, f32, unary32!(f32x::special::i1e));
        probe!(probe_sse2_f32_xlogy, $tok, f32, f32x::special::xlogy);
        probe!(probe_sse2_f64_exp, $tok, f64, unary64!(f64x::u10::exp));
    };
    ($tok:ty, sse4_2) => {
        probe!(
            probe_sse4_2_f64_i0e,
            $tok,
            f64,
            unary64!(f64x::special::i0e)
        );
        probe!(
            probe_sse4_2_f64_i1e,
            $tok,
            f64,
            unary64!(f64x::special::i1e)
        );
        probe!(probe_sse4_2_f64_xlogy, $tok, f64, f64x::special::xlogy);
        probe!(
            probe_sse4_2_f32_i0e,
            $tok,
            f32,
            unary32!(f32x::special::i0e)
        );
        probe!(
            probe_sse4_2_f32_i1e,
            $tok,
            f32,
            unary32!(f32x::special::i1e)
        );
        probe!(probe_sse4_2_f32_xlogy, $tok, f32, f32x::special::xlogy);
        probe!(probe_sse4_2_f64_exp, $tok, f64, unary64!(f64x::u10::exp));
    };
    ($tok:ty, avx2) => {
        probe!(probe_avx2_f64_i0e, $tok, f64, unary64!(f64x::special::i0e));
        probe!(probe_avx2_f64_i1e, $tok, f64, unary64!(f64x::special::i1e));
        probe!(probe_avx2_f64_xlogy, $tok, f64, f64x::special::xlogy);
        probe!(probe_avx2_f32_i0e, $tok, f32, unary32!(f32x::special::i0e));
        probe!(probe_avx2_f32_i1e, $tok, f32, unary32!(f32x::special::i1e));
        probe!(probe_avx2_f32_xlogy, $tok, f32, f32x::special::xlogy);
        probe!(probe_avx2_f64_exp, $tok, f64, unary64!(f64x::u10::exp));
    };
    ($tok:ty, avx512) => {
        probe!(
            probe_avx512_f64_i0e,
            $tok,
            f64,
            unary64!(f64x::special::i0e)
        );
        probe!(
            probe_avx512_f64_i1e,
            $tok,
            f64,
            unary64!(f64x::special::i1e)
        );
        probe!(probe_avx512_f64_xlogy, $tok, f64, f64x::special::xlogy);
        probe!(
            probe_avx512_f32_i0e,
            $tok,
            f32,
            unary32!(f32x::special::i0e)
        );
        probe!(
            probe_avx512_f32_i1e,
            $tok,
            f32,
            unary32!(f32x::special::i1e)
        );
        probe!(probe_avx512_f32_xlogy, $tok, f32, f32x::special::xlogy);
        probe!(probe_avx512_f64_exp, $tok, f64, unary64!(f64x::u10::exp));
    };
}

probes_for_level!(Sse2, sse2);
probes_for_level!(Sse4_2, sse4_2);
probes_for_level!(Avx2, avx2);
probes_for_level!(Avx512, avx512);

/// Keeps every probe in the binary without running it.
fn keep_probes_alive() {
    use std::hint::black_box;
    macro_rules! keep {
        ($($p:ident),*) => { $( black_box($p as *const ()); )* };
    }
    keep!(
        probe_sse2_f64_i0e,
        probe_sse2_f64_i1e,
        probe_sse2_f64_xlogy,
        probe_sse2_f32_i0e,
        probe_sse2_f32_i1e,
        probe_sse2_f32_xlogy,
        probe_sse2_f64_exp,
        probe_sse4_2_f64_i0e,
        probe_sse4_2_f64_i1e,
        probe_sse4_2_f64_xlogy,
        probe_sse4_2_f32_i0e,
        probe_sse4_2_f32_i1e,
        probe_sse4_2_f32_xlogy,
        probe_sse4_2_f64_exp,
        probe_avx2_f64_i0e,
        probe_avx2_f64_i1e,
        probe_avx2_f64_xlogy,
        probe_avx2_f32_i0e,
        probe_avx2_f32_i1e,
        probe_avx2_f32_xlogy,
        probe_avx2_f64_exp,
        probe_avx512_f64_i0e,
        probe_avx512_f64_i1e,
        probe_avx512_f64_xlogy,
        probe_avx512_f32_i0e,
        probe_avx512_f32_i1e,
        probe_avx512_f32_xlogy,
        probe_avx512_f64_exp
    );
}

#[derive(Default)]
struct Func {
    text: String,
    callees: HashSet<String>,
}

fn parse(listing: &str) -> HashMap<String, Func> {
    let mut funcs: HashMap<String, Func> = HashMap::new();
    let mut current: Option<String> = None;
    for line in listing.lines() {
        if let Some(rest) = line.strip_suffix(">:") {
            // "0000000000012340 <symbol>:"
            if let Some(idx) = rest.find(" <") {
                let name = rest[idx + 2..].to_string();
                funcs.entry(name.clone()).or_default();
                current = Some(name);
                continue;
            }
        }
        let Some(cur) = &current else { continue };
        let f = funcs.get_mut(cur).unwrap();
        // Instruction line: "  12345:\tmnemonic operands  # comment" (raw bytes suppressed).
        if let Some(colon) = line.find(":\t") {
            let insn = &line[colon + 2..];
            f.text.push_str(insn);
            f.text.push('\n');
            let is_branch = insn.starts_with("call") || insn.starts_with('j');
            if is_branch {
                // "call 12340 <symbol<T>+0x10>": the target starts at the first " <" and ends
                // at the last '>'; demangled generic names contain angle brackets of their own.
                if let (Some(a), Some(b)) = (insn.find(" <"), insn.rfind('>')) {
                    if a + 2 <= b {
                        let mut target = &insn[a + 2..b];
                        if let Some((head, off)) = target.rsplit_once('+') {
                            if off.starts_with("0x") {
                                target = head;
                            }
                        }
                        f.callees.insert(target.to_string());
                    }
                }
            }
        }
    }
    funcs
}

/// Concatenated text of everything reachable from `root` through direct calls and jumps.
fn reachable_text(funcs: &HashMap<String, Func>, root: &str) -> (String, usize) {
    let mut seen: HashSet<&str> = HashSet::new();
    let mut stack = vec![root];
    let mut text = String::new();
    while let Some(n) = stack.pop() {
        if !seen.insert(n) {
            continue;
        }
        if let Some(f) = funcs.get(n) {
            text.push_str(&f.text);
            for c in &f.callees {
                stack.push(c.as_str());
            }
        }
    }
    (text, seen.len())
}

fn has_reg(text: &str, class: &str) -> bool {
    text.contains(&format!("%{class}"))
}

#[test]
fn kernels_use_only_their_levels_register_width() {
    keep_probes_alive();
    let exe = std::env::current_exe().unwrap();
    let out = Command::new("objdump")
        .args(["-d", "--no-show-raw-insn", "-C", "-w"])
        .arg(&exe)
        .output();
    let out = match out {
        Ok(o) if o.status.success() => o,
        _ => {
            if std::env::var_os("CI").is_some() {
                panic!("objdump is required in CI for the disassembly check (install binutils)");
            }
            eprintln!("SKIP: objdump not available");
            return;
        }
    };
    let listing = String::from_utf8_lossy(&out.stdout);
    let funcs = parse(&listing);

    // (level, ymm required/forbidden or unconstrained, zmm expected)
    let levels = [
        ("sse2", Some(false), false),
        ("sse4_2", Some(false), false),
        ("avx2", Some(true), false),
        ("avx512", None, true),
    ];
    let kernels = [
        "f64_i0e",
        "f64_i1e",
        "f64_xlogy",
        "f32_i0e",
        "f32_i1e",
        "f32_xlogy",
        "f64_exp",
    ];
    let mut failures = Vec::new();
    for (level, want_ymm, want_zmm) in levels {
        for kernel in kernels {
            let probe = format!("probe_{level}_{kernel}");
            // Demangled symbol "disasm::probe_avx2_f64_i0e"; match the final path segment.
            let root = funcs
                .keys()
                .find(|k| k.ends_with(&format!("::{probe}")))
                .unwrap_or_else(|| panic!("probe {probe} is not in the binary"));
            let (text, n) = reachable_text(&funcs, root);
            let (ymm, zmm) = (has_reg(&text, "ymm"), has_reg(&text, "zmm"));
            let (xmm, insns) = (has_reg(&text, "xmm"), text.lines().count());
            println!(
                "{probe:28} reachable fns {n:3}, insns {insns:5}: xmm={xmm} ymm={ymm} zmm={zmm}"
            );
            assert!(
                insns > 20,
                "{probe}: scan reached only {insns} instructions"
            );
            if zmm && !want_zmm {
                failures.push(format!("{probe}: contains zmm but level {level} must not"));
            }
            if !zmm && want_zmm {
                failures.push(format!(
                    "{probe}: expected zmm (positive control), found none"
                ));
            }
            if want_ymm.is_some_and(|w| w != ymm) {
                failures.push(format!(
                    "{probe}: ymm={ymm}, expected {want_ymm:?} at {level}"
                ));
            }
        }
    }
    assert!(failures.is_empty(), "{}", failures.join("\n"));
}