src/bootstrap/src/core/build_steps/llvm.rs RUST 1,831 lines View on github.com → Search inside
1//! Compilation of native dependencies like LLVM.2//!3//! Native projects like LLVM unfortunately aren't suited just yet for4//! compilation in build scripts that Cargo has. This is because the5//! compilation takes a *very* long time but also because we don't want to6//! compile LLVM 3 times as part of a normal bootstrap (we want it cached).7//!8//! LLVM and compiler-rt are essentially just wired up to everything else to9//! ensure that they're always in place if needed.1011use std::env::consts::EXE_EXTENSION;12use std::ffi::{OsStr, OsString};13use std::path::{Path, PathBuf};14use std::sync::OnceLock;15use std::{env, fs};1617use build_helper::exit;18use build_helper::git::PathFreshness;1920use crate::core::build_steps::llvm;21use crate::core::builder::{Builder, RunConfig, ShouldRun, Step, StepMetadata};22use crate::core::config::{Config, TargetSelection};23use crate::utils::build_stamp::{BuildStamp, generate_smart_stamp_hash};24use crate::utils::exec::command;25use crate::utils::helpers::{26    self, exe, get_clang_cl_resource_dir, libdir, t, unhashed_basename, up_to_date,27};28use crate::{CLang, GitRepo, Kind, trace};2930#[derive(Clone)]31pub struct LlvmResult {32    /// Path to llvm-config binary.33    /// NB: This is always the host llvm-config!34    pub host_llvm_config: PathBuf,35    /// Path to LLVM cmake directory for the target.36    pub llvm_cmake_dir: PathBuf,37}3839pub struct Meta {40    stamp: BuildStamp,41    res: LlvmResult,42    out_dir: PathBuf,43    root: String,44}4546pub enum LlvmBuildStatus {47    AlreadyBuilt(LlvmResult),48    ShouldBuild(Meta),49}5051impl LlvmBuildStatus {52    pub fn should_build(&self) -> bool {53        match self {54            LlvmBuildStatus::AlreadyBuilt(_) => false,55            LlvmBuildStatus::ShouldBuild(_) => true,56        }57    }5859    #[cfg(test)]60    pub fn llvm_result(&self) -> &LlvmResult {61        match self {62            LlvmBuildStatus::AlreadyBuilt(res) => res,63            LlvmBuildStatus::ShouldBuild(meta) => &meta.res,64        }65    }66}6768/// Allows each step to add C/Cxx flags which are only used for a specific cmake invocation.69#[derive(Debug, Clone, Default)]70struct CcFlags {71    /// Additional values for CMAKE_CC_FLAGS, to be added before all other values.72    cflags: OsString,73    /// Additional values for CMAKE_CXX_FLAGS, to be added before all other values.74    cxxflags: OsString,75}7677impl CcFlags {78    fn push_all(&mut self, s: impl AsRef<OsStr>) {79        let s = s.as_ref();80        self.cflags.push(" ");81        self.cflags.push(s);82        self.cxxflags.push(" ");83        self.cxxflags.push(s);84    }85}8687/// Linker flags to pass to LLVM's CMake invocation.88#[derive(Debug, Clone, Default)]89struct LdFlags {90    /// CMAKE_EXE_LINKER_FLAGS91    exe: OsString,92    /// CMAKE_SHARED_LINKER_FLAGS93    shared: OsString,94    /// CMAKE_MODULE_LINKER_FLAGS95    module: OsString,96}9798impl LdFlags {99    fn push_all(&mut self, s: impl AsRef<OsStr>) {100        let s = s.as_ref();101        self.exe.push(" ");102        self.exe.push(s);103        self.shared.push(" ");104        self.shared.push(s);105        self.module.push(" ");106        self.module.push(s);107    }108}109110/// This returns whether we've already previously built LLVM.111///112/// It's used to avoid busting caches during x.py check -- if we've already built113/// LLVM, it's fine for us to not try to avoid doing so.114///115/// This will return the llvm-config if it can get it (but it will not build it116/// if not).117pub fn prebuilt_llvm_config(118    builder: &Builder<'_>,119    target: TargetSelection,120    // Certain commands (like `x test mir-opt --bless`) may call this function with different targets,121    // which could bypass the CI LLVM early-return even if `builder.config.llvm_from_ci` is true.122    // This flag should be `true` only if the caller needs the LLVM sources (e.g., if it will build LLVM).123    handle_submodule_when_needed: bool,124) -> LlvmBuildStatus {125    builder.config.maybe_download_ci_llvm();126127    // If we're using a custom LLVM bail out here, but we can only use a128    // custom LLVM for the build triple.129    if let Some(config) = builder.config.target_config.get(&target)130        && let Some(ref s) = config.llvm_config131    {132        check_llvm_version(builder, s);133        let host_llvm_config = s.to_path_buf();134        let mut llvm_cmake_dir = host_llvm_config.clone();135        llvm_cmake_dir.pop();136        llvm_cmake_dir.pop();137        llvm_cmake_dir.push("lib");138        llvm_cmake_dir.push("cmake");139        llvm_cmake_dir.push("llvm");140        return LlvmBuildStatus::AlreadyBuilt(LlvmResult { host_llvm_config, llvm_cmake_dir });141    }142143    if handle_submodule_when_needed {144        // If submodules are disabled, this does nothing.145        builder.config.update_submodule("src/llvm-project");146    }147148    let root = "src/llvm-project/llvm";149    let out_dir = builder.llvm_out(target);150151    let build_llvm_config = if let Some(build_llvm_config) = builder152        .config153        .target_config154        .get(&builder.config.host_target)155        .and_then(|config| config.llvm_config.clone())156    {157        build_llvm_config158    } else {159        let mut llvm_config_ret_dir = builder.llvm_out(builder.config.host_target);160        llvm_config_ret_dir.push("bin");161        llvm_config_ret_dir.join(exe("llvm-config", builder.config.host_target))162    };163164    let llvm_cmake_dir = out_dir.join("lib/cmake/llvm");165    let res = LlvmResult { host_llvm_config: build_llvm_config, llvm_cmake_dir };166167    static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();168    let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {169        generate_smart_stamp_hash(170            builder,171            &builder.config.src.join("src/llvm-project"),172            builder.in_tree_llvm_info.sha().unwrap_or_default(),173        )174    });175176    let stamp = BuildStamp::new(&out_dir).with_prefix("llvm").add_stamp(smart_stamp_hash);177178    if stamp.is_up_to_date() {179        if stamp.stamp().is_empty() {180            builder.info(181                "Could not determine the LLVM submodule commit hash. \182                     Assuming that an LLVM rebuild is not necessary.",183            );184            builder.info(&format!(185                "To force LLVM to rebuild, remove the file `{}`",186                stamp.path().display()187            ));188        }189        return LlvmBuildStatus::AlreadyBuilt(res);190    }191192    LlvmBuildStatus::ShouldBuild(Meta { stamp, res, out_dir, root: root.into() })193}194195/// Paths whose changes invalidate LLVM downloads.196pub const LLVM_INVALIDATION_PATHS: &[&str] = &[197    "src/llvm-project",198    "src/bootstrap/download-ci-llvm-stamp",199    // the LLVM shared object file is named `LLVM-<LLVM-version>-rust-{version}-nightly`200    "src/version",201];202203/// Detect whether LLVM sources have been modified locally or not.204pub(crate) fn detect_llvm_freshness(config: &Config, is_git: bool) -> PathFreshness {205    if is_git {206        config.check_path_modifications(LLVM_INVALIDATION_PATHS)207    } else if let Some(info) = crate::utils::channel::read_commit_info_file(&config.src) {208        PathFreshness::LastModifiedUpstream { upstream: info.sha.trim().to_owned() }209    } else {210        PathFreshness::MissingUpstream211    }212}213214/// Returns whether the CI-found LLVM is currently usable.215///216/// This checks the build triple platform to confirm we're usable at all, and if LLVM217/// with/without assertions is available.218pub(crate) fn is_ci_llvm_available_for_target(219    host_target: &TargetSelection,220    asserts: bool,221) -> bool {222    // This is currently all tier 1 targets and tier 2 targets with host tools223    // (since others may not have CI artifacts)224    // https://doc.rust-lang.org/rustc/platform-support.html#tier-1225    let supported_platforms = [226        // tier 1227        ("aarch64-unknown-linux-gnu", false),228        ("aarch64-apple-darwin", false),229        ("aarch64-pc-windows-msvc", false),230        ("i686-pc-windows-msvc", false),231        ("i686-unknown-linux-gnu", false),232        ("x86_64-unknown-linux-gnu", true),233        ("x86_64-apple-darwin", true),234        ("x86_64-pc-windows-gnu", false),235        ("x86_64-pc-windows-msvc", true),236        // tier 2 with host tools237        ("aarch64-unknown-linux-musl", false),238        ("aarch64-pc-windows-gnullvm", false),239        ("arm-unknown-linux-gnueabi", false),240        ("arm-unknown-linux-gnueabihf", false),241        ("armv7-unknown-linux-gnueabihf", false),242        ("i686-pc-windows-gnu", false),243        ("loongarch64-unknown-linux-gnu", false),244        ("loongarch64-unknown-linux-musl", false),245        ("powerpc-unknown-linux-gnu", false),246        ("powerpc64-unknown-linux-gnu", false),247        ("powerpc64-unknown-linux-musl", false),248        ("powerpc64le-unknown-linux-gnu", false),249        ("powerpc64le-unknown-linux-musl", false),250        ("riscv64gc-unknown-linux-gnu", false),251        ("s390x-unknown-linux-gnu", false),252        ("x86_64-pc-windows-gnullvm", false),253        ("x86_64-unknown-freebsd", false),254        ("x86_64-unknown-illumos", false),255        ("x86_64-unknown-linux-musl", false),256        ("x86_64-unknown-netbsd", false),257    ];258259    if !supported_platforms.contains(&(&*host_target.triple, asserts))260        && (asserts || !supported_platforms.contains(&(&*host_target.triple, true)))261    {262        return false;263    }264265    true266}267268#[derive(Debug, Clone, Hash, PartialEq, Eq)]269pub struct Llvm {270    pub target: TargetSelection,271}272273impl Step for Llvm {274    type Output = LlvmResult;275276    const IS_HOST: bool = true;277278    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {279        run.path("src/llvm-project").path("src/llvm-project/llvm")280    }281282    fn make_run(run: RunConfig<'_>) {283        run.builder.ensure(Llvm { target: run.target });284    }285286    /// Compile LLVM for `target`.287    fn run(self, builder: &Builder<'_>) -> LlvmResult {288        let target = self.target;289        let target_native = if self.target.starts_with("riscv") {290            // RISC-V target triples in Rust is not named the same as C compiler target triples.291            // This converts Rust RISC-V target triples to C compiler triples.292            let idx = target.triple.find('-').unwrap();293294            format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])295        } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {296            // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.297            // Set the version suffix to 13.0 so the correct target details are used.298            format!("{}{}", self.target, "13.0")299        } else {300            target.to_string()301        };302303        // If LLVM has already been built or been downloaded through download-ci-llvm, we avoid building it again.304        let Meta { stamp, res, out_dir, root } = match prebuilt_llvm_config(builder, target, true) {305            LlvmBuildStatus::AlreadyBuilt(p) => return p,306            LlvmBuildStatus::ShouldBuild(m) => m,307        };308309        if builder.llvm_link_shared() && target.is_windows() && !target.is_windows_gnullvm() {310            panic!("shared linking to LLVM is not currently supported on {}", target.triple);311        }312313        let _guard = builder.msg_unstaged(Kind::Build, "LLVM", target);314        t!(stamp.remove());315        let _time = helpers::timeit(builder);316        t!(fs::create_dir_all(&out_dir));317318        // https://llvm.org/docs/CMake.html319        let mut cfg = cmake::Config::new(builder.src.join(root));320        let mut ldflags = LdFlags::default();321322        let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {323            (false, _) => "Debug",324            (true, false) => "Release",325            (true, true) => "RelWithDebInfo",326        };327328        // NOTE: remember to also update `bootstrap.example.toml` when changing the329        // defaults!330        let llvm_targets = match &builder.config.llvm_targets {331            Some(s) => s,332            None => {333                "AArch64;AMDGPU;ARM;BPF;Hexagon;LoongArch;MSP430;Mips;NVPTX;PowerPC;RISCV;\334                     Sparc;SystemZ;WebAssembly;X86"335            }336        };337338        let llvm_exp_targets = match builder.config.llvm_experimental_targets {339            Some(ref s) => s,340            None => "AVR;M68k;CSKY;Xtensa",341        };342343        let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };344        let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };345        let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };346        let enable_warnings = if builder.config.llvm_enable_warnings { "ON" } else { "OFF" };347348        cfg.out_dir(&out_dir)349            .profile(profile)350            .define("LLVM_ENABLE_ASSERTIONS", assertions)351            .define("LLVM_UNREACHABLE_OPTIMIZE", "OFF")352            .define("LLVM_ENABLE_PLUGINS", plugins)353            .define("LLVM_TARGETS_TO_BUILD", llvm_targets)354            .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)355            .define("LLVM_INCLUDE_EXAMPLES", "OFF")356            .define("LLVM_INCLUDE_DOCS", "OFF")357            .define("LLVM_INCLUDE_BENCHMARKS", "OFF")358            .define("LLVM_INCLUDE_TESTS", enable_tests)359            .define("LLVM_ENABLE_LIBEDIT", "OFF")360            .define("LLVM_ENABLE_BINDINGS", "OFF")361            .define("LLVM_ENABLE_Z3_SOLVER", "OFF")362            .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())363            .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())364            .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native)365            .define("LLVM_ENABLE_WARNINGS", enable_warnings);366367        // Parts of our test suite rely on the `FileCheck` tool, which is built by default in368        // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.369        // This flag makes sure `FileCheck` is copied in the final binaries directory.370        cfg.define("LLVM_INSTALL_UTILS", "ON");371372        if builder.config.llvm_profile_generate {373            cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");374            if let Ok(llvm_profile_dir) = std::env::var("LLVM_PROFILE_DIR") {375                cfg.define("LLVM_PROFILE_DATA_DIR", llvm_profile_dir);376            }377            cfg.define("LLVM_BUILD_RUNTIME", "No");378        }379        if let Some(path) = builder.config.llvm_profile_use.as_ref() {380            cfg.define("LLVM_PROFDATA_FILE", path);381        }382383        // Libraries for ELF section compression and profraw files merging.384        if !target.is_msvc() {385            cfg.define("LLVM_ENABLE_ZLIB", "ON");386        } else {387            cfg.define("LLVM_ENABLE_ZLIB", "OFF");388        }389390        // Are we compiling for iOS/tvOS/watchOS/visionOS?391        if target.contains("apple-ios")392            || target.contains("apple-tvos")393            || target.contains("apple-watchos")394            || target.contains("apple-visionos")395        {396            // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.397            cfg.define("LLVM_ENABLE_PLUGINS", "OFF");398            // Zlib fails to link properly, leading to a compiler error.399            cfg.define("LLVM_ENABLE_ZLIB", "OFF");400        }401402        // This setting makes the LLVM tools link to the dynamic LLVM library,403        // which saves both memory during parallel links and overall disk space404        // for the tools. We don't do this on every platform as it doesn't work405        // equally well everywhere.406        if builder.llvm_link_shared() {407            cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");408        }409410        if (target.starts_with("csky")411            || target.starts_with("riscv")412            || target.starts_with("sparc-"))413            && !target.contains("freebsd")414            && !target.contains("openbsd")415            && !target.contains("netbsd")416        {417            // CSKY and RISC-V GCC erroneously requires linking against418            // `libatomic` when using 1-byte and 2-byte C++419            // atomics but the LLVM build system check cannot420            // detect this. Therefore it is set manually here.421            // Some BSD uses Clang as its system compiler and422            // provides no libatomic in its base system so does423            // not want this. 32-bit SPARC requires linking against424            // libatomic as well.425            ldflags.exe.push(" -latomic");426            ldflags.shared.push(" -latomic");427        }428429        if target.starts_with("mips") && target.contains("netbsd") {430            // LLVM wants 64-bit atomics, while mipsel is 32-bit only, so needs -latomic431            ldflags.exe.push(" -latomic");432            ldflags.shared.push(" -latomic");433        }434435        if target.starts_with("arm64ec") {436            // MSVC linker requires the -machine:arm64ec flag to be passed to437            // know it's linking as Arm64EC (vs Arm64X).438            ldflags.exe.push(" -machine:arm64ec");439            ldflags.shared.push(" -machine:arm64ec");440        }441442        if target.is_msvc() {443            cfg.define("CMAKE_MSVC_RUNTIME_LIBRARY", "MultiThreaded");444            cfg.static_crt(true);445        }446447        if target.starts_with("i686") {448            cfg.define("LLVM_BUILD_32_BITS", "ON");449        }450451        if target.starts_with("x86_64") && target.contains("ohos") {452            cfg.define("LLVM_TOOL_LLVM_RTDYLD_BUILD", "OFF");453        }454455        let mut enabled_llvm_projects = Vec::new();456457        if helpers::forcing_clang_based_tests() {458            enabled_llvm_projects.push("clang");459        }460461        if builder.config.llvm_polly {462            enabled_llvm_projects.push("polly");463        }464465        if builder.config.llvm_clang {466            enabled_llvm_projects.push("clang");467        }468469        // We want libxml to be disabled.470        // See https://github.com/rust-lang/rust/pull/50104471        cfg.define("LLVM_ENABLE_LIBXML2", "OFF");472473        let mut enabled_llvm_runtimes = Vec::new();474475        if helpers::forcing_clang_based_tests() {476            enabled_llvm_runtimes.push("compiler-rt");477        }478479        if !enabled_llvm_projects.is_empty() {480            enabled_llvm_projects.sort();481            enabled_llvm_projects.dedup();482            cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));483        }484485        if !enabled_llvm_runtimes.is_empty() {486            enabled_llvm_runtimes.sort();487            enabled_llvm_runtimes.dedup();488            cfg.define("LLVM_ENABLE_RUNTIMES", enabled_llvm_runtimes.join(";"));489        }490491        if let Some(num_linkers) = builder.config.llvm_link_jobs492            && num_linkers > 0493        {494            cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());495        }496497        // https://llvm.org/docs/HowToCrossCompileLLVM.html498        if !builder.config.is_host_target(target) {499            let LlvmResult { host_llvm_config, .. } =500                builder.ensure(Llvm { target: builder.config.host_target });501            if !builder.config.dry_run() {502                let llvm_bindir = command(&host_llvm_config)503                    .arg("--bindir")504                    .cached()505                    .run_capture_stdout(builder)506                    .stdout();507                let host_bin = Path::new(llvm_bindir.trim());508                cfg.define(509                    "LLVM_TABLEGEN",510                    host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION),511                );512                // LLVM_NM is required for cross compiling using MSVC513                cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));514            }515            cfg.define("LLVM_CONFIG_PATH", host_llvm_config);516            if builder.config.llvm_clang {517                let build_bin =518                    builder.llvm_out(builder.config.host_target).join("build").join("bin");519                let clang_tblgen = build_bin.join("clang-tblgen").with_extension(EXE_EXTENSION);520                if !builder.config.dry_run() && !clang_tblgen.exists() {521                    panic!("unable to find {}", clang_tblgen.display());522                }523                cfg.define("CLANG_TABLEGEN", clang_tblgen);524            }525        }526527        let llvm_version_suffix = if let Some(ref suffix) = builder.config.llvm_version_suffix {528            // Allow version-suffix="" to not define a version suffix at all.529            if !suffix.is_empty() { Some(suffix.to_string()) } else { None }530        } else if builder.config.channel == "dev" {531            // Changes to a version suffix require a complete rebuild of the LLVM.532            // To avoid rebuilds during a time of version bump, don't include rustc533            // release number on the dev channel.534            Some("-rust-dev".to_string())535        } else {536            Some(format!("-rust-{}-{}", builder.version, builder.config.channel))537        };538        if let Some(ref suffix) = llvm_version_suffix {539            cfg.define("LLVM_VERSION_SUFFIX", suffix);540        }541542        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);543        configure_llvm(builder, target, &mut cfg);544545        for (key, val) in &builder.config.llvm_build_config {546            cfg.define(key, val);547        }548549        if builder.config.dry_run() {550            return res;551        }552553        cfg.build();554555        // Helper to find the name of LLVM's shared library on darwin and linux.556        let find_llvm_lib_name = |extension| {557            let major = get_llvm_version_major(builder, &res.host_llvm_config);558            match &llvm_version_suffix {559                Some(version_suffix) => format!("libLLVM-{major}{version_suffix}.{extension}"),560                None => format!("libLLVM-{major}.{extension}"),561            }562        };563564        // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned565        // libLLVM.dylib will be built. However, llvm-config will still look566        // for a versioned path like libLLVM-14.dylib. Manually create a symbolic567        // link to make llvm-config happy.568        if builder.llvm_link_shared() && target.contains("apple-darwin") {569            let lib_name = find_llvm_lib_name("dylib");570            let lib_llvm = out_dir.join("build").join("lib").join(lib_name);571            if !lib_llvm.exists() {572                t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));573            }574        }575576        // When building LLVM as a shared library on linux, it can contain unexpected debuginfo:577        // some can come from the C++ standard library. Unless we're explicitly requesting LLVM to578        // be built with debuginfo, strip it away after the fact, to make dist artifacts smaller.579        if builder.llvm_link_shared()580            && builder.config.llvm_optimize581            && !builder.config.llvm_release_debuginfo582        {583            // Find the name of the LLVM shared library that we just built.584            let lib_name = find_llvm_lib_name("so");585586            // If the shared library exists in LLVM's `/build/lib/` or `/lib/` folders, strip its587            // debuginfo.588            crate::core::build_steps::compile::strip_debug(589                builder,590                target,591                &out_dir.join("lib").join(&lib_name),592            );593            crate::core::build_steps::compile::strip_debug(594                builder,595                target,596                &out_dir.join("build").join("lib").join(&lib_name),597            );598        }599600        t!(stamp.write());601602        res603    }604605    fn metadata(&self) -> Option<StepMetadata> {606        Some(StepMetadata::build("llvm", self.target))607    }608}609610pub fn get_llvm_version(builder: &Builder<'_>, llvm_config: &Path) -> String {611    command(llvm_config)612        .arg("--version")613        .cached()614        .run_capture_stdout(builder)615        .stdout()616        .trim()617        .to_owned()618}619620pub fn get_llvm_version_major(builder: &Builder<'_>, llvm_config: &Path) -> u8 {621    let version = get_llvm_version(builder, llvm_config);622    let major_str = version.split_once('.').expect("Failed to parse LLVM version").0;623    major_str.parse().unwrap()624}625626fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {627    if builder.config.dry_run() {628        return;629    }630631    let version = get_llvm_version(builder, llvm_config);632    let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());633    if let (Some(major), Some(_minor)) = (parts.next(), parts.next())634        && major >= 21635    {636        return;637    }638    panic!("\n\nbad LLVM version: {version}, need >=21\n\n")639}640641fn configure_cmake(642    builder: &Builder<'_>,643    target: TargetSelection,644    cfg: &mut cmake::Config,645    use_compiler_launcher: bool,646    mut ldflags: LdFlags,647    ccflags: CcFlags,648    suppressed_compiler_flag_prefixes: &[&str],649) {650    // Do not print installation messages for up-to-date files.651    // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.652    cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");653654    if builder.config.quiet {655        // Only log errors and warnings from `cmake`.656        cfg.define("CMAKE_MESSAGE_LOG_LEVEL", "WARNING");657658        // If we're configuring llvm to build with `ninja`, we can suppress output from it with659        // `--quiet`. Otherwise don't add anything since we don't know which build system is going660        // to use.661        if builder.ninja() {662            cfg.build_arg("--quiet");663        }664    }665666    // Do not allow the user's value of DESTDIR to influence where667    // LLVM will install itself. LLVM must always be installed in our668    // own build directories.669    cfg.env("DESTDIR", "");670671    if builder.ninja() {672        cfg.generator("Ninja");673    }674    cfg.target(&target.triple).host(&builder.config.host_target.triple);675676    if !builder.config.is_host_target(target) {677        cfg.define("CMAKE_CROSSCOMPILING", "True");678679        // NOTE: Ideally, we wouldn't have to do this, and `cmake-rs` would just handle it for us.680        // But it currently determines this based on the `CARGO_CFG_TARGET_OS` environment variable,681        // which isn't set when compiling outside `build.rs` (like bootstrap is).682        //683        // So for now, we define `CMAKE_SYSTEM_NAME` ourselves, to panicking in `cmake-rs`.684        if target.contains("netbsd") {685            cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");686        } else if target.contains("dragonfly") {687            cfg.define("CMAKE_SYSTEM_NAME", "DragonFly");688        } else if target.contains("openbsd") {689            cfg.define("CMAKE_SYSTEM_NAME", "OpenBSD");690        } else if target.contains("freebsd") {691            cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");692        } else if target.is_windows() {693            cfg.define("CMAKE_SYSTEM_NAME", "Windows");694        } else if target.contains("haiku") {695            cfg.define("CMAKE_SYSTEM_NAME", "Haiku");696        } else if target.contains("solaris") || target.contains("illumos") {697            cfg.define("CMAKE_SYSTEM_NAME", "SunOS");698        } else if target.contains("linux") {699            cfg.define("CMAKE_SYSTEM_NAME", "Linux");700        } else if target.contains("darwin") {701            // macOS702            cfg.define("CMAKE_SYSTEM_NAME", "Darwin");703        } else if target.contains("ios") {704            cfg.define("CMAKE_SYSTEM_NAME", "iOS");705        } else if target.contains("tvos") {706            cfg.define("CMAKE_SYSTEM_NAME", "tvOS");707        } else if target.contains("visionos") {708            cfg.define("CMAKE_SYSTEM_NAME", "visionOS");709        } else if target.contains("watchos") {710            cfg.define("CMAKE_SYSTEM_NAME", "watchOS");711        } else if target.contains("none") {712            // "none" should be the last branch713            cfg.define("CMAKE_SYSTEM_NAME", "Generic");714        } else {715            builder.info(&format!(716                "could not determine CMAKE_SYSTEM_NAME from the target `{target}`, build may fail",717            ));718            // Fallback, set `CMAKE_SYSTEM_NAME` anyhow to avoid the logic `cmake-rs` tries, and719            // to avoid CMAKE_SYSTEM_NAME being inferred from the host.720            cfg.define("CMAKE_SYSTEM_NAME", "Generic");721        }722723        // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in724        // that case like CMake we cannot easily determine system version either.725        //726        // Since, the LLVM itself makes rather limited use of version checks in727        // CMakeFiles (and then only in tests), and so far no issues have been728        // reported, the system version is currently left unset.729730        if target.contains("apple") {731            if !target.contains("darwin") {732                // FIXME(madsmtm): compiler-rt's CMake setup is kinda weird, it seems like they do733                // version testing etc. for macOS (i.e. Darwin), even while building for iOS?734                //735                // So for now we set it to "Darwin" on all Apple platforms.736                cfg.define("CMAKE_SYSTEM_NAME", "Darwin");737738                // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.739                cfg.define("CMAKE_OSX_SYSROOT", "/");740                cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");741            }742743            // Make sure that CMake does not build universal binaries on macOS.744            // Explicitly specify the one single target architecture.745            if target.starts_with("aarch64") {746                // macOS uses a different name for building arm64747                cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");748            } else if target.starts_with("i686") {749                // macOS uses a different name for building i386750                cfg.define("CMAKE_OSX_ARCHITECTURES", "i386");751            } else {752                cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());753            }754        }755    }756757    let sanitize_cc = |cc: &Path| {758        if target.is_msvc() {759            OsString::from(cc.to_str().unwrap().replace('\\', "/"))760        } else {761            cc.as_os_str().to_owned()762        }763    };764765    // MSVC with CMake uses msbuild by default which doesn't respect these766    // vars that we'd otherwise configure. In that case we just skip this767    // entirely.768    if target.is_msvc() && !builder.ninja() {769        return;770    }771772    let (cc, cxx) = match builder.config.llvm_clang_cl {773        Some(ref cl) => (cl.into(), cl.into()),774        None => (builder.cc(target), builder.cxx(target).unwrap()),775    };776777    // If ccache is configured we inform the build a little differently how778    // to invoke ccache while also invoking our compilers.779    if use_compiler_launcher && let Some(ref ccache) = builder.config.ccache {780        cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)781            .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);782    }783    cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))784        .define("CMAKE_CXX_COMPILER", sanitize_cc(&cxx))785        .define("CMAKE_ASM_COMPILER", sanitize_cc(&cc));786787    // If we are running under a FIFO jobserver, we should not pass -j to CMake; otherwise it788    // overrides the jobserver settings and can lead to oversubscription.789    let has_modern_jobserver = env::var("MAKEFLAGS")790        .map(|flags| flags.contains("--jobserver-auth=fifo:"))791        .unwrap_or(false);792793    if !has_modern_jobserver {794        cfg.build_arg("-j").build_arg(builder.jobs().to_string());795    }796    let mut cflags = ccflags.cflags.clone();797    // FIXME(madsmtm): Allow `cmake-rs` to select flags by itself by passing798    // our flags via `.cflag`/`.cxxflag` instead.799    //800    // Needs `suppressed_compiler_flag_prefixes` to be gone, and hence801    // https://github.com/llvm/llvm-project/issues/88780 to be fixed.802    for flag in builder803        .cc_handled_clags(target, CLang::C)804        .into_iter()805        .chain(builder.cc_unhandled_cflags(target, GitRepo::Llvm, CLang::C))806        .filter(|flag| !suppressed_compiler_flag_prefixes.iter().any(|p| flag.starts_with(p)))807    {808        cflags.push(" ");809        cflags.push(flag);810    }811    if let Some(ref s) = builder.config.llvm_cflags {812        cflags.push(" ");813        cflags.push(s);814    }815    if target.contains("ohos") {816        cflags.push(" -D_LINUX_SYSINFO_H");817    }818    if builder.config.llvm_clang_cl.is_some() {819        cflags.push(format!(" --target={target}"));820    }821    cfg.define("CMAKE_C_FLAGS", cflags);822    let mut cxxflags = ccflags.cxxflags.clone();823    for flag in builder824        .cc_handled_clags(target, CLang::Cxx)825        .into_iter()826        .chain(builder.cc_unhandled_cflags(target, GitRepo::Llvm, CLang::Cxx))827        .filter(|flag| {828            !suppressed_compiler_flag_prefixes829                .iter()830                .any(|suppressed_prefix| flag.starts_with(suppressed_prefix))831        })832    {833        cxxflags.push(" ");834        cxxflags.push(flag);835    }836    if let Some(ref s) = builder.config.llvm_cxxflags {837        cxxflags.push(" ");838        cxxflags.push(s);839    }840    if target.contains("ohos") {841        cxxflags.push(" -D_LINUX_SYSINFO_H");842    }843    if builder.config.llvm_clang_cl.is_some() {844        cxxflags.push(format!(" --target={target}"));845    }846847    cfg.define("CMAKE_CXX_FLAGS", cxxflags);848    if let Some(ar) = builder.ar(target)849        && ar.is_absolute()850    {851        // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it852        // tries to resolve this path in the LLVM build directory.853        cfg.define("CMAKE_AR", sanitize_cc(&ar));854    }855856    if let Some(ranlib) = builder.ranlib(target)857        && ranlib.is_absolute()858    {859        // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it860        // tries to resolve this path in the LLVM build directory.861        cfg.define("CMAKE_RANLIB", sanitize_cc(&ranlib));862    }863864    if let Some(ref flags) = builder.config.llvm_ldflags {865        ldflags.push_all(flags);866    }867868    if let Some(flags) = get_var("LDFLAGS", &builder.config.host_target.triple, &target.triple) {869        ldflags.push_all(&flags);870    }871872    // For distribution we want the LLVM tools to be *statically* linked to libstdc++.873    // We also do this if the user explicitly requested static libstdc++.874    if builder.config.llvm_static_stdcpp875        && !target.is_msvc()876        && !target.contains("netbsd")877        && !target.contains("solaris")878    {879        if target.contains("apple") || target.is_windows() {880            ldflags.push_all("-static-libstdc++");881        } else {882            ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");883        }884    }885886    cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);887    cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);888    cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);889890    if env::var_os("SCCACHE_ERROR_LOG").is_some() {891        cfg.env("RUSTC_LOG", "sccache=warn");892    }893}894895fn configure_llvm(builder: &Builder<'_>, target: TargetSelection, cfg: &mut cmake::Config) {896    // ThinLTO is only available when building with LLVM, enabling LLD is required.897    // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.898    if builder.config.llvm_thin_lto {899        cfg.define("LLVM_ENABLE_LTO", "Thin");900        if !target.contains("apple") {901            cfg.define("LLVM_ENABLE_LLD", "ON");902        }903    }904905    // Libraries for ELF section compression.906    if builder.config.llvm_libzstd {907        cfg.define("LLVM_ENABLE_ZSTD", "FORCE_ON");908        cfg.define("LLVM_USE_STATIC_ZSTD", "TRUE");909    } else {910        cfg.define("LLVM_ENABLE_ZSTD", "OFF");911    }912913    if let Some(ref linker) = builder.config.llvm_use_linker {914        cfg.define("LLVM_USE_LINKER", linker);915    }916917    if builder.config.llvm_allow_old_toolchain {918        cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");919    }920}921922// Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365923fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {924    let kind = if host == target { "HOST" } else { "TARGET" };925    let target_u = target.replace('-', "_");926    env::var_os(format!("{var_base}_{target}"))927        .or_else(|| env::var_os(format!("{var_base}_{target_u}")))928        .or_else(|| env::var_os(format!("{kind}_{var_base}")))929        .or_else(|| env::var_os(var_base))930}931932#[derive(Clone)]933pub struct BuiltOmpOffload {934    /// Path to the omp and offload dylibs.935    offload: Vec<PathBuf>,936}937938impl BuiltOmpOffload {939    pub fn offload_paths(&self) -> Vec<PathBuf> {940        self.offload.clone()941    }942}943944// FIXME(offload): In an ideal world, we would just enable the offload runtime in our previous LLVM945// build step. For now, we still depend on the openmp runtime since we use some of it's API, so we946// build both. However, when building those runtimes as part of the LLVM step, then LLVM's cmake947// implicitly assumes that Clang has also been build and will try to use it. In the Rust CI, we948// don't always build clang (due to compile times), but instead use a slightly older external clang.949// LLVM tries to remove this build dependency of offload/openmp on Clang for LLVM-22, so in the950// future we might be able to integrate this step into the LLVM step. For now, we instead introduce951// a Clang_DIR bootstrap option, which allows us tell CMake to use an external clang for these two952// runtimes. This external clang will try to use it's own (older) include dirs when building our953// in-tree LLVM submodule, which will cause build failures. To prevent those, we now also954// explicitly set our include dirs.955#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]956pub struct OmpOffload {957    pub target: TargetSelection,958}959960impl Step for OmpOffload {961    type Output = BuiltOmpOffload;962    const IS_HOST: bool = true;963964    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {965        run.path("src/llvm-project/offload")966    }967968    fn make_run(run: RunConfig<'_>) {969        run.builder.ensure(OmpOffload { target: run.target });970    }971972    /// Compile OpenMP offload runtimes for `target`.973    #[allow(unused)]974    fn run(self, builder: &Builder<'_>) -> Self::Output {975        if builder.config.dry_run() {976            return BuiltOmpOffload {977                offload: vec![builder.config.tempdir().join("llvm-offload-dry-run")],978            };979        }980        let target = self.target;981982        let LlvmResult { host_llvm_config, llvm_cmake_dir } =983            builder.ensure(Llvm { target: self.target });984985        // Running cmake twice in the same folder is known to cause issues, like deleting existing986        // binaries. We therefore write our offload artifacts into it's own folder, instead of987        // using the llvm build dir.988        let out_dir = builder.offload_out(target);989990        let mut files = vec![];991        let lib_ext = std::env::consts::DLL_EXTENSION;992        files.push(out_dir.join("lib").join("libLLVMOffload").with_extension(lib_ext));993        files.push(out_dir.join("lib").join("libomp").with_extension(lib_ext));994        files.push(out_dir.join("lib").join("libomptarget").with_extension(lib_ext));995996        // Offload/OpenMP are just subfolders of LLVM, so we can use the LLVM sha.997        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();998        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {999            generate_smart_stamp_hash(1000                builder,1001                &builder.config.src.join("src/llvm-project/offload"),1002                builder.in_tree_llvm_info.sha().unwrap_or_default(),1003            )1004        });1005        let stamp = BuildStamp::new(&out_dir).with_prefix("offload").add_stamp(smart_stamp_hash);10061007        trace!("checking build stamp to see if we need to rebuild offload/openmp artifacts");1008        if stamp.is_up_to_date() {1009            trace!(?out_dir, "offload/openmp build artifacts are up to date");1010            if stamp.stamp().is_empty() {1011                builder.info(1012                    "Could not determine the Offload submodule commit hash. \1013                     Assuming that an Offload rebuild is not necessary.",1014                );1015                builder.info(&format!(1016                    "To force Offload/OpenMP to rebuild, remove the file `{}`",1017                    stamp.path().display()1018                ));1019            }1020            return BuiltOmpOffload { offload: files };1021        }10221023        trace!(?target, "(re)building offload/openmp artifacts");1024        builder.info(&format!("Building OpenMP/Offload for {target}"));1025        t!(stamp.remove());1026        let _time = helpers::timeit(builder);1027        t!(fs::create_dir_all(&out_dir));10281029        builder.config.update_submodule("src/llvm-project");10301031        // OpenMP/Offload builds currently (LLVM-22) still depend on Clang, although there are1032        // intentions to loosen this requirement over time. FIXME(offload): re-evaluate on LLVM 231033        let clang_dir = if !builder.config.llvm_clang {1034            // We must have an external clang to use.1035            assert!(&builder.build.config.llvm_clang_dir.is_some());1036            builder.build.config.llvm_clang_dir.clone()1037        } else {1038            // No need to specify it, since we use the in-tree clang1039            None1040        };10411042        // In the context of OpenMP offload, some libraries must be compiled for the gpu target,1043        // some for the host, and others for both. We do not perform a full cross-compilation, since1044        // we don't want to run rustc on a GPU.1045        let omp_targets = vec![target.triple.as_ref(), "amdgcn-amd-amdhsa", "nvptx64-nvidia-cuda"];1046        for omp_target in omp_targets {1047            let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/runtimes/"));10481049            // If we use an external clang as opposed to building our own llvm_clang, than that clang will1050            // come with it's own set of default include directories, which are based on a potentially older1051            // LLVM. This can cause issues, so we overwrite it to include headers based on our1052            // `src/llvm-project` submodule instead.1053            // FIXME(offload): With LLVM-22 we hopefully won't need an external clang anymore.1054            let mut cflags = CcFlags::default();1055            if !builder.config.llvm_clang {1056                let base = builder.llvm_out(target).join("include");1057                let inc_dir = base.display();1058                cflags.push_all(format!(" -I {inc_dir}"));1059            }10601061            configure_cmake(builder, target, &mut cfg, true, LdFlags::default(), cflags, &[]);10621063            // Re-use the same flags as llvm to control the level of debug information1064            // generated for offload.1065            let profile =1066                match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {1067                    (false, _) => "Debug",1068                    (true, false) => "Release",1069                    (true, true) => "RelWithDebInfo",1070                };1071            trace!(?profile);10721073            // FIXME(offload): Once we move from OMP to Offload (Ol) APIs, we should drop the openmp1074            // runtime to simplify our build. So far, these are still under development.1075            cfg.out_dir(&out_dir)1076                .profile(profile)1077                .env("LLVM_CONFIG_REAL", &host_llvm_config)1078                .define("LLVM_ENABLE_ASSERTIONS", "ON")1079                .define("LLVM_INCLUDE_TESTS", "OFF")1080                .define("OFFLOAD_INCLUDE_TESTS", "OFF")1081                .define("LLVM_ROOT", builder.llvm_out(target).join("build"))1082                .define("LLVM_DIR", llvm_cmake_dir.clone())1083                .define("LLVM_DEFAULT_TARGET_TRIPLE", omp_target);1084            if let Some(p) = clang_dir.clone() {1085                cfg.define("Clang_DIR", p);1086            }10871088            // We don't perform a full cross-compilation of rustc, therefore our target.triple1089            // will still be a CPU target.1090            if *omp_target == *target.triple {1091                // The offload library provides functionality which only makes sense on the host.1092                cfg.define("LLVM_ENABLE_RUNTIMES", "openmp;offload");1093            } else {1094                // OpenMP provides some device libraries, so we also compile it for all gpu targets.1095                cfg.define("LLVM_USE_LINKER", "lld");1096                cfg.define("LLVM_ENABLE_RUNTIMES", "openmp");1097                cfg.define("CMAKE_C_COMPILER_TARGET", omp_target);1098                cfg.define("CMAKE_CXX_COMPILER_TARGET", omp_target);1099            }1100            cfg.build();1101        }11021103        t!(stamp.write());11041105        for p in &files {1106            // At this point, `out_dir` should contain the built <offload-filename>.<dylib-ext>1107            // files.1108            if !p.exists() {1109                eprintln!(1110                    "`{p:?}` not found in `{}`. Either the build has failed or Offload was built with a wrong version of LLVM",1111                    out_dir.display()1112                );1113                exit!(1);1114            }1115        }1116        BuiltOmpOffload { offload: files }1117    }1118}11191120#[derive(Clone)]1121pub struct BuiltEnzyme {1122    /// Path to the libEnzyme dylib.1123    enzyme: PathBuf,1124}11251126impl BuiltEnzyme {1127    pub fn enzyme_path(&self) -> PathBuf {1128        self.enzyme.clone()1129    }1130    pub fn enzyme_filename(&self) -> String {1131        self.enzyme.file_name().unwrap().to_str().unwrap().to_owned()1132    }1133}11341135#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]1136pub struct Enzyme {1137    pub target: TargetSelection,1138}11391140impl Step for Enzyme {1141    type Output = BuiltEnzyme;1142    const IS_HOST: bool = true;11431144    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {1145        run.path("src/tools/enzyme/enzyme")1146    }11471148    fn make_run(run: RunConfig<'_>) {1149        run.builder.ensure(Enzyme { target: run.target });1150    }11511152    /// Compile Enzyme for `target`.1153    fn run(self, builder: &Builder<'_>) -> Self::Output {1154        builder.require_submodule(1155            "src/tools/enzyme",1156            Some("The Enzyme sources are required for autodiff."),1157        );1158        let target = self.target;11591160        if builder.config.dry_run() {1161            return BuiltEnzyme { enzyme: builder.config.tempdir().join("enzyme-dryrun") };1162        }11631164        let LlvmResult { host_llvm_config, llvm_cmake_dir } = builder.ensure(Llvm { target });11651166        // Enzyme links against LLVM. If we update the LLVM submodule libLLVM might get a new1167        // version number, in which case Enzyme will now fail to find LLVM. By including the LLVM1168        // hash into the Enzyme hash we force a rebuild of Enzyme when updating LLVM.1169        let enzyme_hash_input = builder.in_tree_llvm_info.sha().unwrap_or_default().to_owned()1170            + builder.enzyme_info.sha().unwrap_or_default();11711172        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();1173        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {1174            generate_smart_stamp_hash(1175                builder,1176                &builder.config.src.join("src/tools/enzyme"),1177                &enzyme_hash_input,1178            )1179        });11801181        let out_dir = builder.enzyme_out(target);1182        let stamp = BuildStamp::new(&out_dir).with_prefix("enzyme").add_stamp(smart_stamp_hash);11831184        let llvm_version_major = llvm::get_llvm_version_major(builder, &host_llvm_config);1185        let lib_ext = std::env::consts::DLL_EXTENSION;1186        let libenzyme = format!("libEnzyme-{llvm_version_major}");1187        let build_dir = out_dir.join(libdir(target));1188        let dylib = build_dir.join(&libenzyme).with_extension(lib_ext);11891190        trace!("checking build stamp to see if we need to rebuild enzyme artifacts");1191        if stamp.is_up_to_date() {1192            trace!(?out_dir, "enzyme build artifacts are up to date");1193            if stamp.stamp().is_empty() {1194                builder.info(1195                    "Could not determine the Enzyme submodule commit hash. \1196                     Assuming that an Enzyme rebuild is not necessary.",1197                );1198                builder.info(&format!(1199                    "To force Enzyme to rebuild, remove the file `{}`",1200                    stamp.path().display()1201                ));1202            }1203            return BuiltEnzyme { enzyme: dylib };1204        }12051206        if !builder.config.dry_run() && !llvm_cmake_dir.is_dir() {1207            builder.info(&format!(1208                "WARNING: {} does not exist, Enzyme build will likely fail",1209                llvm_cmake_dir.display()1210            ));1211        }12121213        trace!(?target, "(re)building enzyme artifacts");1214        builder.info(&format!("Building Enzyme for {target}"));1215        t!(stamp.remove());1216        let _time = helpers::timeit(builder);1217        t!(fs::create_dir_all(&out_dir));12181219        let mut cfg = cmake::Config::new(builder.src.join("src/tools/enzyme/enzyme/"));1220        // Enzyme devs maintain upstream compatibility, but only fix deprecations when they are about1221        // to turn into a hard error. As such, Enzyme generates various warnings which could make it1222        // hard to spot more relevant issues.1223        let mut cflags = CcFlags::default();1224        cflags.push_all("-Wno-deprecated");12251226        // Logic copied from `configure_llvm`1227        // ThinLTO is only available when building with LLVM, enabling LLD is required.1228        // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.1229        let mut ldflags = LdFlags::default();1230        if builder.config.llvm_thin_lto && !target.contains("apple") {1231            ldflags.push_all("-fuse-ld=lld");1232        }12331234        configure_cmake(builder, target, &mut cfg, true, ldflags, cflags, &[]);12351236        // Re-use the same flags as llvm to control the level of debug information1237        // generated by Enzyme.1238        // FIXME(ZuseZ4): Find a nicer way to use Enzyme Debug builds.1239        let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {1240            (false, _) => "Debug",1241            (true, false) => "Release",1242            (true, true) => "RelWithDebInfo",1243        };1244        trace!(?profile);12451246        cfg.out_dir(&out_dir)1247            .profile(profile)1248            .env("LLVM_CONFIG_REAL", &host_llvm_config)1249            .define("LLVM_ENABLE_ASSERTIONS", "ON")1250            .define("ENZYME_EXTERNAL_SHARED_LIB", "ON")1251            .define("ENZYME_BC_LOADER", "OFF")1252            .define("LLVM_DIR", llvm_cmake_dir);12531254        cfg.build();12551256        // At this point, `out_dir` should contain the built libEnzyme-<LLVM-version>.<dylib-ext>1257        // file.1258        if !dylib.exists() {1259            eprintln!(1260                "`{libenzyme}` not found in `{}`. Either the build has failed or Enzyme was built with a wrong version of LLVM",1261                build_dir.display()1262            );1263            exit!(1);1264        }12651266        t!(stamp.write());1267        BuiltEnzyme { enzyme: dylib }1268    }1269}12701271#[derive(Debug, Clone, Hash, PartialEq, Eq)]1272pub struct Lld {1273    pub target: TargetSelection,1274}12751276impl Step for Lld {1277    type Output = PathBuf;1278    const IS_HOST: bool = true;12791280    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {1281        run.path("src/llvm-project/lld")1282    }12831284    fn make_run(run: RunConfig<'_>) {1285        run.builder.ensure(Lld { target: run.target });1286    }12871288    /// Compile LLD for `target`.1289    fn run(self, builder: &Builder<'_>) -> PathBuf {1290        if builder.config.dry_run() {1291            return PathBuf::from("lld-out-dir-test-gen");1292        }1293        let target = self.target;12941295        let LlvmResult { host_llvm_config, llvm_cmake_dir } = builder.ensure(Llvm { target });12961297        // The `dist` step packages LLD next to LLVM's binaries for download-ci-llvm. The root path1298        // we usually expect here is `./build/$triple/ci-llvm/`, with the binaries in its `bin`1299        // subfolder. We check if that's the case, and if LLD's binary already exists there next to1300        // `llvm-config`: if so, we can use it instead of building LLVM/LLD from source.1301        let ci_llvm_bin = host_llvm_config.parent().unwrap();1302        if ci_llvm_bin.is_dir() && ci_llvm_bin.file_name().unwrap() == "bin" {1303            let lld_path = ci_llvm_bin.join(exe("lld", target));1304            if lld_path.exists() {1305                // The following steps copying `lld` as `rust-lld` to the sysroot, expect it in the1306                // `bin` subfolder of this step's out dir.1307                return ci_llvm_bin.parent().unwrap().to_path_buf();1308            }1309        }13101311        let out_dir = builder.lld_out(target);13121313        let lld_stamp = BuildStamp::new(&out_dir).with_prefix("lld");1314        if lld_stamp.path().exists() {1315            return out_dir;1316        }13171318        let _guard = builder.msg_unstaged(Kind::Build, "LLD", target);1319        let _time = helpers::timeit(builder);1320        t!(fs::create_dir_all(&out_dir));13211322        let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));1323        let mut ldflags = LdFlags::default();13241325        // When building LLD as part of a build with instrumentation on windows, for example1326        // when doing PGO on CI, cmake or clang-cl don't automatically link clang's1327        // profiler runtime in. In that case, we need to manually ask cmake to do it, to avoid1328        // linking errors, much like LLVM's cmake setup does in that situation.1329        if builder.config.llvm_profile_generate1330            && target.is_msvc()1331            && let Some(clang_cl_path) = builder.config.llvm_clang_cl.as_ref()1332        {1333            // Find clang's runtime library directory and push that as a search path to the1334            // cmake linker flags.1335            let clang_rt_dir = get_clang_cl_resource_dir(builder, clang_cl_path);1336            ldflags.push_all(format!("/libpath:{}", clang_rt_dir.display()));1337        }13381339        // LLD is built as an LLVM tool, but is distributed outside of the `llvm-tools` component,1340        // which impacts where it expects to find LLVM's shared library. This causes #80703.1341        //1342        // LLD is distributed at "$root/lib/rustlib/$host/bin/rust-lld", but the `libLLVM-*.so` it1343        // needs is distributed at "$root/lib". The default rpath of "$ORIGIN/../lib" points at the1344        // lib path for LLVM tools, not the one for rust binaries.1345        //1346        // (The `llvm-tools` component copies the .so there for the other tools, and with that1347        // component installed, one can successfully invoke `rust-lld` directly without rustup's1348        // `LD_LIBRARY_PATH` overrides)1349        //1350        if builder.config.rpath_enabled(target)1351            && helpers::use_host_linker(target)1352            && builder.config.llvm_link_shared()1353            && target.contains("linux")1354        {1355            // So we inform LLD where it can find LLVM's libraries by adding an rpath entry to the1356            // expected parent `lib` directory.1357            //1358            // Be careful when changing this path, we need to ensure it's quoted or escaped:1359            // `$ORIGIN` would otherwise be expanded when the `LdFlags` are passed verbatim to1360            // cmake.1361            ldflags.push_all("-Wl,-rpath,'$ORIGIN/../../../'");1362        }13631364        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);1365        configure_llvm(builder, target, &mut cfg);13661367        // Re-use the same flags as llvm to control the level of debug information1368        // generated for lld.1369        let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {1370            (false, _) => "Debug",1371            (true, false) => "Release",1372            (true, true) => "RelWithDebInfo",1373        };13741375        cfg.out_dir(&out_dir)1376            .profile(profile)1377            .define("LLVM_CMAKE_DIR", llvm_cmake_dir)1378            .define("LLVM_INCLUDE_TESTS", "OFF");13791380        if !builder.config.is_host_target(target) {1381            // Use the host llvm-tblgen binary.1382            cfg.define(1383                "LLVM_TABLEGEN_EXE",1384                host_llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),1385            );1386        }13871388        cfg.build();13891390        t!(lld_stamp.write());1391        out_dir1392    }1393}13941395#[derive(Debug, Clone, PartialEq, Eq, Hash)]1396pub struct Sanitizers {1397    pub target: TargetSelection,1398}13991400impl Step for Sanitizers {1401    type Output = Vec<SanitizerRuntime>;14021403    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {1404        run.alias("sanitizers")1405    }14061407    fn make_run(run: RunConfig<'_>) {1408        run.builder.ensure(Sanitizers { target: run.target });1409    }14101411    /// Builds sanitizer runtime libraries.1412    fn run(self, builder: &Builder<'_>) -> Self::Output {1413        let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");1414        if !compiler_rt_dir.exists() {1415            return Vec::new();1416        }14171418        let out_dir = builder.native_dir(self.target).join("sanitizers");1419        let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);14201421        if builder.config.dry_run() || runtimes.is_empty() {1422            return runtimes;1423        }14241425        let LlvmResult { host_llvm_config, .. } =1426            builder.ensure(Llvm { target: builder.config.host_target });14271428        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();1429        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {1430            generate_smart_stamp_hash(1431                builder,1432                &builder.config.src.join("src/llvm-project/compiler-rt"),1433                builder.in_tree_llvm_info.sha().unwrap_or_default(),1434            )1435        });14361437        let stamp = BuildStamp::new(&out_dir).with_prefix("sanitizers").add_stamp(smart_stamp_hash);14381439        if stamp.is_up_to_date() {1440            if stamp.stamp().is_empty() {1441                builder.info(&format!(1442                    "Rebuild sanitizers by removing the file `{}`",1443                    stamp.path().display()1444                ));1445            }14461447            return runtimes;1448        }14491450        let _guard = builder.msg_unstaged(Kind::Build, "sanitizers", self.target);1451        t!(stamp.remove());1452        let _time = helpers::timeit(builder);14531454        let mut cfg = cmake::Config::new(&compiler_rt_dir);1455        cfg.profile("Release");1456        cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);1457        cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");1458        cfg.define("COMPILER_RT_BUILD_CRT", "OFF");1459        cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");1460        cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");1461        cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");1462        cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");1463        cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");1464        cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");1465        cfg.define("LLVM_CONFIG_PATH", &host_llvm_config);14661467        if self.target.contains("ohos") {1468            cfg.define("COMPILER_RT_USE_BUILTINS_LIBRARY", "ON");1469        }14701471        // On Darwin targets the sanitizer runtimes are build as universal binaries.1472        // Unfortunately sccache currently lacks support to build them successfully.1473        // Disable compiler launcher on Darwin targets to avoid potential issues.1474        let use_compiler_launcher = !self.target.contains("apple-darwin");1475        // Since v1.0.86, the cc crate adds -mmacosx-version-min to the default1476        // flags on MacOS. A long-standing bug in the CMake rules for compiler-rt1477        // causes architecture detection to be skipped when this flag is present,1478        // and compilation fails. https://github.com/llvm/llvm-project/issues/887801479        let suppressed_compiler_flag_prefixes: &[&str] =1480            if self.target.contains("apple-darwin") { &["-mmacosx-version-min="] } else { &[] };1481        configure_cmake(1482            builder,1483            self.target,1484            &mut cfg,1485            use_compiler_launcher,1486            LdFlags::default(),1487            CcFlags::default(),1488            suppressed_compiler_flag_prefixes,1489        );14901491        t!(fs::create_dir_all(&out_dir));1492        cfg.out_dir(out_dir);14931494        for runtime in &runtimes {1495            cfg.build_target(&runtime.cmake_target);1496            cfg.build();1497        }1498        t!(stamp.write());14991500        runtimes1501    }1502}15031504#[derive(Clone, Debug)]1505pub struct SanitizerRuntime {1506    /// CMake target used to build the runtime.1507    pub cmake_target: String,1508    /// Path to the built runtime library.1509    pub path: PathBuf,1510    /// Library filename that will be used rustc.1511    pub name: String,1512}15131514/// Returns sanitizers available on a given target.1515fn supported_sanitizers(1516    out_dir: &Path,1517    target: TargetSelection,1518    channel: &str,1519) -> Vec<SanitizerRuntime> {1520    let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {1521        components1522            .iter()1523            .map(move |c| SanitizerRuntime {1524                cmake_target: format!("clang_rt.{c}_{os}_dynamic"),1525                path: out_dir.join(format!("build/lib/darwin/libclang_rt.{c}_{os}_dynamic.dylib")),1526                name: format!("librustc-{channel}_rt.{c}.dylib"),1527            })1528            .collect()1529    };15301531    let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {1532        components1533            .iter()1534            .map(move |c| SanitizerRuntime {1535                cmake_target: format!("clang_rt.{c}-{arch}"),1536                path: out_dir.join(format!("build/lib/{os}/libclang_rt.{c}-{arch}.a")),1537                name: format!("librustc-{channel}_rt.{c}.a"),1538            })1539            .collect()1540    };15411542    match &*target.triple {1543        "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),1544        "aarch64-apple-ios" => darwin_libs("ios", &["asan", "tsan", "rtsan"]),1545        "aarch64-apple-ios-sim" => darwin_libs("iossim", &["asan", "tsan", "rtsan"]),1546        "aarch64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),1547        "aarch64-unknown-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),1548        "aarch64-unknown-linux-gnu" => {1549            common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan", "rtsan"])1550        }1551        "aarch64-unknown-linux-ohos" => {1552            common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])1553        }1554        "loongarch64-unknown-linux-gnu" | "loongarch64-unknown-linux-musl" => {1555            common_libs("linux", "loongarch64", &["asan", "lsan", "msan", "tsan"])1556        }1557        "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),1558        "x86_64-unknown-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),1559        "x86_64-apple-ios" => darwin_libs("iossim", &["asan", "tsan"]),1560        "x86_64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),1561        "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),1562        "x86_64-unknown-netbsd" => {1563            common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])1564        }1565        "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),1566        "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),1567        "x86_64-unknown-linux-gnu" => common_libs(1568            "linux",1569            "x86_64",1570            &["asan", "dfsan", "lsan", "msan", "safestack", "tsan", "rtsan"],1571        ),1572        "x86_64-unknown-linux-gnuasan" => common_libs("linux", "x86_64", &["asan"]),1573        "x86_64-unknown-linux-gnumsan" => common_libs("linux", "x86_64", &["msan"]),1574        "x86_64-unknown-linux-gnutsan" => common_libs("linux", "x86_64", &["tsan"]),1575        "x86_64-unknown-linux-musl" => {1576            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])1577        }1578        "s390x-unknown-linux-gnu" => {1579            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])1580        }1581        "s390x-unknown-linux-musl" => {1582            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])1583        }1584        "x86_64-unknown-linux-ohos" => {1585            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])1586        }1587        _ => Vec::new(),1588    }1589}15901591#[derive(Debug, Clone, PartialEq, Eq, Hash)]1592pub struct CrtBeginEnd {1593    pub target: TargetSelection,1594}15951596impl Step for CrtBeginEnd {1597    type Output = PathBuf;15981599    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {1600        run.path("src/llvm-project/compiler-rt/lib/crt")1601    }16021603    fn make_run(run: RunConfig<'_>) {1604        if run.target.needs_crt_begin_end() {1605            run.builder.ensure(CrtBeginEnd { target: run.target });1606        }1607    }16081609    /// Build crtbegin.o/crtend.o for musl target.1610    fn run(self, builder: &Builder<'_>) -> Self::Output {1611        builder.require_submodule(1612            "src/llvm-project",1613            Some("The LLVM sources are required for the CRT from `compiler-rt`."),1614        );16151616        let out_dir = builder.native_dir(self.target).join("crt");16171618        if builder.config.dry_run() {1619            return out_dir;1620        }16211622        let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtbegin.c");1623        let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtend.c");1624        if up_to_date(&crtbegin_src, &out_dir.join("crtbeginS.o"))1625            && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))1626        {1627            return out_dir;1628        }16291630        let _guard = builder.msg_unstaged(Kind::Build, "crtbegin.o and crtend.o", self.target);1631        t!(fs::create_dir_all(&out_dir));16321633        let mut cfg = cc::Build::new();16341635        if let Some(ar) = builder.ar(self.target) {1636            cfg.archiver(ar);1637        }1638        cfg.compiler(builder.cc(self.target));1639        cfg.cargo_metadata(false)1640            .out_dir(&out_dir)1641            .target(&self.target.triple)1642            .host(&builder.config.host_target.triple)1643            .warnings(false)1644            .debug(false)1645            .opt_level(3)1646            .file(crtbegin_src)1647            .file(crtend_src);16481649        // Those flags are defined in src/llvm-project/compiler-rt/lib/builtins/CMakeLists.txt1650        // Currently only consumer of those objects is musl, which use .init_array/.fini_array1651        // instead of .ctors/.dtors1652        cfg.flag("-std=c11")1653            .define("CRT_HAS_INITFINI_ARRAY", None)1654            .define("EH_USE_FRAME_REGISTRY", None);16551656        let objs = cfg.compile_intermediates();1657        assert_eq!(objs.len(), 2);1658        for obj in objs {1659            let base_name = unhashed_basename(&obj);1660            assert!(base_name == "crtbegin" || base_name == "crtend");1661            t!(fs::copy(&obj, out_dir.join(format!("{base_name}S.o"))));1662            t!(fs::rename(&obj, out_dir.join(format!("{base_name}.o"))));1663        }16641665        out_dir1666    }1667}16681669#[derive(Debug, Clone, PartialEq, Eq, Hash)]1670pub struct Libunwind {1671    pub target: TargetSelection,1672}16731674impl Step for Libunwind {1675    type Output = PathBuf;16761677    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {1678        run.path("src/llvm-project/libunwind")1679    }16801681    fn make_run(run: RunConfig<'_>) {1682        run.builder.ensure(Libunwind { target: run.target });1683    }16841685    /// Build libunwind.a1686    fn run(self, builder: &Builder<'_>) -> Self::Output {1687        builder.require_submodule(1688            "src/llvm-project",1689            Some("The LLVM sources are required for libunwind."),1690        );16911692        if builder.config.dry_run() {1693            return PathBuf::new();1694        }16951696        let out_dir = builder.native_dir(self.target).join("libunwind");1697        let root = builder.src.join("src/llvm-project/libunwind");16981699        if up_to_date(&root, &out_dir.join("libunwind.a")) {1700            return out_dir;1701        }17021703        let _guard = builder.msg_unstaged(Kind::Build, "libunwind.a", self.target);1704        t!(fs::create_dir_all(&out_dir));17051706        let mut cc_cfg = cc::Build::new();1707        let mut cpp_cfg = cc::Build::new();17081709        cpp_cfg.cpp(true);1710        cpp_cfg.cpp_set_stdlib(None);1711        cpp_cfg.flag("-nostdinc++");1712        cpp_cfg.flag("-fno-exceptions");1713        cpp_cfg.flag("-fno-rtti");1714        cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");17151716        for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {1717            if let Some(ar) = builder.ar(self.target) {1718                cfg.archiver(ar);1719            }1720            cfg.target(&self.target.triple);1721            cfg.host(&builder.config.host_target.triple);1722            cfg.warnings(false);1723            cfg.debug(false);1724            // get_compiler() need set opt_level first.1725            cfg.opt_level(3);1726            cfg.flag("-fstrict-aliasing");1727            cfg.flag("-funwind-tables");1728            cfg.flag("-fvisibility=hidden");1729            cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);1730            cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");1731            cfg.include(root.join("include"));1732            cfg.cargo_metadata(false);1733            cfg.out_dir(&out_dir);17341735            if self.target.contains("x86_64-fortanix-unknown-sgx") {1736                cfg.static_flag(true);1737                cfg.flag("-fno-stack-protector");1738                cfg.flag("-ffreestanding");1739                cfg.flag("-fexceptions");17401741                // easiest way to undefine since no API available in cc::Build to undefine1742                cfg.flag("-U_FORTIFY_SOURCE");1743                cfg.define("_FORTIFY_SOURCE", "0");1744                cfg.define("RUST_SGX", "1");1745                cfg.define("__NO_STRING_INLINES", None);1746                cfg.define("__NO_MATH_INLINES", None);1747                cfg.define("_LIBUNWIND_IS_BAREMETAL", None);1748                cfg.define("NDEBUG", None);1749            }1750            if self.target.is_windows() {1751                cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");1752            }1753        }17541755        cc_cfg.compiler(builder.cc(self.target));1756        if let Ok(cxx) = builder.cxx(self.target) {1757            cpp_cfg.compiler(cxx);1758        } else {1759            cc_cfg.compiler(builder.cc(self.target));1760        }17611762        // Don't set this for clang1763        // By default, Clang builds C code in GNU C17 mode.1764        // By default, Clang builds C++ code according to the C++98 standard,1765        // with many C++11 features accepted as extensions.1766        if cc_cfg.get_compiler().is_like_gnu() {1767            cc_cfg.flag("-std=c99");1768        }1769        if cpp_cfg.get_compiler().is_like_gnu() {1770            cpp_cfg.flag("-std=c++11");1771        }17721773        if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {1774            // use the same GCC C compiler command to compile C++ code so we do not need to setup the1775            // C++ compiler env variables on the builders.1776            // Don't set this for clang++, as clang++ is able to compile this without libc++.1777            if cpp_cfg.get_compiler().is_like_gnu() {1778                cpp_cfg.cpp(false);1779                cpp_cfg.compiler(builder.cc(self.target));1780            }1781        }17821783        let mut c_sources = vec![1784            "Unwind-sjlj.c",1785            "UnwindLevel1-gcc-ext.c",1786            "UnwindLevel1.c",1787            "UnwindRegistersRestore.S",1788            "UnwindRegistersSave.S",1789        ];17901791        let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];1792        let cpp_len = cpp_sources.len();17931794        if self.target.contains("x86_64-fortanix-unknown-sgx") {1795            c_sources.push("UnwindRustSgx.c");1796        }17971798        for src in c_sources {1799            cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());1800        }18011802        for src in &cpp_sources {1803            cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());1804        }18051806        cpp_cfg.compile("unwind-cpp");18071808        // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-6792428451809        let mut count = 0;1810        let mut files = fs::read_dir(&out_dir)1811            .unwrap()1812            .map(|entry| entry.unwrap().path().canonicalize().unwrap())1813            .collect::<Vec<_>>();1814        files.sort();1815        for file in files {1816            if file.is_file() && file.extension() == Some(OsStr::new("o")) {1817                // Object file name without the hash prefix is "Unwind-EHABI", "Unwind-seh" or "libunwind".1818                let base_name = unhashed_basename(&file);1819                if cpp_sources.iter().any(|f| *base_name == f[..f.len() - 4]) {1820                    cc_cfg.object(&file);1821                    count += 1;1822                }1823            }1824        }1825        assert_eq!(cpp_len, count, "Can't get object files from {out_dir:?}");18261827        cc_cfg.compile("unwind");1828        out_dir1829    }1830}

