//! Run-time feature detection for LoongArch on Linux.

use core::arch::asm;

use super::auxvec;
use crate::detect::{Feature, bit, cache};

/// Try to read the features from the auxiliary vector.
pub(crate) fn detect_features() -> cache::Initializer {
    let mut value = cache::Initializer::default();
    let enable_feature = |value: &mut cache::Initializer, feature, enable| {
        if enable {
            value.set(feature as u32);
        }
    };

    // The values are part of the platform-specific [cpucfg]
    //
    // [cpucfg]: LoongArch Reference Manual Volume 1: Basic Architecture v1.1
    let cpucfg2: usize;
    unsafe {
        asm!(
            "cpucfg {}, {}",
            out(reg) cpucfg2, in(reg) 2,
            options(pure, nomem, preserves_flags, nostack)
        );
    }
    enable_feature(&mut value, Feature::frecipe, bit::test(cpucfg2, 25));

    // The values are part of the platform-specific [asm/hwcap.h][hwcap]
    //
    // [hwcap]: https://github.com/torvalds/linux/blob/master/arch/loongarch/include/uapi/asm/hwcap.h
    if let Ok(auxv) = auxvec::auxv() {
        enable_feature(&mut value, Feature::lsx, bit::test(auxv.hwcap, 4));
        enable_feature(&mut value, Feature::lasx, bit::test(auxv.hwcap, 5));
        return value;
    }
    value
}
