linkcell 0.5.0

Periodic linked-cell cutoff pairs and k-nearest neighbour search
Documentation
fn main() {
    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-changed=src/knn_region.c");
    println!("cargo:rerun-if-env-changed=LINKCELL_OPENMP");
    #[cfg(feature = "scotch")]
    build_scotch();
    #[cfg(feature = "ptscotch")]
    build_ptscotch();
    let (major, minor) = rustc_version();
    // `unexpected_cfgs` arrived in 1.80. AVX-512 intrinsics arrived in 1.89.
    if major > 1 || minor >= 80 {
        println!("cargo:rustc-check-cfg=cfg(linkcell_avx512)");
        println!("cargo:rustc-check-cfg=cfg(linkcell_openmp)");
    }
    if major > 1 || minor >= 89 {
        println!("cargo:rustc-cfg=linkcell_avx512");
    }
    // Linux and macOS with `parallel` link the fused OpenMP region. A failed
    // probe is a build error on glibc Linux and macOS. LINKCELL_OPENMP=0
    // keeps rayon and skips the region, so the archive does not reference
    // libgomp or libomp.
    if std::env::var_os("CARGO_FEATURE_PARALLEL").is_some()
        && openmp_requested()
        && compile_knn_region()
    {
        println!("cargo:rustc-cfg=linkcell_openmp");
    }
}

/// Meson and CMake set LINKCELL_OPENMP. Unset keeps the historical default.
fn openmp_requested() -> bool {
    match std::env::var("LINKCELL_OPENMP") {
        Ok(value) => {
            let value = value.trim().to_ascii_lowercase();
            value != "0" && value != "false" && value != "off" && value != "no"
        }
        Err(_) => true,
    }
}

fn target_is(key: &str, value: &str) -> bool {
    std::env::var(key).ok().as_deref() == Some(value)
}

/// Compile `src/knn_region.c` with OpenMP for the target, through the `cc`
/// crate so `CC`, the target triple and cross compilers are honoured.
/// On glibc Linux and macOS a failure is a build error. musl and other
/// targets keep the rayon walk when the region does not build.
fn compile_knn_region() -> bool {
    let linux = target_is("CARGO_CFG_TARGET_OS", "linux");
    let macos = target_is("CARGO_CFG_TARGET_OS", "macos");
    if !linux && !macos {
        return false;
    }
    let required = macos || target_is("CARGO_CFG_TARGET_ENV", "gnu");
    let macos_libomp = macos.then(|| {
        libomp_prefix().unwrap_or_else(|| {
            panic!(
                "OpenMP k-nearest region: finding libomp failed; \
                     run `brew install libomp` or set LIBOMP_PREFIX"
            )
        })
    });
    let mut build = cc::Build::new();
    // Clang as `cc` passes `--target=<rust-triple>` and then does not see
    // gcc's `omp.h`. A native build with no compiler chosen keeps gcc. A
    // chosen compiler or a cross build is left to the `cc` crate, and the
    // runtime linked below follows whichever compiler that is.
    let target = std::env::var("TARGET").unwrap_or_default();
    let chosen = [
        "CC".to_string(),
        "TARGET_CC".to_string(),
        format!("CC_{target}"),
        format!("CC_{}", target.replace('-', "_")),
    ];
    for key in &chosen {
        println!("cargo:rerun-if-env-changed={key}");
    }
    if linux
        && chosen.iter().all(|key| std::env::var_os(key).is_none())
        && std::env::var("HOST").ok().as_deref() == Some(target.as_str())
    {
        build.compiler("gcc");
    }
    build
        .file("src/knn_region.c")
        .flag("-pthread")
        .opt_level(2)
        .warnings(true)
        .extra_warnings(true);
    if let Some(prefix) = &macos_libomp {
        build
            .flag("-Xpreprocessor")
            .flag("-fopenmp")
            .include(prefix.join("include"));
    } else {
        build.flag("-fopenmp");
    }
    // The region coordinates threads and does no arithmetic worth
    // vectorising. Pin the x86_64 baseline so no host-specific ISA reaches
    // a path that is not runtime-dispatched.
    if target_is("CARGO_CFG_TARGET_ARCH", "x86_64") {
        build
            .flag("-march=x86-64")
            .flag("-mtune=generic")
            .flag("-fno-tree-vectorize");
    }
    if let Err(err) = build.try_compile("knnregion") {
        if required {
            panic!("OpenMP k-nearest region: compiling src/knn_region.c failed: {err}");
        }
        return false;
    }
    // Clang's -fopenmp emits __kmpc_* calls into libomp, GCC's emits GOMP_*
    // calls into libgomp. Link the runtime of the compiler that built the
    // region, so a Clang build does not load both.
    let compiler = build.get_compiler();
    let runtime = if macos || compiler.is_like_clang() {
        "omp"
    } else {
        "gomp"
    };
    let directory = macos_libomp
        .map(|prefix| prefix.join("lib"))
        .or_else(|| runtime_dir(compiler.path(), runtime));
    match directory {
        Some(dir) => {
            println!("cargo:rustc-link-search=native={}", dir.display());
            println!("cargo:rustc-link-lib={runtime}");
            true
        }
        None if required => panic!("OpenMP k-nearest region: finding lib{runtime} failed"),
        None => false,
    }
}

