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::exit;
18use build_helper::git::PathFreshness;
19
20use 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};
29
30#[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}
38
39pub struct Meta {
40    stamp: BuildStamp,
41    res: LlvmResult,
42    out_dir: PathBuf,
43    root: String,
44}
45
46pub enum LlvmBuildStatus {
47    AlreadyBuilt(LlvmResult),
48    ShouldBuild(Meta),
49}
50
51impl LlvmBuildStatus {
52    pub fn should_build(&self) -> bool {
53        match self {
54            LlvmBuildStatus::AlreadyBuilt(_) => false,
55            LlvmBuildStatus::ShouldBuild(_) => true,
56        }
57    }
58
59    #[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}
67
68/// 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}
76
77impl 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}
86
87/// Linker flags to pass to LLVM's CMake invocation.
88#[derive(Debug, Clone, Default)]
89struct LdFlags {
90    /// CMAKE_EXE_LINKER_FLAGS
91    exe: OsString,
92    /// CMAKE_SHARED_LINKER_FLAGS
93    shared: OsString,
94    /// CMAKE_MODULE_LINKER_FLAGS
95    module: OsString,
96}
97
98impl 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}
109
110/// 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 built
113/// 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 it
116/// 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();
126
127    // If we're using a custom LLVM bail out here, but we can only use a
128    // custom LLVM for the build triple.
129    if let Some(config) = builder.config.target_config.get(&target)
130        && let Some(ref s) = config.llvm_config
131    {
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    }
142
143    if handle_submodule_when_needed {
144        // If submodules are disabled, this does nothing.
145        builder.config.update_submodule("src/llvm-project");
146    }
147
148    let root = "src/llvm-project/llvm";
149    let out_dir = builder.llvm_out(target);
150
151    let build_llvm_config = if let Some(build_llvm_config) = builder
152        .config
153        .target_config
154        .get(&builder.config.host_target)
155        .and_then(|config| config.llvm_config.clone())
156    {
157        build_llvm_config
158    } 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    };
163
164    let llvm_cmake_dir = out_dir.join("lib/cmake/llvm");
165    let res = LlvmResult { host_llvm_config: build_llvm_config, llvm_cmake_dir };
166
167    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    });
175
176    let stamp = BuildStamp::new(&out_dir).with_prefix("llvm").add_stamp(smart_stamp_hash);
177
178    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    }
191
192    LlvmBuildStatus::ShouldBuild(Meta { stamp, res, out_dir, root: root.into() })
193}
194
195/// 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];
202
203/// 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::MissingUpstream
211    }
212}
213
214/// 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 LLVM
217/// 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 tools
223    // (since others may not have CI artifacts)
224    // https://doc.rust-lang.org/rustc/platform-support.html#tier-1
225    let supported_platforms = [
226        // tier 1
227        ("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 tools
237        ("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    ];
258
259    if !supported_platforms.contains(&(&*host_target.triple, asserts))
260        && (asserts || !supported_platforms.contains(&(&*host_target.triple, true)))
261    {
262        return false;
263    }
264
265    true
266}
267
268#[derive(Debug, Clone, Hash, PartialEq, Eq)]
269pub struct Llvm {
270    pub target: TargetSelection,
271}
272
273impl Step for Llvm {
274    type Output = LlvmResult;
275
276    const IS_HOST: bool = true;
277
278    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
279        run.path("src/llvm-project").path("src/llvm-project/llvm")
280    }
281
282    fn make_run(run: RunConfig<'_>) {
283        run.builder.ensure(Llvm { target: run.target });
284    }
285
286    /// 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();
293
294            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        };
302
303        // 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        };
308
309        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        }
312
313        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));
317
318        // https://llvm.org/docs/CMake.html
319        let mut cfg = cmake::Config::new(builder.src.join(root));
320        let mut ldflags = LdFlags::default();
321
322        let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
323            (false, _) => "Debug",
324            (true, false) => "Release",
325            (true, true) => "RelWithDebInfo",
326        };
327
328        // NOTE: remember to also update `bootstrap.example.toml` when changing the
329        // 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        };
337
338        let llvm_exp_targets = match builder.config.llvm_experimental_targets {
339            Some(ref s) => s,
340            None => "AVR;M68k;CSKY;Xtensa",
341        };
342
343        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" };
347
348        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);
366
367        // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
368        // `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");
371
372        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        }
382
383        // 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        }
389
390        // 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        }
401
402        // This setting makes the LLVM tools link to the dynamic LLVM library,
403        // which saves both memory during parallel links and overall disk space
404        // for the tools. We don't do this on every platform as it doesn't work
405        // equally well everywhere.
406        if builder.llvm_link_shared() {
407            cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
408        }
409
410        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 against
418            // `libatomic` when using 1-byte and 2-byte C++
419            // atomics but the LLVM build system check cannot
420            // detect this. Therefore it is set manually here.
421            // Some BSD uses Clang as its system compiler and
422            // provides no libatomic in its base system so does
423            // not want this. 32-bit SPARC requires linking against
424            // libatomic as well.
425            ldflags.exe.push(" -latomic");
426            ldflags.shared.push(" -latomic");
427        }
428
429        if target.starts_with("mips") && target.contains("netbsd") {
430            // LLVM wants 64-bit atomics, while mipsel is 32-bit only, so needs -latomic
431            ldflags.exe.push(" -latomic");
432            ldflags.shared.push(" -latomic");
433        }
434
435        if target.starts_with("arm64ec") {
436            // MSVC linker requires the -machine:arm64ec flag to be passed to
437            // know it's linking as Arm64EC (vs Arm64X).
438            ldflags.exe.push(" -machine:arm64ec");
439            ldflags.shared.push(" -machine:arm64ec");
440        }
441
442        if target.is_msvc() {
443            cfg.define("CMAKE_MSVC_RUNTIME_LIBRARY", "MultiThreaded");
444            cfg.static_crt(true);
445        }
446
447        if target.starts_with("i686") {
448            cfg.define("LLVM_BUILD_32_BITS", "ON");
449        }
450
451        if target.starts_with("x86_64") && target.contains("ohos") {
452            cfg.define("LLVM_TOOL_LLVM_RTDYLD_BUILD", "OFF");
453        }
454
455        let mut enabled_llvm_projects = Vec::new();
456
457        if helpers::forcing_clang_based_tests() {
458            enabled_llvm_projects.push("clang");
459        }
460
461        if builder.config.llvm_polly {
462            enabled_llvm_projects.push("polly");
463        }
464
465        if builder.config.llvm_clang {
466            enabled_llvm_projects.push("clang");
467        }
468
469        // We want libxml to be disabled.
470        // See https://github.com/rust-lang/rust/pull/50104
471        cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
472
473        let mut enabled_llvm_runtimes = Vec::new();
474
475        if helpers::forcing_clang_based_tests() {
476            enabled_llvm_runtimes.push("compiler-rt");
477        }
478
479        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        }
484
485        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        }
490
491        if let Some(num_linkers) = builder.config.llvm_link_jobs
492            && num_linkers > 0
493        {
494            cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
495        }
496
497        // https://llvm.org/docs/HowToCrossCompileLLVM.html
498        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 MSVC
513                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        }
526
527        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 rustc
533            // 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        }
541
542        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
543        configure_llvm(builder, target, &mut cfg);
544
545        for (key, val) in &builder.config.llvm_build_config {
546            cfg.define(key, val);
547        }
548
549        if builder.config.dry_run() {
550            return res;
551        }
552
553        cfg.build();
554
555        // 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        };
563
564        // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
565        // libLLVM.dylib will be built. However, llvm-config will still look
566        // for a versioned path like libLLVM-14.dylib. Manually create a symbolic
567        // 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        }
575
576        // 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 to
578        // 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_optimize
581            && !builder.config.llvm_release_debuginfo
582        {
583            // Find the name of the LLVM shared library that we just built.
584            let lib_name = find_llvm_lib_name("so");
585
586            // If the shared library exists in LLVM's `/build/lib/` or `/lib/` folders, strip its
587            // 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        }
599
600        t!(stamp.write());
601
602        res
603    }
604
605    fn metadata(&self) -> Option<StepMetadata> {
606        Some(StepMetadata::build("llvm", self.target))
607    }
608}
609
610pub 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}
619
620pub 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}
625
626fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
627    if builder.config.dry_run() {
628        return;
629    }
630
631    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 >= 21
635    {
636        return;
637    }
638    panic!("\n\nbad LLVM version: {version}, need >=21\n\n")
639}
640
641fn 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");
653
654    if builder.config.quiet {
655        // Only log errors and warnings from `cmake`.
656        cfg.define("CMAKE_MESSAGE_LOG_LEVEL", "WARNING");
657
658        // If we're configuring llvm to build with `ninja`, we can suppress output from it with
659        // `--quiet`. Otherwise don't add anything since we don't know which build system is going
660        // to use.
661        if builder.ninja() {
662            cfg.build_arg("--quiet");
663        }
664    }
665
666    // Do not allow the user's value of DESTDIR to influence where
667    // LLVM will install itself. LLVM must always be installed in our
668    // own build directories.
669    cfg.env("DESTDIR", "");
670
671    if builder.ninja() {
672        cfg.generator("Ninja");
673    }
674    cfg.target(&target.triple).host(&builder.config.host_target.triple);
675
676    if !builder.config.is_host_target(target) {
677        cfg.define("CMAKE_CROSSCOMPILING", "True");
678
679        // 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            // macOS
702            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 branch
713            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, and
719            // to avoid CMAKE_SYSTEM_NAME being inferred from the host.
720            cfg.define("CMAKE_SYSTEM_NAME", "Generic");
721        }
722
723        // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
724        // that case like CMake we cannot easily determine system version either.
725        //
726        // Since, the LLVM itself makes rather limited use of version checks in
727        // CMakeFiles (and then only in tests), and so far no issues have been
728        // reported, the system version is currently left unset.
729
730        if target.contains("apple") {
731            if !target.contains("darwin") {
732                // FIXME(madsmtm): compiler-rt's CMake setup is kinda weird, it seems like they do
733                // 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");
737
738                // 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            }
742
743            // 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 arm64
747                cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
748            } else if target.starts_with("i686") {
749                // macOS uses a different name for building i386
750                cfg.define("CMAKE_OSX_ARCHITECTURES", "i386");
751            } else {
752                cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
753            }
754        }
755    }
756
757    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    };
764
765    // MSVC with CMake uses msbuild by default which doesn't respect these
766    // vars that we'd otherwise configure. In that case we just skip this
767    // entirely.
768    if target.is_msvc() && !builder.ninja() {
769        return;
770    }
771
772    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    };
776
777    // If ccache is configured we inform the build a little differently how
778    // 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));
786
787    // If we are running under a FIFO jobserver, we should not pass -j to CMake; otherwise it
788    // 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);
792
793    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 passing
798    // our flags via `.cflag`/`.cxxflag` instead.
799    //
800    // Needs `suppressed_compiler_flag_prefixes` to be gone, and hence
801    // https://github.com/llvm/llvm-project/issues/88780 to be fixed.
802    for flag in builder
803        .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 builder
824        .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_prefixes
829                .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    }
846
847    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 it
852        // tries to resolve this path in the LLVM build directory.
853        cfg.define("CMAKE_AR", sanitize_cc(&ar));
854    }
855
856    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 it
860        // tries to resolve this path in the LLVM build directory.
861        cfg.define("CMAKE_RANLIB", sanitize_cc(&ranlib));
862    }
863
864    if let Some(ref flags) = builder.config.llvm_ldflags {
865        ldflags.push_all(flags);
866    }
867
868    if let Some(flags) = get_var("LDFLAGS", &builder.config.host_target.triple, &target.triple) {
869        ldflags.push_all(&flags);
870    }
871
872    // 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_stdcpp
875        && !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    }
885
886    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);
889
890    if env::var_os("SCCACHE_ERROR_LOG").is_some() {
891        cfg.env("RUSTC_LOG", "sccache=warn");
892    }
893}
894
895fn 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    }
904
905    // 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    }
912
913    if let Some(ref linker) = builder.config.llvm_use_linker {
914        cfg.define("LLVM_USE_LINKER", linker);
915    }
916
917    if builder.config.llvm_allow_old_toolchain {
918        cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
919    }
920}
921
922// Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
923fn 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}
931
932#[derive(Clone)]
933pub struct BuiltOmpOffload {
934    /// Path to the omp and offload dylibs.
935    offload: Vec<PathBuf>,
936}
937
938impl BuiltOmpOffload {
939    pub fn offload_paths(&self) -> Vec<PathBuf> {
940        self.offload.clone()
941    }
942}
943
944// FIXME(offload): In an ideal world, we would just enable the offload runtime in our previous LLVM
945// build step. For now, we still depend on the openmp runtime since we use some of it's API, so we
946// build both. However, when building those runtimes as part of the LLVM step, then LLVM's cmake
947// implicitly assumes that Clang has also been build and will try to use it. In the Rust CI, we
948// 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 the
950// future we might be able to integrate this step into the LLVM step. For now, we instead introduce
951// a Clang_DIR bootstrap option, which allows us tell CMake to use an external clang for these two
952// runtimes. This external clang will try to use it's own (older) include dirs when building our
953// in-tree LLVM submodule, which will cause build failures. To prevent those, we now also
954// explicitly set our include dirs.
955#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
956pub struct OmpOffload {
957    pub target: TargetSelection,
958}
959
960impl Step for OmpOffload {
961    type Output = BuiltOmpOffload;
962    const IS_HOST: bool = true;
963
964    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
965        run.path("src/llvm-project/offload")
966    }
967
968    fn make_run(run: RunConfig<'_>) {
969        run.builder.ensure(OmpOffload { target: run.target });
970    }
971
972    /// 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;
981
982        let LlvmResult { host_llvm_config, llvm_cmake_dir } =
983            builder.ensure(Llvm { target: self.target });
984
985        // Running cmake twice in the same folder is known to cause issues, like deleting existing
986        // binaries. We therefore write our offload artifacts into it's own folder, instead of
987        // using the llvm build dir.
988        let out_dir = builder.offload_out(target);
989
990        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));
995
996        // 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);
1006
1007        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        }
1022
1023        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));
1028
1029        builder.config.update_submodule("src/llvm-project");
1030
1031        // OpenMP/Offload builds currently (LLVM-22) still depend on Clang, although there are
1032        // intentions to loosen this requirement over time. FIXME(offload): re-evaluate on LLVM 23
1033        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 clang
1039            None
1040        };
1041
1042        // 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, since
1044        // 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/"));
1048
1049            // If we use an external clang as opposed to building our own llvm_clang, than that clang will
1050            // come with it's own set of default include directories, which are based on a potentially older
1051            // LLVM. This can cause issues, so we overwrite it to include headers based on our
1052            // `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            }
1060
1061            configure_cmake(builder, target, &mut cfg, true, LdFlags::default(), cflags, &[]);
1062
1063            // Re-use the same flags as llvm to control the level of debug information
1064            // 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);
1072
1073            // FIXME(offload): Once we move from OMP to Offload (Ol) APIs, we should drop the openmp
1074            // 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            }
1087
1088            // We don't perform a full cross-compilation of rustc, therefore our target.triple
1089            // 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        }
1102
1103        t!(stamp.write());
1104
1105        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}
1119
1120#[derive(Clone)]
1121pub struct BuiltEnzyme {
1122    /// Path to the libEnzyme dylib.
1123    enzyme: PathBuf,
1124}
1125
1126impl 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}
1134
1135#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1136pub struct Enzyme {
1137    pub target: TargetSelection,
1138}
1139
1140impl Step for Enzyme {
1141    type Output = BuiltEnzyme;
1142    const IS_HOST: bool = true;
1143
1144    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1145        run.path("src/tools/enzyme/enzyme")
1146    }
1147
1148    fn make_run(run: RunConfig<'_>) {
1149        run.builder.ensure(Enzyme { target: run.target });
1150    }
1151
1152    /// 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;
1159
1160        if builder.config.dry_run() {
1161            return BuiltEnzyme { enzyme: builder.config.tempdir().join("enzyme-dryrun") };
1162        }
1163
1164        let LlvmResult { host_llvm_config, llvm_cmake_dir } = builder.ensure(Llvm { target });
1165
1166        // Enzyme links against LLVM. If we update the LLVM submodule libLLVM might get a new
1167        // version number, in which case Enzyme will now fail to find LLVM. By including the LLVM
1168        // 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();
1171
1172        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        });
1180
1181        let out_dir = builder.enzyme_out(target);
1182        let stamp = BuildStamp::new(&out_dir).with_prefix("enzyme").add_stamp(smart_stamp_hash);
1183
1184        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);
1189
1190        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        }
1205
1206        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        }
1212
1213        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));
1218
1219        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 about
1221        // to turn into a hard error. As such, Enzyme generates various warnings which could make it
1222        // hard to spot more relevant issues.
1223        let mut cflags = CcFlags::default();
1224        cflags.push_all("-Wno-deprecated");
1225
1226        // 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        }
1233
1234        configure_cmake(builder, target, &mut cfg, true, ldflags, cflags, &[]);
1235
1236        // Re-use the same flags as llvm to control the level of debug information
1237        // 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);
1245
1246        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);
1253
1254        cfg.build();
1255
1256        // 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        }
1265
1266        t!(stamp.write());
1267        BuiltEnzyme { enzyme: dylib }
1268    }
1269}
1270
1271#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1272pub struct Lld {
1273    pub target: TargetSelection,
1274}
1275
1276impl Step for Lld {
1277    type Output = PathBuf;
1278    const IS_HOST: bool = true;
1279
1280    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1281        run.path("src/llvm-project/lld")
1282    }
1283
1284    fn make_run(run: RunConfig<'_>) {
1285        run.builder.ensure(Lld { target: run.target });
1286    }
1287
1288    /// 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;
1294
1295        let LlvmResult { host_llvm_config, llvm_cmake_dir } = builder.ensure(Llvm { target });
1296
1297        // The `dist` step packages LLD next to LLVM's binaries for download-ci-llvm. The root path
1298        // 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 to
1300        // `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 the
1306                // `bin` subfolder of this step's out dir.
1307                return ci_llvm_bin.parent().unwrap().to_path_buf();
1308            }
1309        }
1310
1311        let out_dir = builder.lld_out(target);
1312
1313        let lld_stamp = BuildStamp::new(&out_dir).with_prefix("lld");
1314        if lld_stamp.path().exists() {
1315            return out_dir;
1316        }
1317
1318        let _guard = builder.msg_unstaged(Kind::Build, "LLD", target);
1319        let _time = helpers::timeit(builder);
1320        t!(fs::create_dir_all(&out_dir));
1321
1322        let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
1323        let mut ldflags = LdFlags::default();
1324
1325        // When building LLD as part of a build with instrumentation on windows, for example
1326        // when doing PGO on CI, cmake or clang-cl don't automatically link clang's
1327        // profiler runtime in. In that case, we need to manually ask cmake to do it, to avoid
1328        // linking errors, much like LLVM's cmake setup does in that situation.
1329        if builder.config.llvm_profile_generate
1330            && 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 the
1334            // 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        }
1338
1339        // 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` it
1343        // needs is distributed at "$root/lib". The default rpath of "$ORIGIN/../lib" points at the
1344        // 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 that
1347        // component installed, one can successfully invoke `rust-lld` directly without rustup's
1348        // `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 the
1356            // 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 to
1360            // cmake.
1361            ldflags.push_all("-Wl,-rpath,'$ORIGIN/../../../'");
1362        }
1363
1364        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
1365        configure_llvm(builder, target, &mut cfg);
1366
1367        // Re-use the same flags as llvm to control the level of debug information
1368        // 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        };
1374
1375        cfg.out_dir(&out_dir)
1376            .profile(profile)
1377            .define("LLVM_CMAKE_DIR", llvm_cmake_dir)
1378            .define("LLVM_INCLUDE_TESTS", "OFF");
1379
1380        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        }
1387
1388        cfg.build();
1389
1390        t!(lld_stamp.write());
1391        out_dir
1392    }
1393}
1394
1395#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1396pub struct Sanitizers {
1397    pub target: TargetSelection,
1398}
1399
1400impl Step for Sanitizers {
1401    type Output = Vec<SanitizerRuntime>;
1402
1403    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1404        run.alias("sanitizers")
1405    }
1406
1407    fn make_run(run: RunConfig<'_>) {
1408        run.builder.ensure(Sanitizers { target: run.target });
1409    }
1410
1411    /// 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        }
1417
1418        let out_dir = builder.native_dir(self.target).join("sanitizers");
1419        let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
1420
1421        if builder.config.dry_run() || runtimes.is_empty() {
1422            return runtimes;
1423        }
1424
1425        let LlvmResult { host_llvm_config, .. } =
1426            builder.ensure(Llvm { target: builder.config.host_target });
1427
1428        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        });
1436
1437        let stamp = BuildStamp::new(&out_dir).with_prefix("sanitizers").add_stamp(smart_stamp_hash);
1438
1439        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            }
1446
1447            return runtimes;
1448        }
1449
1450        let _guard = builder.msg_unstaged(Kind::Build, "sanitizers", self.target);
1451        t!(stamp.remove());
1452        let _time = helpers::timeit(builder);
1453
1454        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);
1466
1467        if self.target.contains("ohos") {
1468            cfg.define("COMPILER_RT_USE_BUILTINS_LIBRARY", "ON");
1469        }
1470
1471        // 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 default
1476        // flags on MacOS. A long-standing bug in the CMake rules for compiler-rt
1477        // causes architecture detection to be skipped when this flag is present,
1478        // and compilation fails. https://github.com/llvm/llvm-project/issues/88780
1479        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        );
1490
1491        t!(fs::create_dir_all(&out_dir));
1492        cfg.out_dir(out_dir);
1493
1494        for runtime in &runtimes {
1495            cfg.build_target(&runtime.cmake_target);
1496            cfg.build();
1497        }
1498        t!(stamp.write());
1499
1500        runtimes
1501    }
1502}
1503
1504#[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}
1513
1514/// 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        components
1522            .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    };
1530
1531    let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1532        components
1533            .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    };
1541
1542    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}
1590
1591#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1592pub struct CrtBeginEnd {
1593    pub target: TargetSelection,
1594}
1595
1596impl Step for CrtBeginEnd {
1597    type Output = PathBuf;
1598
1599    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1600        run.path("src/llvm-project/compiler-rt/lib/crt")
1601    }
1602
1603    fn make_run(run: RunConfig<'_>) {
1604        if run.target.needs_crt_begin_end() {
1605            run.builder.ensure(CrtBeginEnd { target: run.target });
1606        }
1607    }
1608
1609    /// 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        );
1615
1616        let out_dir = builder.native_dir(self.target).join("crt");
1617
1618        if builder.config.dry_run() {
1619            return out_dir;
1620        }
1621
1622        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        }
1629
1630        let _guard = builder.msg_unstaged(Kind::Build, "crtbegin.o and crtend.o", self.target);
1631        t!(fs::create_dir_all(&out_dir));
1632
1633        let mut cfg = cc::Build::new();
1634
1635        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);
1648
1649        // Those flags are defined in src/llvm-project/compiler-rt/lib/builtins/CMakeLists.txt
1650        // Currently only consumer of those objects is musl, which use .init_array/.fini_array
1651        // instead of .ctors/.dtors
1652        cfg.flag("-std=c11")
1653            .define("CRT_HAS_INITFINI_ARRAY", None)
1654            .define("EH_USE_FRAME_REGISTRY", None);
1655
1656        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        }
1664
1665        out_dir
1666    }
1667}
1668
1669#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1670pub struct Libunwind {
1671    pub target: TargetSelection,
1672}
1673
1674impl Step for Libunwind {
1675    type Output = PathBuf;
1676
1677    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1678        run.path("src/llvm-project/libunwind")
1679    }
1680
1681    fn make_run(run: RunConfig<'_>) {
1682        run.builder.ensure(Libunwind { target: run.target });
1683    }
1684
1685    /// Build libunwind.a
1686    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        );
1691
1692        if builder.config.dry_run() {
1693            return PathBuf::new();
1694        }
1695
1696        let out_dir = builder.native_dir(self.target).join("libunwind");
1697        let root = builder.src.join("src/llvm-project/libunwind");
1698
1699        if up_to_date(&root, &out_dir.join("libunwind.a")) {
1700            return out_dir;
1701        }
1702
1703        let _guard = builder.msg_unstaged(Kind::Build, "libunwind.a", self.target);
1704        t!(fs::create_dir_all(&out_dir));
1705
1706        let mut cc_cfg = cc::Build::new();
1707        let mut cpp_cfg = cc::Build::new();
1708
1709        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");
1715
1716        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);
1734
1735            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");
1740
1741                // easiest way to undefine since no API available in cc::Build to undefine
1742                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        }
1754
1755        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        }
1761
1762        // Don't set this for clang
1763        // 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        }
1772
1773        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 the
1775            // 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        }
1782
1783        let mut c_sources = vec![
1784            "Unwind-sjlj.c",
1785            "UnwindLevel1-gcc-ext.c",
1786            "UnwindLevel1.c",
1787            "UnwindRegistersRestore.S",
1788            "UnwindRegistersSave.S",
1789        ];
1790
1791        let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1792        let cpp_len = cpp_sources.len();
1793
1794        if self.target.contains("x86_64-fortanix-unknown-sgx") {
1795            c_sources.push("UnwindRustSgx.c");
1796        }
1797
1798        for src in c_sources {
1799            cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1800        }
1801
1802        for src in &cpp_sources {
1803            cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1804        }
1805
1806        cpp_cfg.compile("unwind-cpp");
1807
1808        // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1809        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:?}");
1826
1827        cc_cfg.compile("unwind");
1828        out_dir
1829    }
1830}