Skip to main content

bootstrap/core/build_steps/
llvm.rs

1//! Compilation of native dependencies like LLVM.
2//!
3//! Native projects like LLVM unfortunately aren't suited just yet for
4//! compilation in build scripts that Cargo has. This is because the
5//! compilation takes a *very* long time but also because we don't want to
6//! 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 to
9//! ensure that they're always in place if needed.
10
11use std::env::consts::EXE_EXTENSION;
12use std::ffi::{OsStr, OsString};
13use std::path::{Path, PathBuf};
14use std::sync::OnceLock;
15use std::{env, fs};
16
17use build_helper::git::PathFreshness;
18
19use crate::core::build_steps::llvm;
20use crate::core::builder::{Builder, RunConfig, ShouldRun, Step, StepMetadata};
21use crate::core::config::{Config, LlvmPgoGenerationMode, TargetSelection};
22use crate::utils::build_stamp::{BuildStamp, generate_smart_stamp_hash};
23use crate::utils::exec::command;
24use crate::utils::helpers::{
25    self, exe, get_clang_cl_resource_dir, libdir, t, unhashed_basename, up_to_date,
26};
27use crate::{CLang, GitRepo, Kind, exit, trace};
28
29#[derive(Clone)]
30pub struct LlvmResult {
31    /// Path to llvm-config binary.
32    /// NB: This is always the host llvm-config!
33    pub host_llvm_config: PathBuf,
34    /// Path to LLVM cmake directory for the target.
35    pub llvm_cmake_dir: PathBuf,
36}
37
38pub struct Meta {
39    stamp: BuildStamp,
40    res: LlvmResult,
41    out_dir: PathBuf,
42    root: String,
43}
44
45pub enum LlvmBuildStatus {
46    AlreadyBuilt(LlvmResult),
47    ShouldBuild(Meta),
48}
49
50impl LlvmBuildStatus {
51    pub fn should_build(&self) -> bool {
52        match self {
53            LlvmBuildStatus::AlreadyBuilt(_) => false,
54            LlvmBuildStatus::ShouldBuild(_) => true,
55        }
56    }
57
58    #[cfg(test)]
59    pub fn llvm_result(&self) -> &LlvmResult {
60        match self {
61            LlvmBuildStatus::AlreadyBuilt(res) => res,
62            LlvmBuildStatus::ShouldBuild(meta) => &meta.res,
63        }
64    }
65}
66
67/// Allows each step to add C/Cxx flags which are only used for a specific cmake invocation.
68#[derive(Debug, Clone, Default)]
69struct CcFlags {
70    /// Additional values for CMAKE_CC_FLAGS, to be added before all other values.
71    cflags: OsString,
72    /// Additional values for CMAKE_CXX_FLAGS, to be added before all other values.
73    cxxflags: OsString,
74}
75
76impl CcFlags {
77    fn push_all(&mut self, s: impl AsRef<OsStr>) {
78        let s = s.as_ref();
79        self.cflags.push(" ");
80        self.cflags.push(s);
81        self.cxxflags.push(" ");
82        self.cxxflags.push(s);
83    }
84}
85
86/// Linker flags to pass to LLVM's CMake invocation.
87#[derive(Debug, Clone, Default)]
88struct LdFlags {
89    /// CMAKE_EXE_LINKER_FLAGS
90    exe: OsString,
91    /// CMAKE_SHARED_LINKER_FLAGS
92    shared: OsString,
93    /// CMAKE_MODULE_LINKER_FLAGS
94    module: OsString,
95}
96
97impl LdFlags {
98    fn push_all(&mut self, s: impl AsRef<OsStr>) {
99        let s = s.as_ref();
100        self.exe.push(" ");
101        self.exe.push(s);
102        self.shared.push(" ");
103        self.shared.push(s);
104        self.module.push(" ");
105        self.module.push(s);
106    }
107}
108
109/// This returns whether we've already previously built LLVM.
110///
111/// It's used to avoid busting caches during x.py check -- if we've already built
112/// LLVM, it's fine for us to not try to avoid doing so.
113///
114/// This will return the llvm-config if it can get it (but it will not build it
115/// if not).
116pub fn prebuilt_llvm_config(
117    builder: &Builder<'_>,
118    target: TargetSelection,
119    // Certain commands (like `x test mir-opt --bless`) may call this function with different targets,
120    // which could bypass the CI LLVM early-return even if `builder.config.llvm_from_ci` is true.
121    // This flag should be `true` only if the caller needs the LLVM sources (e.g., if it will build LLVM).
122    handle_submodule_when_needed: bool,
123) -> LlvmBuildStatus {
124    builder.config.maybe_download_ci_llvm();
125
126    // If we're using a custom LLVM bail out here, but we can only use a
127    // custom LLVM for the build triple.
128    if let Some(config) = builder.config.target_config.get(&target)
129        && let Some(ref s) = config.llvm_config
130    {
131        check_llvm_version(builder, s);
132        let host_llvm_config = s.to_path_buf();
133        let mut llvm_cmake_dir = host_llvm_config.clone();
134        llvm_cmake_dir.pop();
135        llvm_cmake_dir.pop();
136        llvm_cmake_dir.push("lib");
137        llvm_cmake_dir.push("cmake");
138        llvm_cmake_dir.push("llvm");
139        return LlvmBuildStatus::AlreadyBuilt(LlvmResult { host_llvm_config, llvm_cmake_dir });
140    }
141
142    if handle_submodule_when_needed {
143        // If submodules are disabled, this does nothing.
144        builder.config.update_submodule("src/llvm-project");
145    }
146
147    let root = "src/llvm-project/llvm";
148    let out_dir = builder.llvm_out(target);
149
150    let build_llvm_config = if let Some(build_llvm_config) = builder
151        .config
152        .target_config
153        .get(&builder.config.host_target)
154        .and_then(|config| config.llvm_config.clone())
155    {
156        build_llvm_config
157    } else {
158        let mut llvm_config_ret_dir = builder.llvm_out(builder.config.host_target);
159        llvm_config_ret_dir.push("bin");
160        llvm_config_ret_dir.join(exe("llvm-config", builder.config.host_target))
161    };
162
163    let llvm_cmake_dir = out_dir.join("lib/cmake/llvm");
164    let res = LlvmResult { host_llvm_config: build_llvm_config, llvm_cmake_dir };
165
166    static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
167    let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
168        generate_smart_stamp_hash(
169            builder,
170            &builder.config.src.join("src/llvm-project"),
171            builder.in_tree_llvm_info.sha().unwrap_or_default(),
172        )
173    });
174
175    let stamp = BuildStamp::new(&out_dir).with_prefix("llvm").add_stamp(smart_stamp_hash);
176
177    if stamp.is_up_to_date() {
178        if stamp.stamp().is_empty() {
179            builder.info(
180                "Could not determine the LLVM submodule commit hash. \
181                     Assuming that an LLVM rebuild is not necessary.",
182            );
183            builder.info(&format!(
184                "To force LLVM to rebuild, remove the file `{}`",
185                stamp.path().display()
186            ));
187        }
188        return LlvmBuildStatus::AlreadyBuilt(res);
189    }
190
191    LlvmBuildStatus::ShouldBuild(Meta { stamp, res, out_dir, root: root.into() })
192}
193
194/// Paths whose changes invalidate LLVM downloads.
195pub const LLVM_INVALIDATION_PATHS: &[&str] = &[
196    "src/llvm-project",
197    "src/bootstrap/download-ci-llvm-stamp",
198    // the LLVM shared object file is named `LLVM-<LLVM-version>-rust-{version}-nightly`
199    "src/version",
200];
201
202/// Detect whether LLVM sources have been modified locally or not.
203pub(crate) fn detect_llvm_freshness(config: &Config, is_git: bool) -> PathFreshness {
204    assert!(cfg!(not(test)), "unit tests shouldn't care about LLVM freshness");
205
206    if is_git {
207        config.check_path_modifications(LLVM_INVALIDATION_PATHS)
208    } else if let Some(info) = crate::utils::channel::read_commit_info_file(&config.src) {
209        PathFreshness::LastModifiedUpstream { upstream: info.sha.trim().to_owned() }
210    } else {
211        PathFreshness::MissingUpstream
212    }
213}
214
215/// Returns whether the CI-found LLVM is currently usable.
216///
217/// This checks the build triple platform to confirm we're usable at all, and if LLVM
218/// with/without assertions is available.
219pub(crate) fn is_ci_llvm_available_for_target(
220    host_target: &TargetSelection,
221    asserts: bool,
222) -> bool {
223    // This is currently all tier 1 targets and tier 2 targets with host tools
224    // (since others may not have CI artifacts)
225    // https://doc.rust-lang.org/rustc/platform-support.html#tier-1
226    let supported_platforms = [
227        // tier 1
228        ("aarch64-unknown-linux-gnu", false),
229        ("aarch64-apple-darwin", false),
230        ("aarch64-pc-windows-msvc", false),
231        ("i686-pc-windows-msvc", false),
232        ("i686-unknown-linux-gnu", false),
233        ("x86_64-unknown-linux-gnu", true),
234        ("x86_64-apple-darwin", true),
235        ("x86_64-pc-windows-gnu", false),
236        ("x86_64-pc-windows-msvc", true),
237        // tier 2 with host tools
238        ("aarch64-unknown-linux-musl", false),
239        ("aarch64-pc-windows-gnullvm", false),
240        ("arm-unknown-linux-gnueabi", false),
241        ("arm-unknown-linux-gnueabihf", false),
242        ("armv7-unknown-linux-gnueabihf", false),
243        ("i686-pc-windows-gnu", false),
244        ("loongarch64-unknown-linux-gnu", false),
245        ("loongarch64-unknown-linux-musl", false),
246        ("powerpc-unknown-linux-gnu", false),
247        ("powerpc64-unknown-linux-gnu", false),
248        ("powerpc64-unknown-linux-musl", false),
249        ("powerpc64le-unknown-linux-gnu", false),
250        ("powerpc64le-unknown-linux-musl", false),
251        ("riscv64gc-unknown-linux-gnu", false),
252        ("s390x-unknown-linux-gnu", false),
253        ("x86_64-pc-windows-gnullvm", false),
254        ("x86_64-unknown-freebsd", false),
255        ("x86_64-unknown-illumos", false),
256        ("x86_64-unknown-linux-musl", false),
257        ("x86_64-unknown-netbsd", false),
258    ];
259
260    if !supported_platforms.contains(&(&*host_target.triple, asserts))
261        && (asserts || !supported_platforms.contains(&(&*host_target.triple, true)))
262    {
263        return false;
264    }
265
266    true
267}
268
269#[derive(Debug, Clone, Hash, PartialEq, Eq)]
270pub struct Llvm {
271    pub target: TargetSelection,
272}
273
274impl Step for Llvm {
275    type Output = LlvmResult;
276
277    const IS_HOST: bool = true;
278
279    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
280        run.path("src/llvm-project").path("src/llvm-project/llvm")
281    }
282
283    fn make_run(run: RunConfig<'_>) {
284        run.builder.ensure(Llvm { target: run.target });
285    }
286
287    /// Compile LLVM for `target`.
288    fn run(self, builder: &Builder<'_>) -> LlvmResult {
289        let target = self.target;
290        let target_native = if self.target.starts_with("riscv") {
291            // RISC-V target triples in Rust is not named the same as C compiler target triples.
292            // This converts Rust RISC-V target triples to C compiler triples.
293            let idx = target.triple.find('-').unwrap();
294
295            format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
296        } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
297            // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
298            // Set the version suffix to 13.0 so the correct target details are used.
299            format!("{}{}", self.target, "13.0")
300        } else {
301            target.to_string()
302        };
303
304        // If LLVM has already been built or been downloaded through download-ci-llvm, we avoid building it again.
305        let Meta { stamp, res, out_dir, root } = match prebuilt_llvm_config(builder, target, true) {
306            LlvmBuildStatus::AlreadyBuilt(p) => return p,
307            LlvmBuildStatus::ShouldBuild(m) => m,
308        };
309
310        if builder.llvm_link_shared() && target.is_windows() && !target.is_windows_gnullvm() {
311            panic!("shared linking to LLVM is not currently supported on {}", target.triple);
312        }
313
314        let _guard = builder.msg_unstaged(Kind::Build, "LLVM", target);
315        t!(stamp.remove());
316        let _time = helpers::timeit(builder);
317        t!(fs::create_dir_all(&out_dir));
318
319        // https://llvm.org/docs/CMake.html
320        let mut cfg = cmake::Config::new(builder.src.join(root));
321        let mut ldflags = LdFlags::default();
322
323        let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
324            (false, _) => "Debug",
325            (true, false) => "Release",
326            (true, true) => "RelWithDebInfo",
327        };
328
329        // NOTE: remember to also update `bootstrap.example.toml` when changing the
330        // defaults!
331        let llvm_targets = match &builder.config.llvm_targets {
332            Some(s) => s,
333            None => {
334                "AArch64;AMDGPU;ARM;BPF;Hexagon;LoongArch;MSP430;Mips;NVPTX;PowerPC;RISCV;\
335                     Sparc;SystemZ;WebAssembly;X86"
336            }
337        };
338
339        let llvm_exp_targets = match builder.config.llvm_experimental_targets {
340            Some(ref s) => s,
341            None => "AVR;M68k;CSKY;Xtensa",
342        };
343
344        let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
345        let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
346        let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
347        let enable_warnings = if builder.config.llvm_enable_warnings { "ON" } else { "OFF" };
348
349        cfg.out_dir(&out_dir)
350            .profile(profile)
351            .define("LLVM_ENABLE_ASSERTIONS", assertions)
352            .define("LLVM_UNREACHABLE_OPTIMIZE", "OFF")
353            .define("LLVM_ENABLE_PLUGINS", plugins)
354            .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
355            .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
356            .define("LLVM_INCLUDE_EXAMPLES", "OFF")
357            .define("LLVM_INCLUDE_DOCS", "OFF")
358            .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
359            .define("LLVM_INCLUDE_TESTS", enable_tests)
360            .define("LLVM_ENABLE_LIBEDIT", "OFF")
361            .define("LLVM_ENABLE_BINDINGS", "OFF")
362            .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
363            .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
364            .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
365            .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native)
366            .define("LLVM_ENABLE_WARNINGS", enable_warnings);
367
368        // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
369        // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
370        // This flag makes sure `FileCheck` is copied in the final binaries directory.
371        cfg.define("LLVM_INSTALL_UTILS", "ON");
372
373        if let Some(mode) = builder.config.llvm_pgo.generate_profile.as_ref() {
374            cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
375            match mode {
376                LlvmPgoGenerationMode::Implicit => {}
377                LlvmPgoGenerationMode::Directory(llvm_profile_dir) => {
378                    cfg.define("LLVM_PROFILE_DATA_DIR", llvm_profile_dir);
379                }
380            }
381            cfg.define("LLVM_BUILD_RUNTIME", "No");
382        }
383        if let Some(path) = builder.config.llvm_pgo.use_profile.as_ref() {
384            cfg.define("LLVM_PROFDATA_FILE", path);
385        }
386
387        // Libraries for ELF section compression and profraw files merging.
388        if !target.is_msvc() {
389            cfg.define("LLVM_ENABLE_ZLIB", "ON");
390        } else {
391            cfg.define("LLVM_ENABLE_ZLIB", "OFF");
392        }
393
394        // Are we compiling for iOS/tvOS/watchOS/visionOS?
395        if target.contains("apple-ios")
396            || target.contains("apple-tvos")
397            || target.contains("apple-watchos")
398            || target.contains("apple-visionos")
399        {
400            // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
401            cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
402            // Zlib fails to link properly, leading to a compiler error.
403            cfg.define("LLVM_ENABLE_ZLIB", "OFF");
404        }
405
406        // This setting makes the LLVM tools link to the dynamic LLVM library,
407        // which saves both memory during parallel links and overall disk space
408        // for the tools. We don't do this on every platform as it doesn't work
409        // equally well everywhere.
410        if builder.llvm_link_shared() {
411            cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
412        }
413
414        if (target.starts_with("csky")
415            || target.starts_with("riscv")
416            || target.starts_with("sparc-"))
417            && !target.contains("freebsd")
418            && !target.contains("openbsd")
419            && !target.contains("netbsd")
420        {
421            // CSKY and RISC-V GCC erroneously requires linking against
422            // `libatomic` when using 1-byte and 2-byte C++
423            // atomics but the LLVM build system check cannot
424            // detect this. Therefore it is set manually here.
425            // Some BSD uses Clang as its system compiler and
426            // provides no libatomic in its base system so does
427            // not want this. 32-bit SPARC requires linking against
428            // libatomic as well.
429            ldflags.exe.push(" -latomic");
430            ldflags.shared.push(" -latomic");
431        }
432
433        if target.starts_with("mips") && target.contains("netbsd") {
434            // LLVM wants 64-bit atomics, while mipsel is 32-bit only, so needs -latomic
435            ldflags.exe.push(" -latomic");
436            ldflags.shared.push(" -latomic");
437        }
438
439        if target.starts_with("arm64ec") {
440            // MSVC linker requires the -machine:arm64ec flag to be passed to
441            // know it's linking as Arm64EC (vs Arm64X).
442            ldflags.exe.push(" -machine:arm64ec");
443            ldflags.shared.push(" -machine:arm64ec");
444        }
445
446        if target.is_msvc() {
447            cfg.define("CMAKE_MSVC_RUNTIME_LIBRARY", "MultiThreaded");
448            cfg.static_crt(true);
449        }
450
451        if target.starts_with("i686") {
452            cfg.define("LLVM_BUILD_32_BITS", "ON");
453        }
454
455        if target.starts_with("x86_64") && target.contains("ohos") {
456            cfg.define("LLVM_TOOL_LLVM_RTDYLD_BUILD", "OFF");
457        }
458
459        let mut enabled_llvm_projects = Vec::new();
460
461        if helpers::forcing_clang_based_tests() {
462            enabled_llvm_projects.push("clang");
463        }
464
465        if builder.config.llvm_polly {
466            enabled_llvm_projects.push("polly");
467        }
468
469        if builder.config.llvm_clang {
470            enabled_llvm_projects.push("clang");
471        }
472
473        // We want libxml to be disabled.
474        // See https://github.com/rust-lang/rust/pull/50104
475        cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
476
477        let mut enabled_llvm_runtimes = Vec::new();
478
479        if helpers::forcing_clang_based_tests() {
480            enabled_llvm_runtimes.push("compiler-rt");
481        }
482
483        if !enabled_llvm_projects.is_empty() {
484            enabled_llvm_projects.sort();
485            enabled_llvm_projects.dedup();
486            cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
487        }
488
489        if !enabled_llvm_runtimes.is_empty() {
490            enabled_llvm_runtimes.sort();
491            enabled_llvm_runtimes.dedup();
492            cfg.define("LLVM_ENABLE_RUNTIMES", enabled_llvm_runtimes.join(";"));
493        }
494
495        if let Some(num_linkers) = builder.config.llvm_link_jobs
496            && num_linkers > 0
497        {
498            cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
499        }
500
501        // https://llvm.org/docs/HowToCrossCompileLLVM.html
502        if !builder.config.is_host_target(target) {
503            let LlvmResult { host_llvm_config, .. } =
504                builder.ensure(Llvm { target: builder.config.host_target });
505            if !builder.config.dry_run() {
506                let llvm_bindir = command(&host_llvm_config)
507                    .arg("--bindir")
508                    .cached()
509                    .run_capture_stdout(builder)
510                    .stdout();
511                let host_bin = Path::new(llvm_bindir.trim());
512                cfg.define(
513                    "LLVM_TABLEGEN",
514                    host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION),
515                );
516                // LLVM_NM is required for cross compiling using MSVC
517                cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
518            }
519            cfg.define("LLVM_CONFIG_PATH", host_llvm_config);
520            if builder.config.llvm_clang {
521                let build_bin =
522                    builder.llvm_out(builder.config.host_target).join("build").join("bin");
523                let clang_tblgen = build_bin.join("clang-tblgen").with_extension(EXE_EXTENSION);
524                if !builder.config.dry_run() && !clang_tblgen.exists() {
525                    panic!("unable to find {}", clang_tblgen.display());
526                }
527                cfg.define("CLANG_TABLEGEN", clang_tblgen);
528            }
529        }
530
531        let llvm_version_suffix = if let Some(ref suffix) = builder.config.llvm_version_suffix {
532            // Allow version-suffix="" to not define a version suffix at all.
533            if !suffix.is_empty() { Some(suffix.to_string()) } else { None }
534        } else if builder.config.channel == "dev" {
535            // Changes to a version suffix require a complete rebuild of the LLVM.
536            // To avoid rebuilds during a time of version bump, don't include rustc
537            // release number on the dev channel.
538            Some("-rust-dev".to_string())
539        } else {
540            Some(format!("-rust-{}-{}", builder.version, builder.config.channel))
541        };
542        if let Some(ref suffix) = llvm_version_suffix {
543            cfg.define("LLVM_VERSION_SUFFIX", suffix);
544        }
545
546        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
547        configure_llvm(builder, target, &mut cfg);
548
549        for (key, val) in &builder.config.llvm_build_config {
550            cfg.define(key, val);
551        }
552
553        if builder.config.dry_run() {
554            return res;
555        }
556
557        cfg.build();
558
559        // Helper to find the name of LLVM's shared library on darwin and linux.
560        let find_llvm_lib_name = |extension| {
561            let major = get_llvm_version_major(builder, &res.host_llvm_config);
562            match &llvm_version_suffix {
563                Some(version_suffix) => format!("libLLVM-{major}{version_suffix}.{extension}"),
564                None => format!("libLLVM-{major}.{extension}"),
565            }
566        };
567
568        // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
569        // libLLVM.dylib will be built. However, llvm-config will still look
570        // for a versioned path like libLLVM-14.dylib. Manually create a symbolic
571        // link to make llvm-config happy.
572        if builder.llvm_link_shared() && target.contains("apple-darwin") {
573            let lib_name = find_llvm_lib_name("dylib");
574            let lib_llvm = out_dir.join("build").join("lib").join(lib_name);
575            if !lib_llvm.exists() {
576                t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));
577            }
578        }
579
580        // When building LLVM as a shared library on linux, it can contain unexpected debuginfo:
581        // some can come from the C++ standard library. Unless we're explicitly requesting LLVM to
582        // be built with debuginfo, strip it away after the fact, to make dist artifacts smaller.
583        if builder.llvm_link_shared()
584            && builder.config.llvm_optimize
585            && !builder.config.llvm_release_debuginfo
586        {
587            // Find the name of the LLVM shared library that we just built.
588            let lib_name = find_llvm_lib_name("so");
589
590            // If the shared library exists in LLVM's `/build/lib/` or `/lib/` folders, strip its
591            // debuginfo.
592            crate::core::build_steps::compile::strip_debug(
593                builder,
594                target,
595                &out_dir.join("lib").join(&lib_name),
596            );
597            crate::core::build_steps::compile::strip_debug(
598                builder,
599                target,
600                &out_dir.join("build").join("lib").join(&lib_name),
601            );
602        }
603
604        t!(stamp.write());
605
606        res
607    }
608
609    fn metadata(&self) -> Option<StepMetadata> {
610        Some(StepMetadata::build("llvm", self.target))
611    }
612}
613
614pub fn get_llvm_version(builder: &Builder<'_>, llvm_config: &Path) -> String {
615    command(llvm_config)
616        .arg("--version")
617        .cached()
618        .run_capture_stdout(builder)
619        .stdout()
620        .trim()
621        .to_owned()
622}
623
624pub fn get_llvm_version_major(builder: &Builder<'_>, llvm_config: &Path) -> u8 {
625    let version = get_llvm_version(builder, llvm_config);
626    let major_str = version.split_once('.').expect("Failed to parse LLVM version").0;
627    major_str.parse().unwrap()
628}
629
630fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
631    if builder.config.dry_run() {
632        return;
633    }
634
635    let version = get_llvm_version(builder, llvm_config);
636    let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
637    if let (Some(major), Some(_minor)) = (parts.next(), parts.next())
638        && major >= 21
639    {
640        return;
641    }
642    panic!("\n\nbad LLVM version: {version}, need >=21\n\n")
643}
644
645fn configure_cmake(
646    builder: &Builder<'_>,
647    target: TargetSelection,
648    cfg: &mut cmake::Config,
649    use_compiler_launcher: bool,
650    mut ldflags: LdFlags,
651    ccflags: CcFlags,
652    suppressed_compiler_flag_prefixes: &[&str],
653) {
654    // Do not print installation messages for up-to-date files.
655    // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
656    cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
657
658    if builder.config.quiet {
659        // Only log errors and warnings from `cmake`.
660        cfg.define("CMAKE_MESSAGE_LOG_LEVEL", "WARNING");
661
662        // If we're configuring llvm to build with `ninja`, we can suppress output from it with
663        // `--quiet`. Otherwise don't add anything since we don't know which build system is going
664        // to use.
665        if builder.ninja() {
666            cfg.build_arg("--quiet");
667        }
668    }
669
670    // Do not allow the user's value of DESTDIR to influence where
671    // LLVM will install itself. LLVM must always be installed in our
672    // own build directories.
673    cfg.env("DESTDIR", "");
674
675    if builder.ninja() {
676        cfg.generator("Ninja");
677    }
678    cfg.target(&target.triple).host(&builder.config.host_target.triple);
679
680    if !builder.config.is_host_target(target) {
681        cfg.define("CMAKE_CROSSCOMPILING", "True");
682
683        // NOTE: Ideally, we wouldn't have to do this, and `cmake-rs` would just handle it for us.
684        // But it currently determines this based on the `CARGO_CFG_TARGET_OS` environment variable,
685        // which isn't set when compiling outside `build.rs` (like bootstrap is).
686        //
687        // So for now, we define `CMAKE_SYSTEM_NAME` ourselves, to panicking in `cmake-rs`.
688        if target.contains("netbsd") {
689            cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
690        } else if target.contains("dragonfly") {
691            cfg.define("CMAKE_SYSTEM_NAME", "DragonFly");
692        } else if target.contains("openbsd") {
693            cfg.define("CMAKE_SYSTEM_NAME", "OpenBSD");
694        } else if target.contains("freebsd") {
695            cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
696        } else if target.is_windows() {
697            cfg.define("CMAKE_SYSTEM_NAME", "Windows");
698        } else if target.contains("haiku") {
699            cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
700        } else if target.contains("solaris") || target.contains("illumos") {
701            cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
702        } else if target.contains("linux") {
703            cfg.define("CMAKE_SYSTEM_NAME", "Linux");
704        } else if target.contains("darwin") {
705            // macOS
706            cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
707        } else if target.contains("ios") {
708            cfg.define("CMAKE_SYSTEM_NAME", "iOS");
709        } else if target.contains("tvos") {
710            cfg.define("CMAKE_SYSTEM_NAME", "tvOS");
711        } else if target.contains("visionos") {
712            cfg.define("CMAKE_SYSTEM_NAME", "visionOS");
713        } else if target.contains("watchos") {
714            cfg.define("CMAKE_SYSTEM_NAME", "watchOS");
715        } else if target.contains("none") {
716            // "none" should be the last branch
717            cfg.define("CMAKE_SYSTEM_NAME", "Generic");
718        } else {
719            builder.info(&format!(
720                "could not determine CMAKE_SYSTEM_NAME from the target `{target}`, build may fail",
721            ));
722            // Fallback, set `CMAKE_SYSTEM_NAME` anyhow to avoid the logic `cmake-rs` tries, and
723            // to avoid CMAKE_SYSTEM_NAME being inferred from the host.
724            cfg.define("CMAKE_SYSTEM_NAME", "Generic");
725        }
726
727        // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
728        // that case like CMake we cannot easily determine system version either.
729        //
730        // Since, the LLVM itself makes rather limited use of version checks in
731        // CMakeFiles (and then only in tests), and so far no issues have been
732        // reported, the system version is currently left unset.
733
734        if target.contains("apple") {
735            if !target.contains("darwin") {
736                // FIXME(madsmtm): compiler-rt's CMake setup is kinda weird, it seems like they do
737                // version testing etc. for macOS (i.e. Darwin), even while building for iOS?
738                //
739                // So for now we set it to "Darwin" on all Apple platforms.
740                cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
741
742                // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
743                cfg.define("CMAKE_OSX_SYSROOT", "/");
744                cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
745            }
746
747            // Make sure that CMake does not build universal binaries on macOS.
748            // Explicitly specify the one single target architecture.
749            if target.starts_with("aarch64") {
750                // macOS uses a different name for building arm64
751                cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
752            } else if target.starts_with("i686") {
753                // macOS uses a different name for building i386
754                cfg.define("CMAKE_OSX_ARCHITECTURES", "i386");
755            } else {
756                cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
757            }
758        }
759    }
760
761    let sanitize_cc = |cc: &Path| {
762        if target.is_msvc() {
763            OsString::from(cc.to_str().unwrap().replace('\\', "/"))
764        } else {
765            cc.as_os_str().to_owned()
766        }
767    };
768
769    // MSVC with CMake uses msbuild by default which doesn't respect these
770    // vars that we'd otherwise configure. In that case we just skip this
771    // entirely.
772    if target.is_msvc() && !builder.ninja() {
773        return;
774    }
775
776    let (cc, cxx) = match builder.config.llvm_clang_cl {
777        Some(ref cl) => (cl.into(), cl.into()),
778        None => (builder.cc(target), builder.cxx(target).unwrap()),
779    };
780
781    // If ccache is configured we inform the build a little differently how
782    // to invoke ccache while also invoking our compilers.
783    if use_compiler_launcher && let Some(ref ccache) = builder.config.ccache {
784        cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
785            .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
786    }
787    cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
788        .define("CMAKE_CXX_COMPILER", sanitize_cc(&cxx))
789        .define("CMAKE_ASM_COMPILER", sanitize_cc(&cc));
790
791    // If we are running under a FIFO jobserver, we should not pass -j to CMake; otherwise it
792    // overrides the jobserver settings and can lead to oversubscription.
793    let has_modern_jobserver = env::var("MAKEFLAGS")
794        .map(|flags| flags.contains("--jobserver-auth=fifo:"))
795        .unwrap_or(false);
796
797    if !has_modern_jobserver {
798        cfg.build_arg("-j").build_arg(builder.jobs().to_string());
799    }
800    let mut cflags = ccflags.cflags.clone();
801    // FIXME(madsmtm): Allow `cmake-rs` to select flags by itself by passing
802    // our flags via `.cflag`/`.cxxflag` instead.
803    //
804    // Needs `suppressed_compiler_flag_prefixes` to be gone, and hence
805    // https://github.com/llvm/llvm-project/issues/88780 to be fixed.
806    for flag in builder
807        .cc_handled_cflags(target, CLang::C)
808        .into_iter()
809        .chain(builder.cc_unhandled_cflags(target, GitRepo::Llvm, CLang::C))
810        .filter(|flag| !suppressed_compiler_flag_prefixes.iter().any(|p| flag.starts_with(p)))
811    {
812        cflags.push(" ");
813        cflags.push(flag);
814    }
815    if let Some(ref s) = builder.config.llvm_cflags {
816        cflags.push(" ");
817        cflags.push(s);
818    }
819    if target.contains("ohos") {
820        cflags.push(" -D_LINUX_SYSINFO_H");
821    }
822    if builder.config.llvm_clang_cl.is_some() {
823        cflags.push(format!(" --target={target}"));
824    }
825    cfg.define("CMAKE_C_FLAGS", cflags);
826    let mut cxxflags = ccflags.cxxflags.clone();
827    for flag in builder
828        .cc_handled_cflags(target, CLang::Cxx)
829        .into_iter()
830        .chain(builder.cc_unhandled_cflags(target, GitRepo::Llvm, CLang::Cxx))
831        .filter(|flag| {
832            !suppressed_compiler_flag_prefixes
833                .iter()
834                .any(|suppressed_prefix| flag.starts_with(suppressed_prefix))
835        })
836    {
837        cxxflags.push(" ");
838        cxxflags.push(flag);
839    }
840    if let Some(ref s) = builder.config.llvm_cxxflags {
841        cxxflags.push(" ");
842        cxxflags.push(s);
843    }
844    if target.contains("ohos") {
845        cxxflags.push(" -D_LINUX_SYSINFO_H");
846    }
847    if builder.config.llvm_clang_cl.is_some() {
848        cxxflags.push(format!(" --target={target}"));
849    }
850
851    cfg.define("CMAKE_CXX_FLAGS", cxxflags);
852    if let Some(ar) = builder.ar(target)
853        && ar.is_absolute()
854    {
855        // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
856        // tries to resolve this path in the LLVM build directory.
857        cfg.define("CMAKE_AR", sanitize_cc(&ar));
858    }
859
860    if let Some(ranlib) = builder.ranlib(target)
861        && ranlib.is_absolute()
862    {
863        // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
864        // tries to resolve this path in the LLVM build directory.
865        cfg.define("CMAKE_RANLIB", sanitize_cc(&ranlib));
866    }
867
868    if let Some(ref flags) = builder.config.llvm_ldflags {
869        ldflags.push_all(flags);
870    }
871
872    if let Some(flags) = get_var("LDFLAGS", &builder.config.host_target.triple, &target.triple) {
873        ldflags.push_all(&flags);
874    }
875
876    // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
877    // We also do this if the user explicitly requested static libstdc++.
878    if builder.config.llvm_static_stdcpp
879        && !target.is_msvc()
880        && !target.contains("netbsd")
881        && !target.contains("solaris")
882    {
883        if target.contains("apple") || target.is_windows() {
884            ldflags.push_all("-static-libstdc++");
885        } else {
886            ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
887        }
888    }
889
890    cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
891    cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
892    cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
893
894    if env::var_os("SCCACHE_ERROR_LOG").is_some() {
895        cfg.env("RUSTC_LOG", "sccache=warn");
896    }
897}
898
899fn configure_llvm(builder: &Builder<'_>, target: TargetSelection, cfg: &mut cmake::Config) {
900    // ThinLTO is only available when building with LLVM, enabling LLD is required.
901    // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
902    if builder.config.llvm_thin_lto {
903        cfg.define("LLVM_ENABLE_LTO", "Thin");
904        if !target.contains("apple") {
905            cfg.define("LLVM_ENABLE_LLD", "ON");
906        }
907    }
908
909    // Libraries for ELF section compression.
910    if builder.config.llvm_libzstd {
911        cfg.define("LLVM_ENABLE_ZSTD", "FORCE_ON");
912        cfg.define("LLVM_USE_STATIC_ZSTD", "TRUE");
913    } else {
914        cfg.define("LLVM_ENABLE_ZSTD", "OFF");
915    }
916
917    if let Some(ref linker) = builder.config.llvm_use_linker {
918        cfg.define("LLVM_USE_LINKER", linker);
919    }
920
921    if builder.config.llvm_allow_old_toolchain {
922        cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
923    }
924}
925
926// Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
927fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
928    let kind = if host == target { "HOST" } else { "TARGET" };
929    let target_u = target.replace('-', "_");
930    env::var_os(format!("{var_base}_{target}"))
931        .or_else(|| env::var_os(format!("{var_base}_{target_u}")))
932        .or_else(|| env::var_os(format!("{kind}_{var_base}")))
933        .or_else(|| env::var_os(var_base))
934}
935
936#[derive(Clone)]
937pub struct BuiltOmpOffload {
938    /// Path to the omp and offload dylibs.
939    offload: Vec<PathBuf>,
940}
941
942impl BuiltOmpOffload {
943    pub fn offload_paths(&self) -> Vec<PathBuf> {
944        self.offload.clone()
945    }
946}
947
948// FIXME(offload): In an ideal world, we would just enable the offload runtime in our previous LLVM
949// build step. For now, we still depend on the openmp runtime since we use some of it's API, so we
950// build both. However, when building those runtimes as part of the LLVM step, then LLVM's cmake
951// implicitly assumes that Clang has also been build and will try to use it. In the Rust CI, we
952// don't always build clang (due to compile times), but instead use a slightly older external clang.
953// LLVM tries to remove this build dependency of offload/openmp on Clang for LLVM-22, so in the
954// future we might be able to integrate this step into the LLVM step. For now, we instead introduce
955// a Clang_DIR bootstrap option, which allows us tell CMake to use an external clang for these two
956// runtimes. This external clang will try to use it's own (older) include dirs when building our
957// in-tree LLVM submodule, which will cause build failures. To prevent those, we now also
958// explicitly set our include dirs.
959#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
960pub struct OmpOffload {
961    pub target: TargetSelection,
962}
963
964impl Step for OmpOffload {
965    type Output = BuiltOmpOffload;
966    const IS_HOST: bool = true;
967
968    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
969        run.path("src/llvm-project/offload")
970    }
971
972    fn make_run(run: RunConfig<'_>) {
973        run.builder.ensure(OmpOffload { target: run.target });
974    }
975
976    /// Compile OpenMP offload runtimes for `target`.
977    #[allow(unused)]
978    fn run(self, builder: &Builder<'_>) -> Self::Output {
979        if builder.config.dry_run() {
980            return BuiltOmpOffload {
981                offload: vec![builder.config.tempdir().join("llvm-offload-dry-run")],
982            };
983        }
984        let target = self.target;
985
986        let LlvmResult { host_llvm_config, llvm_cmake_dir } =
987            builder.ensure(Llvm { target: self.target });
988
989        // Running cmake twice in the same folder is known to cause issues, like deleting existing
990        // binaries. We therefore write our offload artifacts into it's own folder, instead of
991        // using the llvm build dir.
992        let out_dir = builder.offload_out(target);
993
994        let mut files = vec![];
995        let lib_ext = std::env::consts::DLL_EXTENSION;
996        files.push(out_dir.join("lib").join("libLLVMOffload").with_extension(lib_ext));
997        files.push(out_dir.join("lib").join("libomp").with_extension(lib_ext));
998        files.push(out_dir.join("lib").join("libomptarget").with_extension(lib_ext));
999
1000        // Offload/OpenMP are just subfolders of LLVM, so we can use the LLVM sha.
1001        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1002        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1003            generate_smart_stamp_hash(
1004                builder,
1005                &builder.config.src.join("src/llvm-project/offload"),
1006                builder.in_tree_llvm_info.sha().unwrap_or_default(),
1007            )
1008        });
1009        let stamp = BuildStamp::new(&out_dir).with_prefix("offload").add_stamp(smart_stamp_hash);
1010
1011        trace!("checking build stamp to see if we need to rebuild offload/openmp artifacts");
1012        if stamp.is_up_to_date() {
1013            trace!(?out_dir, "offload/openmp build artifacts are up to date");
1014            if stamp.stamp().is_empty() {
1015                builder.info(
1016                    "Could not determine the Offload submodule commit hash. \
1017                     Assuming that an Offload rebuild is not necessary.",
1018                );
1019                builder.info(&format!(
1020                    "To force Offload/OpenMP to rebuild, remove the file `{}`",
1021                    stamp.path().display()
1022                ));
1023            }
1024            return BuiltOmpOffload { offload: files };
1025        }
1026
1027        trace!(?target, "(re)building offload/openmp artifacts");
1028        builder.info(&format!("Building OpenMP/Offload for {target}"));
1029        t!(stamp.remove());
1030        let _time = helpers::timeit(builder);
1031        t!(fs::create_dir_all(&out_dir));
1032
1033        builder.config.update_submodule("src/llvm-project");
1034
1035        // OpenMP/Offload builds currently (LLVM-22) still depend on Clang, although there are
1036        // intentions to loosen this requirement over time. FIXME(offload): re-evaluate on LLVM 23
1037        let clang_dir = if !builder.config.llvm_clang {
1038            // We must have an external clang to use.
1039            assert!(&builder.build.config.llvm_clang_dir.is_some());
1040            builder.build.config.llvm_clang_dir.clone()
1041        } else {
1042            // No need to specify it, since we use the in-tree clang
1043            None
1044        };
1045
1046        // In the context of OpenMP offload, some libraries must be compiled for the gpu target,
1047        // some for the host, and others for both. We do not perform a full cross-compilation, since
1048        // we don't want to run rustc on a GPU.
1049        let omp_targets = vec![target.triple.as_ref(), "amdgcn-amd-amdhsa", "nvptx64-nvidia-cuda"];
1050        for omp_target in omp_targets {
1051            let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/runtimes/"));
1052
1053            // If we use an external clang as opposed to building our own llvm_clang, than that clang will
1054            // come with it's own set of default include directories, which are based on a potentially older
1055            // LLVM. This can cause issues, so we overwrite it to include headers based on our
1056            // `src/llvm-project` submodule instead.
1057            // FIXME(offload): With LLVM-22 we hopefully won't need an external clang anymore.
1058            let mut cflags = CcFlags::default();
1059            if !builder.config.llvm_clang {
1060                let base = builder.llvm_out(target).join("include");
1061                let inc_dir = base.display();
1062                cflags.push_all(format!(" -I {inc_dir}"));
1063            }
1064
1065            configure_cmake(builder, target, &mut cfg, true, LdFlags::default(), cflags, &[]);
1066
1067            // Re-use the same flags as llvm to control the level of debug information
1068            // generated for offload.
1069            let profile =
1070                match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
1071                    (false, _) => "Debug",
1072                    (true, false) => "Release",
1073                    (true, true) => "RelWithDebInfo",
1074                };
1075            trace!(?profile);
1076
1077            // FIXME(offload): Once we move from OMP to Offload (Ol) APIs, we should drop the openmp
1078            // runtime to simplify our build. So far, these are still under development.
1079            cfg.out_dir(&out_dir)
1080                .profile(profile)
1081                .env("LLVM_CONFIG_REAL", &host_llvm_config)
1082                .define("LLVM_ENABLE_ASSERTIONS", "ON")
1083                .define("LLVM_INCLUDE_TESTS", "OFF")
1084                .define("OFFLOAD_INCLUDE_TESTS", "OFF")
1085                .define("LLVM_ROOT", builder.llvm_out(target).join("build"))
1086                .define("LLVM_DIR", llvm_cmake_dir.clone())
1087                .define("LLVM_DEFAULT_TARGET_TRIPLE", omp_target);
1088            if let Some(p) = clang_dir.clone() {
1089                cfg.define("Clang_DIR", p);
1090            }
1091
1092            // We don't perform a full cross-compilation of rustc, therefore our target.triple
1093            // will still be a CPU target.
1094            if *omp_target == *target.triple {
1095                // The offload library provides functionality which only makes sense on the host.
1096                cfg.define("LLVM_ENABLE_RUNTIMES", "openmp;offload");
1097            } else {
1098                // OpenMP provides some device libraries, so we also compile it for all gpu targets.
1099                cfg.define("LLVM_USE_LINKER", "lld");
1100                cfg.define("LLVM_ENABLE_RUNTIMES", "openmp");
1101                cfg.define("CMAKE_C_COMPILER_TARGET", omp_target);
1102                cfg.define("CMAKE_CXX_COMPILER_TARGET", omp_target);
1103            }
1104            cfg.build();
1105        }
1106
1107        t!(stamp.write());
1108
1109        for p in &files {
1110            // At this point, `out_dir` should contain the built <offload-filename>.<dylib-ext>
1111            // files.
1112            if !p.exists() {
1113                eprintln!(
1114                    "`{p:?}` not found in `{}`. Either the build has failed or Offload was built with a wrong version of LLVM",
1115                    out_dir.display()
1116                );
1117                exit!(1);
1118            }
1119        }
1120        BuiltOmpOffload { offload: files }
1121    }
1122}
1123
1124#[derive(Clone)]
1125pub struct BuiltEnzyme {
1126    /// Path to the libEnzyme dylib.
1127    enzyme: PathBuf,
1128}
1129
1130impl BuiltEnzyme {
1131    pub fn enzyme_path(&self) -> PathBuf {
1132        self.enzyme.clone()
1133    }
1134    pub fn enzyme_filename(&self) -> String {
1135        self.enzyme.file_name().unwrap().to_str().unwrap().to_owned()
1136    }
1137}
1138
1139#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1140pub struct Enzyme {
1141    pub target: TargetSelection,
1142}
1143
1144impl Step for Enzyme {
1145    type Output = BuiltEnzyme;
1146    const IS_HOST: bool = true;
1147
1148    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1149        run.path("src/tools/enzyme/enzyme")
1150    }
1151
1152    fn make_run(run: RunConfig<'_>) {
1153        run.builder.ensure(Enzyme { target: run.target });
1154    }
1155
1156    /// Compile Enzyme for `target`.
1157    fn run(self, builder: &Builder<'_>) -> Self::Output {
1158        builder.require_submodule(
1159            "src/tools/enzyme",
1160            Some("The Enzyme sources are required for autodiff."),
1161        );
1162        let target = self.target;
1163
1164        if builder.config.dry_run() {
1165            return BuiltEnzyme { enzyme: builder.config.tempdir().join("enzyme-dryrun") };
1166        }
1167
1168        let LlvmResult { host_llvm_config, llvm_cmake_dir } = builder.ensure(Llvm { target });
1169
1170        // Enzyme links against LLVM. If we update the LLVM submodule libLLVM might get a new
1171        // version number, in which case Enzyme will now fail to find LLVM. By including the LLVM
1172        // hash into the Enzyme hash we force a rebuild of Enzyme when updating LLVM.
1173        let enzyme_hash_input = builder.in_tree_llvm_info.sha().unwrap_or_default().to_owned()
1174            + builder.enzyme_info.sha().unwrap_or_default();
1175
1176        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1177        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1178            generate_smart_stamp_hash(
1179                builder,
1180                &builder.config.src.join("src/tools/enzyme"),
1181                &enzyme_hash_input,
1182            )
1183        });
1184
1185        let out_dir = builder.enzyme_out(target);
1186        let stamp = BuildStamp::new(&out_dir).with_prefix("enzyme").add_stamp(smart_stamp_hash);
1187
1188        let llvm_version_major = llvm::get_llvm_version_major(builder, &host_llvm_config);
1189        let lib_ext = std::env::consts::DLL_EXTENSION;
1190        let libenzyme = format!("libEnzyme-{llvm_version_major}");
1191        let build_dir = out_dir.join(libdir(target));
1192        let dylib = build_dir.join(&libenzyme).with_extension(lib_ext);
1193
1194        trace!("checking build stamp to see if we need to rebuild enzyme artifacts");
1195        if stamp.is_up_to_date() {
1196            trace!(?out_dir, "enzyme build artifacts are up to date");
1197            if stamp.stamp().is_empty() {
1198                builder.info(
1199                    "Could not determine the Enzyme submodule commit hash. \
1200                     Assuming that an Enzyme rebuild is not necessary.",
1201                );
1202                builder.info(&format!(
1203                    "To force Enzyme to rebuild, remove the file `{}`",
1204                    stamp.path().display()
1205                ));
1206            }
1207            return BuiltEnzyme { enzyme: dylib };
1208        }
1209
1210        if !builder.config.dry_run() && !llvm_cmake_dir.is_dir() {
1211            builder.info(&format!(
1212                "WARNING: {} does not exist, Enzyme build will likely fail",
1213                llvm_cmake_dir.display()
1214            ));
1215        }
1216
1217        trace!(?target, "(re)building enzyme artifacts");
1218        builder.info(&format!("Building Enzyme for {target}"));
1219        t!(stamp.remove());
1220        let _time = helpers::timeit(builder);
1221        t!(fs::create_dir_all(&out_dir));
1222
1223        let mut cfg = cmake::Config::new(builder.src.join("src/tools/enzyme/enzyme/"));
1224        // Enzyme devs maintain upstream compatibility, but only fix deprecations when they are about
1225        // to turn into a hard error. As such, Enzyme generates various warnings which could make it
1226        // hard to spot more relevant issues.
1227        let mut cflags = CcFlags::default();
1228        cflags.push_all("-Wno-deprecated");
1229
1230        // Logic copied from `configure_llvm`
1231        // ThinLTO is only available when building with LLVM, enabling LLD is required.
1232        // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
1233        let mut ldflags = LdFlags::default();
1234        if builder.config.llvm_thin_lto && !target.contains("apple") {
1235            ldflags.push_all("-fuse-ld=lld");
1236        }
1237
1238        configure_cmake(builder, target, &mut cfg, true, ldflags, cflags, &[]);
1239
1240        // Re-use the same flags as llvm to control the level of debug information
1241        // generated by Enzyme.
1242        // FIXME(ZuseZ4): Find a nicer way to use Enzyme Debug builds.
1243        let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
1244            (false, _) => "Debug",
1245            (true, false) => "Release",
1246            (true, true) => "RelWithDebInfo",
1247        };
1248        trace!(?profile);
1249
1250        cfg.out_dir(&out_dir)
1251            .profile(profile)
1252            .env("LLVM_CONFIG_REAL", &host_llvm_config)
1253            .define("LLVM_ENABLE_ASSERTIONS", "ON")
1254            .define("ENZYME_EXTERNAL_SHARED_LIB", "ON")
1255            .define("ENZYME_BC_LOADER", "OFF")
1256            .define("LLVM_DIR", llvm_cmake_dir);
1257
1258        cfg.build();
1259
1260        // At this point, `out_dir` should contain the built libEnzyme-<LLVM-version>.<dylib-ext>
1261        // file.
1262        if !dylib.exists() {
1263            eprintln!(
1264                "`{libenzyme}` not found in `{}`. Either the build has failed or Enzyme was built with a wrong version of LLVM",
1265                build_dir.display()
1266            );
1267            exit!(1);
1268        }
1269
1270        t!(stamp.write());
1271        BuiltEnzyme { enzyme: dylib }
1272    }
1273}
1274
1275#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1276pub struct Lld {
1277    pub target: TargetSelection,
1278}
1279
1280impl Step for Lld {
1281    type Output = PathBuf;
1282    const IS_HOST: bool = true;
1283
1284    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1285        run.path("src/llvm-project/lld")
1286    }
1287
1288    fn make_run(run: RunConfig<'_>) {
1289        run.builder.ensure(Lld { target: run.target });
1290    }
1291
1292    /// Compile LLD for `target`.
1293    fn run(self, builder: &Builder<'_>) -> PathBuf {
1294        if builder.config.dry_run() {
1295            return PathBuf::from("lld-out-dir-test-gen");
1296        }
1297        let target = self.target;
1298
1299        let LlvmResult { host_llvm_config, llvm_cmake_dir } = builder.ensure(Llvm { target });
1300
1301        // The `dist` step packages LLD next to LLVM's binaries for download-ci-llvm. The root path
1302        // we usually expect here is `./build/$triple/ci-llvm/`, with the binaries in its `bin`
1303        // subfolder. We check if that's the case, and if LLD's binary already exists there next to
1304        // `llvm-config`: if so, we can use it instead of building LLVM/LLD from source.
1305        let ci_llvm_bin = host_llvm_config.parent().unwrap();
1306        if ci_llvm_bin.is_dir() && ci_llvm_bin.file_name().unwrap() == "bin" {
1307            let lld_path = ci_llvm_bin.join(exe("lld", target));
1308            if lld_path.exists() {
1309                // The following steps copying `lld` as `rust-lld` to the sysroot, expect it in the
1310                // `bin` subfolder of this step's out dir.
1311                return ci_llvm_bin.parent().unwrap().to_path_buf();
1312            }
1313        }
1314
1315        let out_dir = builder.lld_out(target);
1316
1317        let lld_stamp = BuildStamp::new(&out_dir).with_prefix("lld");
1318        if lld_stamp.path().exists() {
1319            return out_dir;
1320        }
1321
1322        let _guard = builder.msg_unstaged(Kind::Build, "LLD", target);
1323        let _time = helpers::timeit(builder);
1324        t!(fs::create_dir_all(&out_dir));
1325
1326        let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
1327        let mut ldflags = LdFlags::default();
1328
1329        // When building LLD as part of a build with instrumentation on windows, for example
1330        // when doing PGO on CI, cmake or clang-cl don't automatically link clang's
1331        // profiler runtime in. In that case, we need to manually ask cmake to do it, to avoid
1332        // linking errors, much like LLVM's cmake setup does in that situation.
1333        if builder.config.llvm_pgo.generate_profile.is_some()
1334            && target.is_msvc()
1335            && let Some(clang_cl_path) = builder.config.llvm_clang_cl.as_ref()
1336        {
1337            // Find clang's runtime library directory and push that as a search path to the
1338            // cmake linker flags.
1339            let clang_rt_dir = get_clang_cl_resource_dir(builder, clang_cl_path);
1340            ldflags.push_all(format!("/libpath:{}", clang_rt_dir.display()));
1341        }
1342
1343        // LLD is built as an LLVM tool, but is distributed outside of the `llvm-tools` component,
1344        // which impacts where it expects to find LLVM's shared library. This causes #80703.
1345        //
1346        // LLD is distributed at "$root/lib/rustlib/$host/bin/rust-lld", but the `libLLVM-*.so` it
1347        // needs is distributed at "$root/lib". The default rpath of "$ORIGIN/../lib" points at the
1348        // lib path for LLVM tools, not the one for rust binaries.
1349        //
1350        // (The `llvm-tools` component copies the .so there for the other tools, and with that
1351        // component installed, one can successfully invoke `rust-lld` directly without rustup's
1352        // `LD_LIBRARY_PATH` overrides)
1353        //
1354        if builder.config.rpath_enabled(target)
1355            && helpers::use_host_linker(target)
1356            && builder.config.llvm_link_shared()
1357            && target.contains("linux")
1358        {
1359            // So we inform LLD where it can find LLVM's libraries by adding an rpath entry to the
1360            // expected parent `lib` directory.
1361            //
1362            // Be careful when changing this path, we need to ensure it's quoted or escaped:
1363            // `$ORIGIN` would otherwise be expanded when the `LdFlags` are passed verbatim to
1364            // cmake.
1365            ldflags.push_all("-Wl,-rpath,'$ORIGIN/../../../'");
1366        }
1367
1368        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
1369        configure_llvm(builder, target, &mut cfg);
1370
1371        // Re-use the same flags as llvm to control the level of debug information
1372        // generated for lld.
1373        let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
1374            (false, _) => "Debug",
1375            (true, false) => "Release",
1376            (true, true) => "RelWithDebInfo",
1377        };
1378
1379        cfg.out_dir(&out_dir)
1380            .profile(profile)
1381            .define("LLVM_CMAKE_DIR", llvm_cmake_dir)
1382            .define("LLVM_INCLUDE_TESTS", "OFF");
1383
1384        if !builder.config.is_host_target(target) {
1385            // Use the host llvm-tblgen binary.
1386            cfg.define(
1387                "LLVM_TABLEGEN_EXE",
1388                host_llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
1389            );
1390        }
1391
1392        cfg.build();
1393
1394        t!(lld_stamp.write());
1395        out_dir
1396    }
1397}
1398
1399#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1400pub struct Sanitizers {
1401    pub target: TargetSelection,
1402}
1403
1404impl Step for Sanitizers {
1405    type Output = Vec<SanitizerRuntime>;
1406
1407    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1408        run.alias("sanitizers")
1409    }
1410
1411    fn make_run(run: RunConfig<'_>) {
1412        run.builder.ensure(Sanitizers { target: run.target });
1413    }
1414
1415    /// Builds sanitizer runtime libraries.
1416    fn run(self, builder: &Builder<'_>) -> Self::Output {
1417        let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
1418        if !compiler_rt_dir.exists() {
1419            return Vec::new();
1420        }
1421
1422        let out_dir = builder.native_dir(self.target).join("sanitizers");
1423        let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
1424
1425        if builder.config.dry_run() || runtimes.is_empty() {
1426            return runtimes;
1427        }
1428
1429        let LlvmResult { host_llvm_config, .. } =
1430            builder.ensure(Llvm { target: builder.config.host_target });
1431
1432        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1433        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1434            generate_smart_stamp_hash(
1435                builder,
1436                &builder.config.src.join("src/llvm-project/compiler-rt"),
1437                builder.in_tree_llvm_info.sha().unwrap_or_default(),
1438            )
1439        });
1440
1441        let stamp = BuildStamp::new(&out_dir).with_prefix("sanitizers").add_stamp(smart_stamp_hash);
1442
1443        if stamp.is_up_to_date() {
1444            if stamp.stamp().is_empty() {
1445                builder.info(&format!(
1446                    "Rebuild sanitizers by removing the file `{}`",
1447                    stamp.path().display()
1448                ));
1449            }
1450
1451            return runtimes;
1452        }
1453
1454        let _guard = builder.msg_unstaged(Kind::Build, "sanitizers", self.target);
1455        t!(stamp.remove());
1456        let _time = helpers::timeit(builder);
1457
1458        let mut cfg = cmake::Config::new(&compiler_rt_dir);
1459        cfg.profile("Release");
1460        cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
1461        cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
1462        cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
1463        cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
1464        cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
1465        cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
1466        cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
1467        cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
1468        cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
1469        cfg.define("LLVM_CONFIG_PATH", &host_llvm_config);
1470
1471        if self.target.contains("ohos") {
1472            cfg.define("COMPILER_RT_USE_BUILTINS_LIBRARY", "ON");
1473        }
1474
1475        // On Darwin targets the sanitizer runtimes are build as universal binaries.
1476        // Unfortunately sccache currently lacks support to build them successfully.
1477        // Disable compiler launcher on Darwin targets to avoid potential issues.
1478        let use_compiler_launcher = !self.target.contains("apple-darwin");
1479        // Since v1.0.86, the cc crate adds -mmacosx-version-min to the default
1480        // flags on MacOS. A long-standing bug in the CMake rules for compiler-rt
1481        // causes architecture detection to be skipped when this flag is present,
1482        // and compilation fails. https://github.com/llvm/llvm-project/issues/88780
1483        let suppressed_compiler_flag_prefixes: &[&str] =
1484            if self.target.contains("apple-darwin") { &["-mmacosx-version-min="] } else { &[] };
1485        configure_cmake(
1486            builder,
1487            self.target,
1488            &mut cfg,
1489            use_compiler_launcher,
1490            LdFlags::default(),
1491            CcFlags::default(),
1492            suppressed_compiler_flag_prefixes,
1493        );
1494
1495        t!(fs::create_dir_all(&out_dir));
1496        cfg.out_dir(out_dir);
1497
1498        for runtime in &runtimes {
1499            cfg.build_target(&runtime.cmake_target);
1500            cfg.build();
1501        }
1502        t!(stamp.write());
1503
1504        runtimes
1505    }
1506}
1507
1508#[derive(Clone, Debug)]
1509pub struct SanitizerRuntime {
1510    /// CMake target used to build the runtime.
1511    pub cmake_target: String,
1512    /// Path to the built runtime library.
1513    pub path: PathBuf,
1514    /// Library filename that will be used rustc.
1515    pub name: String,
1516}
1517
1518/// Returns sanitizers available on a given target.
1519fn supported_sanitizers(
1520    out_dir: &Path,
1521    target: TargetSelection,
1522    channel: &str,
1523) -> Vec<SanitizerRuntime> {
1524    let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1525        components
1526            .iter()
1527            .map(move |c| SanitizerRuntime {
1528                cmake_target: format!("clang_rt.{c}_{os}_dynamic"),
1529                path: out_dir.join(format!("build/lib/darwin/libclang_rt.{c}_{os}_dynamic.dylib")),
1530                name: format!("librustc-{channel}_rt.{c}.dylib"),
1531            })
1532            .collect()
1533    };
1534
1535    let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1536        components
1537            .iter()
1538            .map(move |c| SanitizerRuntime {
1539                cmake_target: format!("clang_rt.{c}-{arch}"),
1540                path: out_dir.join(format!("build/lib/{os}/libclang_rt.{c}-{arch}.a")),
1541                name: format!("librustc-{channel}_rt.{c}.a"),
1542            })
1543            .collect()
1544    };
1545
1546    match &*target.triple {
1547        "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),
1548        "aarch64-apple-ios" => darwin_libs("ios", &["asan", "tsan", "rtsan"]),
1549        "aarch64-apple-ios-sim" => darwin_libs("iossim", &["asan", "tsan", "rtsan"]),
1550        "aarch64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1551        "aarch64-unknown-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
1552        "aarch64-unknown-linux-gnu" => {
1553            common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan", "rtsan"])
1554        }
1555        "aarch64-unknown-linux-ohos" => {
1556            common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
1557        }
1558        "loongarch64-unknown-linux-gnu" | "loongarch64-unknown-linux-musl" => {
1559            common_libs("linux", "loongarch64", &["asan", "lsan", "msan", "tsan"])
1560        }
1561        "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),
1562        "x86_64-unknown-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
1563        "x86_64-apple-ios" => darwin_libs("iossim", &["asan", "tsan"]),
1564        "x86_64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1565        "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
1566        "x86_64-unknown-netbsd" => {
1567            common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
1568        }
1569        "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
1570        "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
1571        "x86_64-unknown-linux-gnu" => common_libs(
1572            "linux",
1573            "x86_64",
1574            &["asan", "dfsan", "lsan", "msan", "safestack", "tsan", "rtsan"],
1575        ),
1576        "x86_64-unknown-linux-gnuasan" => common_libs("linux", "x86_64", &["asan"]),
1577        "x86_64-unknown-linux-gnumsan" => common_libs("linux", "x86_64", &["msan"]),
1578        "x86_64-unknown-linux-gnutsan" => common_libs("linux", "x86_64", &["tsan"]),
1579        "x86_64-unknown-linux-musl" => {
1580            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1581        }
1582        "s390x-unknown-linux-gnu" => {
1583            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1584        }
1585        "s390x-unknown-linux-musl" => {
1586            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1587        }
1588        "x86_64-unknown-linux-ohos" => {
1589            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1590        }
1591        _ => Vec::new(),
1592    }
1593}
1594
1595#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1596pub struct CrtBeginEnd {
1597    pub target: TargetSelection,
1598}
1599
1600impl Step for CrtBeginEnd {
1601    type Output = PathBuf;
1602
1603    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1604        run.path("src/llvm-project/compiler-rt/lib/crt")
1605    }
1606
1607    fn make_run(run: RunConfig<'_>) {
1608        if run.target.needs_crt_begin_end() {
1609            run.builder.ensure(CrtBeginEnd { target: run.target });
1610        }
1611    }
1612
1613    /// Build crtbegin.o/crtend.o for musl target.
1614    fn run(self, builder: &Builder<'_>) -> Self::Output {
1615        builder.require_submodule(
1616            "src/llvm-project",
1617            Some("The LLVM sources are required for the CRT from `compiler-rt`."),
1618        );
1619
1620        let out_dir = builder.native_dir(self.target).join("crt");
1621
1622        if builder.config.dry_run() {
1623            return out_dir;
1624        }
1625
1626        let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtbegin.c");
1627        let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtend.c");
1628        if up_to_date(&crtbegin_src, &out_dir.join("crtbeginS.o"))
1629            && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
1630        {
1631            return out_dir;
1632        }
1633
1634        let _guard = builder.msg_unstaged(Kind::Build, "crtbegin.o and crtend.o", self.target);
1635        t!(fs::create_dir_all(&out_dir));
1636
1637        let mut cfg = cc::Build::new();
1638
1639        if let Some(ar) = builder.ar(self.target) {
1640            cfg.archiver(ar);
1641        }
1642        cfg.compiler(builder.cc(self.target));
1643        cfg.cargo_metadata(false)
1644            .out_dir(&out_dir)
1645            .target(&self.target.triple)
1646            .host(&builder.config.host_target.triple)
1647            .warnings(false)
1648            .debug(false)
1649            .opt_level(3)
1650            .file(crtbegin_src)
1651            .file(crtend_src);
1652
1653        // Those flags are defined in src/llvm-project/compiler-rt/lib/builtins/CMakeLists.txt
1654        // Currently only consumer of those objects is musl, which use .init_array/.fini_array
1655        // instead of .ctors/.dtors
1656        cfg.flag("-std=c11")
1657            .define("CRT_HAS_INITFINI_ARRAY", None)
1658            .define("EH_USE_FRAME_REGISTRY", None);
1659
1660        let objs = cfg.compile_intermediates();
1661        assert_eq!(objs.len(), 2);
1662        for obj in objs {
1663            let base_name = unhashed_basename(&obj);
1664            assert!(base_name == "crtbegin" || base_name == "crtend");
1665            t!(fs::copy(&obj, out_dir.join(format!("{base_name}S.o"))));
1666            t!(fs::rename(&obj, out_dir.join(format!("{base_name}.o"))));
1667        }
1668
1669        out_dir
1670    }
1671}
1672
1673#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1674pub struct Libunwind {
1675    pub target: TargetSelection,
1676}
1677
1678impl Step for Libunwind {
1679    type Output = PathBuf;
1680
1681    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1682        run.path("src/llvm-project/libunwind")
1683    }
1684
1685    fn make_run(run: RunConfig<'_>) {
1686        run.builder.ensure(Libunwind { target: run.target });
1687    }
1688
1689    /// Build libunwind.a
1690    fn run(self, builder: &Builder<'_>) -> Self::Output {
1691        builder.require_submodule(
1692            "src/llvm-project",
1693            Some("The LLVM sources are required for libunwind."),
1694        );
1695
1696        if builder.config.dry_run() {
1697            return PathBuf::new();
1698        }
1699
1700        let out_dir = builder.native_dir(self.target).join("libunwind");
1701        let root = builder.src.join("src/llvm-project/libunwind");
1702
1703        if up_to_date(&root, &out_dir.join("libunwind.a")) {
1704            return out_dir;
1705        }
1706
1707        let _guard = builder.msg_unstaged(Kind::Build, "libunwind.a", self.target);
1708        t!(fs::create_dir_all(&out_dir));
1709
1710        let mut cc_cfg = cc::Build::new();
1711        let mut cpp_cfg = cc::Build::new();
1712
1713        cpp_cfg.cpp(true);
1714        cpp_cfg.cpp_set_stdlib(None);
1715        cpp_cfg.flag("-nostdinc++");
1716        cpp_cfg.flag("-fno-exceptions");
1717        cpp_cfg.flag("-fno-rtti");
1718        cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
1719
1720        for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
1721            if let Some(ar) = builder.ar(self.target) {
1722                cfg.archiver(ar);
1723            }
1724            cfg.target(&self.target.triple);
1725            cfg.host(&builder.config.host_target.triple);
1726            cfg.warnings(false);
1727            cfg.debug(false);
1728            // get_compiler() need set opt_level first.
1729            cfg.opt_level(3);
1730            cfg.flag("-fstrict-aliasing");
1731            cfg.flag("-funwind-tables");
1732            cfg.flag("-fvisibility=hidden");
1733            cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1734            cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");
1735            cfg.include(root.join("include"));
1736            cfg.cargo_metadata(false);
1737            cfg.out_dir(&out_dir);
1738
1739            if self.target.contains("x86_64-fortanix-unknown-sgx") {
1740                cfg.static_flag(true);
1741                cfg.flag("-fno-stack-protector");
1742                cfg.flag("-ffreestanding");
1743                cfg.flag("-fexceptions");
1744
1745                // easiest way to undefine since no API available in cc::Build to undefine
1746                cfg.flag("-U_FORTIFY_SOURCE");
1747                cfg.define("_FORTIFY_SOURCE", "0");
1748                cfg.define("RUST_SGX", "1");
1749                cfg.define("__NO_STRING_INLINES", None);
1750                cfg.define("__NO_MATH_INLINES", None);
1751                cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1752                cfg.define("NDEBUG", None);
1753            }
1754            if self.target.is_windows() {
1755                cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");
1756            }
1757        }
1758
1759        cc_cfg.compiler(builder.cc(self.target));
1760        if let Ok(cxx) = builder.cxx(self.target) {
1761            cpp_cfg.compiler(cxx);
1762        } else {
1763            cc_cfg.compiler(builder.cc(self.target));
1764        }
1765
1766        // Don't set this for clang
1767        // By default, Clang builds C code in GNU C17 mode.
1768        // By default, Clang builds C++ code according to the C++98 standard,
1769        // with many C++11 features accepted as extensions.
1770        if cc_cfg.get_compiler().is_like_gnu() {
1771            cc_cfg.flag("-std=c99");
1772        }
1773        if cpp_cfg.get_compiler().is_like_gnu() {
1774            cpp_cfg.flag("-std=c++11");
1775        }
1776
1777        if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1778            // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1779            // C++ compiler env variables on the builders.
1780            // Don't set this for clang++, as clang++ is able to compile this without libc++.
1781            if cpp_cfg.get_compiler().is_like_gnu() {
1782                cpp_cfg.cpp(false);
1783                cpp_cfg.compiler(builder.cc(self.target));
1784            }
1785        }
1786
1787        let mut c_sources = vec![
1788            "Unwind-sjlj.c",
1789            "UnwindLevel1-gcc-ext.c",
1790            "UnwindLevel1.c",
1791            "UnwindRegistersRestore.S",
1792            "UnwindRegistersSave.S",
1793        ];
1794
1795        let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1796        let cpp_len = cpp_sources.len();
1797
1798        if self.target.contains("x86_64-fortanix-unknown-sgx") {
1799            c_sources.push("UnwindRustSgx.c");
1800        }
1801
1802        for src in c_sources {
1803            cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1804        }
1805
1806        for src in &cpp_sources {
1807            cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1808        }
1809
1810        cpp_cfg.compile("unwind-cpp");
1811
1812        // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1813        let mut count = 0;
1814        let mut files = fs::read_dir(&out_dir)
1815            .unwrap()
1816            .map(|entry| entry.unwrap().path().canonicalize().unwrap())
1817            .collect::<Vec<_>>();
1818        files.sort();
1819        for file in files {
1820            if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1821                // Object file name without the hash prefix is "Unwind-EHABI", "Unwind-seh" or "libunwind".
1822                let base_name = unhashed_basename(&file);
1823                if cpp_sources.iter().any(|f| *base_name == f[..f.len() - 4]) {
1824                    cc_cfg.object(&file);
1825                    count += 1;
1826                }
1827            }
1828        }
1829        assert_eq!(cpp_len, count, "Can't get object files from {out_dir:?}");
1830
1831        cc_cfg.compile("unwind");
1832        out_dir
1833    }
1834}