/// The prefix holding `include/omp.h` and `lib/libomp.dylib`. A caller that
/// builds its own runtime names it with `LIBOMP_PREFIX`; wheels do, because
/// a runtime they bundle must not need a newer macOS than the wheel claims.
/// Otherwise ask Homebrew's keg-only libomp, through `brew` and then the
/// standard Apple Silicon and Intel prefixes.
fn libomp_prefix() -> Option<std::path::PathBuf> {
    println!("cargo:rerun-if-env-changed=PATH");
    println!("cargo:rerun-if-env-changed=LIBOMP_PREFIX");
    let mut prefixes = Vec::new();
    if let Some(prefix) = std::env::var_os("LIBOMP_PREFIX").filter(|prefix| !prefix.is_empty()) {
        prefixes.push(std::path::PathBuf::from(prefix));
    }
    if let Ok(output) = std::process::Command::new("brew")
        .args(["--prefix", "libomp"])
        .output()
    {
        if output.status.success() {
            if let Ok(text) = String::from_utf8(output.stdout) {
                prefixes.push(std::path::PathBuf::from(text.trim()));
            }
        }
    }
    prefixes.extend([
        std::path::PathBuf::from("/opt/homebrew/opt/libomp"),
        std::path::PathBuf::from("/usr/local/opt/libomp"),
    ]);
    prefixes.into_iter().find(|prefix| {
        prefix.join("include/omp.h").is_file() && prefix.join("lib/libomp.dylib").is_file()
    })
}

/// The directory holding `lib<runtime>.so`: the compiler's own search
/// path first, then `LIBRARY_PATH`, then the library directory beside
/// Clang's resource directory. Both drivers link `-l<runtime>` from
/// `LIBRARY_PATH`, but Clang's `-print-file-name` does not look there, so
/// a libomp reached only through it (a sanitizer build of the runtime, a
/// conda prefix) is otherwise reported missing. Clang also answers with
/// the bare name for the libomp a distribution installs in `<llvm>/lib`,
/// next to its resource directory `<llvm>/lib/clang/<v>`.
fn runtime_dir(cc: &std::path::Path, runtime: &str) -> Option<std::path::PathBuf> {
    let file = format!("lib{runtime}.so");
    println!("cargo:rerun-if-env-changed=LIBRARY_PATH");
    if let Some(dir) = compiler_says(cc, &format!("-print-file-name={file}"))
        .filter(|path| path.is_absolute() && path.is_file())
        .and_then(|path| path.parent().map(|dir| dir.to_path_buf()))
    {
        return Some(dir);
    }
    if let Some(dir) = std::env::var_os("LIBRARY_PATH").and_then(|dirs| {
        std::env::split_paths(&dirs)
            .filter(|dir| dir.is_absolute())
            .find(|dir| dir.join(&file).is_file())
    }) {
        return Some(dir);
    }
    let resource = compiler_says(cc, "-print-resource-dir")?;
    let dir = resource.parent()?.parent()?;
    dir.join(&file).is_file().then(|| dir.to_path_buf())
}

fn compiler_says(cc: &std::path::Path, arg: &str) -> Option<std::path::PathBuf> {
    std::process::Command::new(cc)
        .arg(arg)
        .output()
        .ok()
        .filter(|out| out.status.success())
        .and_then(|out| String::from_utf8(out.stdout).ok())
        .map(|text| std::path::PathBuf::from(text.trim()))
}

#[cfg(feature = "scotch")]
fn build_scotch() {
    println!("cargo:rerun-if-changed=src/scotch_part.c");
    let include = std::env::var("SCOTCH_INCLUDE").ok().or_else(|| {
        ["/usr/include/scotch", "/usr/include"]
            .into_iter()
            .find(|dir| std::path::Path::new(dir).join("scotch.h").is_file())
            .map(|dir| dir.to_string())
    });
    let Some(include) = include else {
        panic!("scotch feature needs scotch.h (set SCOTCH_INCLUDE)");
    };
    let mut build = cc::Build::new();
    build
        .file("src/scotch_part.c")
        .include(&include)
        .warnings(true);
    build.compile("linkcell_scotch");
    println!("cargo:rustc-link-lib=scotch");
    println!("cargo:rustc-link-lib=scotcherr");
    println!("cargo:rustc-link-lib=m");
}

#[cfg(feature = "ptscotch")]
fn build_ptscotch() {
    println!("cargo:rerun-if-changed=src/ptscotch_part.c");
    let include = std::env::var("SCOTCH_INCLUDE").unwrap_or_else(|_| "/usr/include/scotch".into());
    cc::Build::new()
        .file("src/ptscotch_part.c")
        .include(&include)
        .include("/usr/lib/x86_64-linux-gnu/openmpi/include")
        .warnings(true)
        .compile("linkcell_ptscotch");
    println!("cargo:rustc-link-search=native=/usr/lib/x86_64-linux-gnu/openmpi/lib");
    println!("cargo:rustc-link-lib=ptscotch");
    println!("cargo:rustc-link-lib=scotch");
    println!("cargo:rustc-link-lib=ptscotcherr");
    println!("cargo:rustc-link-lib=scotcherr");
    println!("cargo:rustc-link-lib=mpi");
    println!("cargo:rustc-link-lib=m");
}

fn rustc_version() -> (u32, u32) {
    let rustc = std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_string());
    let out = std::process::Command::new(rustc)
        .arg("-vV")
        .output()
        .expect("rustc -vV");
    let text = String::from_utf8_lossy(&out.stdout);
    for line in text.lines() {
        if let Some(rest) = line.strip_prefix("release: ") {
            let ver = rest.split('-').next().unwrap_or(rest);
            let mut parts = ver.split('.');
            let major = parts.next().unwrap_or("1").parse().unwrap_or(1);
            let minor = parts.next().unwrap_or("70").parse().unwrap_or(70);
            return (major, minor);
        }
    }
    (1, 70)
}