Code quality findings 34

Warning: '.unwrap()' will panic on None/Err variants. Prefer using pattern matching (match, if let), combinators (map, and_then), or the '?' operator for robust error handling.
warning correctness unwrap-usage
let idx = target.triple.find('-').unwrap();
Warning: Direct indexing (e.g., `vec[i]`, `slice[i]`) panics on out-of-bounds access. Prefer using `.get(index)` or `.get_mut(index)` which return Option<&T>/Option<&mut T>.
warning correctness unchecked-indexing
format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
Warning: '.unwrap()' will panic on None/Err variants. Prefer using pattern matching (match, if let), combinators (map, and_then), or the '?' operator for robust error handling.
warning correctness unwrap-usage
.define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
Warning: '.expect()' will panic with a custom message on None/Err. While better than unwrap() for debugging, prefer non-panicking error handling in production code (match, if let, ?).
warning correctness expect-usage
let major_str = version.split_once('.').expect("Failed to parse LLVM version").0;
Warning: '.unwrap()' will panic on None/Err variants. Prefer using pattern matching (match, if let), combinators (map, and_then), or the '?' operator for robust error handling.
warning correctness unwrap-usage
major_str.parse().unwrap()
Warning: '.unwrap()' will panic on None/Err variants. Prefer using pattern matching (match, if let), combinators (map, and_then), or the '?' operator for robust error handling.
warning correctness unwrap-usage
cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
Warning: '.unwrap()' will panic on None/Err variants. Prefer using pattern matching (match, if let), combinators (map, and_then), or the '?' operator for robust error handling.
warning correctness unwrap-usage
OsString::from(cc.to_str().unwrap().replace('\\', "/"))
Warning: '.unwrap()' will panic on None/Err variants. Prefer using pattern matching (match, if let), combinators (map, and_then), or the '?' operator for robust error handling.
warning correctness unwrap-usage
None => (builder.cc(target), builder.cxx(target).unwrap()),
Warning: '.unwrap()' will panic on None/Err variants. Prefer using pattern matching (match, if let), combinators (map, and_then), or the '?' operator for robust error handling.
warning correctness unwrap-usage
self.enzyme.file_name().unwrap().to_str().unwrap().to_owned()
Warning: '.unwrap()' will panic on None/Err variants. Prefer using pattern matching (match, if let), combinators (map, and_then), or the '?' operator for robust error handling.
warning correctness unwrap-usage
let ci_llvm_bin = host_llvm_config.parent().unwrap();
Warning: '.unwrap()' will panic on None/Err variants. Prefer using pattern matching (match, if let), combinators (map, and_then), or the '?' operator for robust error handling.
warning correctness unwrap-usage
if ci_llvm_bin.is_dir() && ci_llvm_bin.file_name().unwrap() == "bin" {
Warning: '.unwrap()' will panic on None/Err variants. Prefer using pattern matching (match, if let), combinators (map, and_then), or the '?' operator for robust error handling.
warning correctness unwrap-usage
return ci_llvm_bin.parent().unwrap().to_path_buf();
Warning: Direct indexing (e.g., `vec[i]`, `slice[i]`) panics on out-of-bounds access. Prefer using `.get(index)` or `.get_mut(index)` which return Option<&T>/Option<&mut T>.
warning correctness unchecked-indexing
for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
Warning: '.unwrap()' will panic on None/Err variants. Prefer using pattern matching (match, if let), combinators (map, and_then), or the '?' operator for robust error handling.
warning correctness unwrap-usage
cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
Warning: '.unwrap()' will panic on None/Err variants. Prefer using pattern matching (match, if let), combinators (map, and_then), or the '?' operator for robust error handling.
warning correctness unwrap-usage
cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
Warning: '.unwrap()' will panic on None/Err variants. Prefer using pattern matching (match, if let), combinators (map, and_then), or the '?' operator for robust error handling.
warning correctness unwrap-usage
.unwrap()
Warning: '.unwrap()' will panic on None/Err variants. Prefer using pattern matching (match, if let), combinators (map, and_then), or the '?' operator for robust error handling.
warning correctness unwrap-usage
.map(|entry| entry.unwrap().path().canonicalize().unwrap())
Warning: Direct indexing (e.g., `vec[i]`, `slice[i]`) panics on out-of-bounds access. Prefer using `.get(index)` or `.get_mut(index)` which return Option<&T>/Option<&mut T>.
warning correctness unchecked-indexing
if cpp_sources.iter().any(|f| *base_name == f[..f.len() - 4]) {
Info: This standard library function returns a Result. Ensure the Result is handled properly (e.g., using '?', match, if let) rather than potentially panicking with .unwrap() or .expect().
info correctness unhandled-result
let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
Performance Info: Calling .to_string() (especially on &str) allocates a new String. If done repeatedly in loops, consider alternatives like working with &str or using crates like `itoa`/`ryu` for number-to-string conversion.
info performance to-string-in-loop
cfg.build_arg("-j").build_arg(builder.jobs().to_string());
Performance Info: Frequent cloning, especially of Strings, Vecs, or other heap-allocated types inside loops, can be expensive. Consider using references/borrowing where possible.
info performance clone-in-loop
let mut cflags = ccflags.cflags.clone();
Performance Info: Calling .push() repeatedly inside a loop without prior capacity reservation can lead to multiple reallocations. Consider using `Vec::with_capacity(n)` or `vec.reserve(n)` if the approximate number of elements is known.
info performance push-without-reserve
cflags.push(" ");
Performance Info: Calling .push() repeatedly inside a loop without prior capacity reservation can lead to multiple reallocations. Consider using `Vec::with_capacity(n)` or `vec.reserve(n)` if the approximate number of elements is known.
info performance push-without-reserve
cflags.push(flag);
Performance Info: Calling .push() repeatedly inside a loop without prior capacity reservation can lead to multiple reallocations. Consider using `Vec::with_capacity(n)` or `vec.reserve(n)` if the approximate number of elements is known.
info performance push-without-reserve
cflags.push(" ");
Performance Info: Calling .push() repeatedly inside a loop without prior capacity reservation can lead to multiple reallocations. Consider using `Vec::with_capacity(n)` or `vec.reserve(n)` if the approximate number of elements is known.
info performance push-without-reserve
cflags.push(s);
Performance Info: Calling .push() repeatedly inside a loop without prior capacity reservation can lead to multiple reallocations. Consider using `Vec::with_capacity(n)` or `vec.reserve(n)` if the approximate number of elements is known.
info performance push-without-reserve
cflags.push(" -D_LINUX_SYSINFO_H");
Performance Info: Calling .push() repeatedly inside a loop without prior capacity reservation can lead to multiple reallocations. Consider using `Vec::with_capacity(n)` or `vec.reserve(n)` if the approximate number of elements is known.
info performance push-without-reserve
cflags.push(format!(" --target={target}"));
Performance Info: Frequent cloning, especially of Strings, Vecs, or other heap-allocated types inside loops, can be expensive. Consider using references/borrowing where possible.
info performance clone-in-loop
let mut cxxflags = ccflags.cxxflags.clone();
Performance Info: Calling .push() repeatedly inside a loop without prior capacity reservation can lead to multiple reallocations. Consider using `Vec::with_capacity(n)` or `vec.reserve(n)` if the approximate number of elements is known.
info performance push-without-reserve
cxxflags.push(" ");
Info: Usage of `#[allow(...)]` suppresses compiler lints. Ensure the allowance is justified, well-scoped, and ideally temporary. Overuse can hide potential issues.
info maintainability allow-lint
#[allow(unused)]
Performance Info: Frequent cloning, especially of Strings, Vecs, or other heap-allocated types inside loops, can be expensive. Consider using references/borrowing where possible.
info performance clone-in-loop
builder.build.config.llvm_clang_dir.clone()
Info: Direct printing to stdout/stderr. For application logging, prefer using a logging facade like `log` or `tracing` for better control over levels, formatting, and output destinations.
info maintainability println-macro
eprintln!(
Info: Direct printing to stdout/stderr. For application logging, prefer using a logging facade like `log` or `tracing` for better control over levels, formatting, and output destinations.
info maintainability println-macro
eprintln!(
Performance Info: Calling .push() repeatedly inside a loop without prior capacity reservation can lead to multiple reallocations. Consider using `Vec::with_capacity(n)` or `vec.reserve(n)` if the approximate number of elements is known.
info performance push-without-reserve
c_sources.push("UnwindRustSgx.c");

Security findings 1

Security Info: Reading environment variables. Treat them as untrusted input; validate or sanitize values before use, especially if controlling paths, commands, or network addresses.
security env-var-untrusted
if let Ok(llvm_profile_dir) = std::env::var("LLVM_PROFILE_DIR") {

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.