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, 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        // FIXME(ZuseZ4): Do we need that for Enzyme too?
565        // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
566        // libLLVM.dylib will be built. However, llvm-config will still look
567        // for a versioned path like libLLVM-14.dylib. Manually create a symbolic
568        // link to make llvm-config happy.
569        if builder.llvm_link_shared() && target.contains("apple-darwin") {
570            let lib_name = find_llvm_lib_name("dylib");
571            let lib_llvm = out_dir.join("build").join("lib").join(lib_name);
572            if !lib_llvm.exists() {
573                t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));
574            }
575        }
576
577        // When building LLVM as a shared library on linux, it can contain unexpected debuginfo:
578        // some can come from the C++ standard library. Unless we're explicitly requesting LLVM to
579        // be built with debuginfo, strip it away after the fact, to make dist artifacts smaller.
580        if builder.llvm_link_shared()
581            && builder.config.llvm_optimize
582            && !builder.config.llvm_release_debuginfo
583        {
584            // Find the name of the LLVM shared library that we just built.
585            let lib_name = find_llvm_lib_name("so");
586
587            // If the shared library exists in LLVM's `/build/lib/` or `/lib/` folders, strip its
588            // debuginfo.
589            crate::core::build_steps::compile::strip_debug(
590                builder,
591                target,
592                &out_dir.join("lib").join(&lib_name),
593            );
594            crate::core::build_steps::compile::strip_debug(
595                builder,
596                target,
597                &out_dir.join("build").join("lib").join(&lib_name),
598            );
599        }
600
601        t!(stamp.write());
602
603        res
604    }
605
606    fn metadata(&self) -> Option<StepMetadata> {
607        Some(StepMetadata::build("llvm", self.target))
608    }
609}
610
611pub fn get_llvm_version(builder: &Builder<'_>, llvm_config: &Path) -> String {
612    command(llvm_config)
613        .arg("--version")
614        .cached()
615        .run_capture_stdout(builder)
616        .stdout()
617        .trim()
618        .to_owned()
619}
620
621pub fn get_llvm_version_major(builder: &Builder<'_>, llvm_config: &Path) -> u8 {
622    let version = get_llvm_version(builder, llvm_config);
623    let major_str = version.split_once('.').expect("Failed to parse LLVM version").0;
624    major_str.parse().unwrap()
625}
626
627fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
628    if builder.config.dry_run() {
629        return;
630    }
631
632    let version = get_llvm_version(builder, llvm_config);
633    let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
634    if let (Some(major), Some(_minor)) = (parts.next(), parts.next())
635        && major >= 20
636    {
637        return;
638    }
639    panic!("\n\nbad LLVM version: {version}, need >=20\n\n")
640}
641
642fn configure_cmake(
643    builder: &Builder<'_>,
644    target: TargetSelection,
645    cfg: &mut cmake::Config,
646    use_compiler_launcher: bool,
647    mut ldflags: LdFlags,
648    ccflags: CcFlags,
649    suppressed_compiler_flag_prefixes: &[&str],
650) {
651    // Do not print installation messages for up-to-date files.
652    // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
653    cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
654
655    // Do not allow the user's value of DESTDIR to influence where
656    // LLVM will install itself. LLVM must always be installed in our
657    // own build directories.
658    cfg.env("DESTDIR", "");
659
660    if builder.ninja() {
661        cfg.generator("Ninja");
662    }
663    cfg.target(&target.triple).host(&builder.config.host_target.triple);
664
665    if !builder.config.is_host_target(target) {
666        cfg.define("CMAKE_CROSSCOMPILING", "True");
667
668        // NOTE: Ideally, we wouldn't have to do this, and `cmake-rs` would just handle it for us.
669        // But it currently determines this based on the `CARGO_CFG_TARGET_OS` environment variable,
670        // which isn't set when compiling outside `build.rs` (like bootstrap is).
671        //
672        // So for now, we define `CMAKE_SYSTEM_NAME` ourselves, to panicking in `cmake-rs`.
673        if target.contains("netbsd") {
674            cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
675        } else if target.contains("dragonfly") {
676            cfg.define("CMAKE_SYSTEM_NAME", "DragonFly");
677        } else if target.contains("openbsd") {
678            cfg.define("CMAKE_SYSTEM_NAME", "OpenBSD");
679        } else if target.contains("freebsd") {
680            cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
681        } else if target.is_windows() {
682            cfg.define("CMAKE_SYSTEM_NAME", "Windows");
683        } else if target.contains("haiku") {
684            cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
685        } else if target.contains("solaris") || target.contains("illumos") {
686            cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
687        } else if target.contains("linux") {
688            cfg.define("CMAKE_SYSTEM_NAME", "Linux");
689        } else if target.contains("darwin") {
690            // macOS
691            cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
692        } else if target.contains("ios") {
693            cfg.define("CMAKE_SYSTEM_NAME", "iOS");
694        } else if target.contains("tvos") {
695            cfg.define("CMAKE_SYSTEM_NAME", "tvOS");
696        } else if target.contains("visionos") {
697            cfg.define("CMAKE_SYSTEM_NAME", "visionOS");
698        } else if target.contains("watchos") {
699            cfg.define("CMAKE_SYSTEM_NAME", "watchOS");
700        } else if target.contains("none") {
701            // "none" should be the last branch
702            cfg.define("CMAKE_SYSTEM_NAME", "Generic");
703        } else {
704            builder.info(&format!(
705                "could not determine CMAKE_SYSTEM_NAME from the target `{target}`, build may fail",
706            ));
707            // Fallback, set `CMAKE_SYSTEM_NAME` anyhow to avoid the logic `cmake-rs` tries, and
708            // to avoid CMAKE_SYSTEM_NAME being inferred from the host.
709            cfg.define("CMAKE_SYSTEM_NAME", "Generic");
710        }
711
712        // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
713        // that case like CMake we cannot easily determine system version either.
714        //
715        // Since, the LLVM itself makes rather limited use of version checks in
716        // CMakeFiles (and then only in tests), and so far no issues have been
717        // reported, the system version is currently left unset.
718
719        if target.contains("apple") {
720            if !target.contains("darwin") {
721                // FIXME(madsmtm): compiler-rt's CMake setup is kinda weird, it seems like they do
722                // version testing etc. for macOS (i.e. Darwin), even while building for iOS?
723                //
724                // So for now we set it to "Darwin" on all Apple platforms.
725                cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
726
727                // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
728                cfg.define("CMAKE_OSX_SYSROOT", "/");
729                cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
730            }
731
732            // Make sure that CMake does not build universal binaries on macOS.
733            // Explicitly specify the one single target architecture.
734            if target.starts_with("aarch64") {
735                // macOS uses a different name for building arm64
736                cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
737            } else if target.starts_with("i686") {
738                // macOS uses a different name for building i386
739                cfg.define("CMAKE_OSX_ARCHITECTURES", "i386");
740            } else {
741                cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
742            }
743        }
744    }
745
746    let sanitize_cc = |cc: &Path| {
747        if target.is_msvc() {
748            OsString::from(cc.to_str().unwrap().replace('\\', "/"))
749        } else {
750            cc.as_os_str().to_owned()
751        }
752    };
753
754    // MSVC with CMake uses msbuild by default which doesn't respect these
755    // vars that we'd otherwise configure. In that case we just skip this
756    // entirely.
757    if target.is_msvc() && !builder.ninja() {
758        return;
759    }
760
761    let (cc, cxx) = match builder.config.llvm_clang_cl {
762        Some(ref cl) => (cl.into(), cl.into()),
763        None => (builder.cc(target), builder.cxx(target).unwrap()),
764    };
765
766    // If ccache is configured we inform the build a little differently how
767    // to invoke ccache while also invoking our compilers.
768    if use_compiler_launcher && let Some(ref ccache) = builder.config.ccache {
769        cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
770            .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
771    }
772    cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
773        .define("CMAKE_CXX_COMPILER", sanitize_cc(&cxx))
774        .define("CMAKE_ASM_COMPILER", sanitize_cc(&cc));
775
776    cfg.build_arg("-j").build_arg(builder.jobs().to_string());
777    let mut cflags = ccflags.cflags.clone();
778    // FIXME(madsmtm): Allow `cmake-rs` to select flags by itself by passing
779    // our flags via `.cflag`/`.cxxflag` instead.
780    //
781    // Needs `suppressed_compiler_flag_prefixes` to be gone, and hence
782    // https://github.com/llvm/llvm-project/issues/88780 to be fixed.
783    for flag in builder
784        .cc_handled_clags(target, CLang::C)
785        .into_iter()
786        .chain(builder.cc_unhandled_cflags(target, GitRepo::Llvm, CLang::C))
787        .filter(|flag| !suppressed_compiler_flag_prefixes.iter().any(|p| flag.starts_with(p)))
788    {
789        cflags.push(" ");
790        cflags.push(flag);
791    }
792    if let Some(ref s) = builder.config.llvm_cflags {
793        cflags.push(" ");
794        cflags.push(s);
795    }
796    if target.contains("ohos") {
797        cflags.push(" -D_LINUX_SYSINFO_H");
798    }
799    if builder.config.llvm_clang_cl.is_some() {
800        cflags.push(format!(" --target={target}"));
801    }
802    cfg.define("CMAKE_C_FLAGS", cflags);
803    let mut cxxflags = ccflags.cxxflags.clone();
804    for flag in builder
805        .cc_handled_clags(target, CLang::Cxx)
806        .into_iter()
807        .chain(builder.cc_unhandled_cflags(target, GitRepo::Llvm, CLang::Cxx))
808        .filter(|flag| {
809            !suppressed_compiler_flag_prefixes
810                .iter()
811                .any(|suppressed_prefix| flag.starts_with(suppressed_prefix))
812        })
813    {
814        cxxflags.push(" ");
815        cxxflags.push(flag);
816    }
817    if let Some(ref s) = builder.config.llvm_cxxflags {
818        cxxflags.push(" ");
819        cxxflags.push(s);
820    }
821    if target.contains("ohos") {
822        cxxflags.push(" -D_LINUX_SYSINFO_H");
823    }
824    if builder.config.llvm_clang_cl.is_some() {
825        cxxflags.push(format!(" --target={target}"));
826    }
827
828    cfg.define("CMAKE_CXX_FLAGS", cxxflags);
829    if let Some(ar) = builder.ar(target)
830        && ar.is_absolute()
831    {
832        // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
833        // tries to resolve this path in the LLVM build directory.
834        cfg.define("CMAKE_AR", sanitize_cc(&ar));
835    }
836
837    if let Some(ranlib) = builder.ranlib(target)
838        && ranlib.is_absolute()
839    {
840        // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
841        // tries to resolve this path in the LLVM build directory.
842        cfg.define("CMAKE_RANLIB", sanitize_cc(&ranlib));
843    }
844
845    if let Some(ref flags) = builder.config.llvm_ldflags {
846        ldflags.push_all(flags);
847    }
848
849    if let Some(flags) = get_var("LDFLAGS", &builder.config.host_target.triple, &target.triple) {
850        ldflags.push_all(&flags);
851    }
852
853    // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
854    // We also do this if the user explicitly requested static libstdc++.
855    if builder.config.llvm_static_stdcpp
856        && !target.is_msvc()
857        && !target.contains("netbsd")
858        && !target.contains("solaris")
859    {
860        if target.contains("apple") || target.is_windows() {
861            ldflags.push_all("-static-libstdc++");
862        } else {
863            ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
864        }
865    }
866
867    cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
868    cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
869    cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
870
871    if env::var_os("SCCACHE_ERROR_LOG").is_some() {
872        cfg.env("RUSTC_LOG", "sccache=warn");
873    }
874}
875
876fn configure_llvm(builder: &Builder<'_>, target: TargetSelection, cfg: &mut cmake::Config) {
877    // ThinLTO is only available when building with LLVM, enabling LLD is required.
878    // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
879    if builder.config.llvm_thin_lto {
880        cfg.define("LLVM_ENABLE_LTO", "Thin");
881        if !target.contains("apple") {
882            cfg.define("LLVM_ENABLE_LLD", "ON");
883        }
884    }
885
886    // Libraries for ELF section compression.
887    if builder.config.llvm_libzstd {
888        cfg.define("LLVM_ENABLE_ZSTD", "FORCE_ON");
889        cfg.define("LLVM_USE_STATIC_ZSTD", "TRUE");
890    } else {
891        cfg.define("LLVM_ENABLE_ZSTD", "OFF");
892    }
893
894    if let Some(ref linker) = builder.config.llvm_use_linker {
895        cfg.define("LLVM_USE_LINKER", linker);
896    }
897
898    if builder.config.llvm_allow_old_toolchain {
899        cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
900    }
901}
902
903// Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
904fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
905    let kind = if host == target { "HOST" } else { "TARGET" };
906    let target_u = target.replace('-', "_");
907    env::var_os(format!("{var_base}_{target}"))
908        .or_else(|| env::var_os(format!("{var_base}_{target_u}")))
909        .or_else(|| env::var_os(format!("{kind}_{var_base}")))
910        .or_else(|| env::var_os(var_base))
911}
912
913#[derive(Clone)]
914pub struct BuiltOmpOffload {
915    /// Path to the omp and offload dylibs.
916    offload: Vec<PathBuf>,
917}
918
919impl BuiltOmpOffload {
920    pub fn offload_paths(&self) -> Vec<PathBuf> {
921        self.offload.clone()
922    }
923}
924
925// FIXME(offload): In an ideal world, we would just enable the offload runtime in our previous LLVM
926// build step. For now, we still depend on the openmp runtime since we use some of it's API, so we
927// build both. However, when building those runtimes as part of the LLVM step, then LLVM's cmake
928// implicitly assumes that Clang has also been build and will try to use it. In the Rust CI, we
929// don't always build clang (due to compile times), but instead use a slightly older external clang.
930// LLVM tries to remove this build dependency of offload/openmp on Clang for LLVM-22, so in the
931// future we might be able to integrate this step into the LLVM step. For now, we instead introduce
932// a Clang_DIR bootstrap option, which allows us tell CMake to use an external clang for these two
933// runtimes. This external clang will try to use it's own (older) include dirs when building our
934// in-tree LLVM submodule, which will cause build failures. To prevent those, we now also
935// explicitly set our include dirs.
936#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
937pub struct OmpOffload {
938    pub target: TargetSelection,
939}
940
941impl Step for OmpOffload {
942    type Output = BuiltOmpOffload;
943    const IS_HOST: bool = true;
944
945    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
946        run.path("src/llvm-project/offload")
947    }
948
949    fn make_run(run: RunConfig<'_>) {
950        run.builder.ensure(OmpOffload { target: run.target });
951    }
952
953    /// Compile OpenMP offload runtimes for `target`.
954    #[allow(unused)]
955    fn run(self, builder: &Builder<'_>) -> Self::Output {
956        if builder.config.dry_run() {
957            return BuiltOmpOffload {
958                offload: vec![builder.config.tempdir().join("llvm-offload-dry-run")],
959            };
960        }
961        let target = self.target;
962
963        let LlvmResult { host_llvm_config, llvm_cmake_dir } =
964            builder.ensure(Llvm { target: self.target });
965
966        // Running cmake twice in the same folder is known to cause issues, like deleting existing
967        // binaries. We therefore write our offload artifacts into it's own folder, instead of
968        // using the llvm build dir.
969        let out_dir = builder.offload_out(target);
970
971        let mut files = vec![];
972        let lib_ext = std::env::consts::DLL_EXTENSION;
973        files.push(out_dir.join("lib").join("libLLVMOffload").with_extension(lib_ext));
974        files.push(out_dir.join("lib").join("libomp").with_extension(lib_ext));
975        files.push(out_dir.join("lib").join("libomptarget").with_extension(lib_ext));
976
977        // Offload/OpenMP are just subfolders of LLVM, so we can use the LLVM sha.
978        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
979        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
980            generate_smart_stamp_hash(
981                builder,
982                &builder.config.src.join("src/llvm-project/offload"),
983                builder.in_tree_llvm_info.sha().unwrap_or_default(),
984            )
985        });
986        let stamp = BuildStamp::new(&out_dir).with_prefix("offload").add_stamp(smart_stamp_hash);
987
988        trace!("checking build stamp to see if we need to rebuild offload/openmp artifacts");
989        if stamp.is_up_to_date() {
990            trace!(?out_dir, "offload/openmp build artifacts are up to date");
991            if stamp.stamp().is_empty() {
992                builder.info(
993                    "Could not determine the Offload submodule commit hash. \
994                     Assuming that an Offload rebuild is not necessary.",
995                );
996                builder.info(&format!(
997                    "To force Offload/OpenMP to rebuild, remove the file `{}`",
998                    stamp.path().display()
999                ));
1000            }
1001            return BuiltOmpOffload { offload: files };
1002        }
1003
1004        trace!(?target, "(re)building offload/openmp artifacts");
1005        builder.info(&format!("Building OpenMP/Offload for {target}"));
1006        t!(stamp.remove());
1007        let _time = helpers::timeit(builder);
1008        t!(fs::create_dir_all(&out_dir));
1009
1010        builder.config.update_submodule("src/llvm-project");
1011
1012        // OpenMP/Offload builds currently (LLVM-22) still depend on Clang, although there are
1013        // intentions to loosen this requirement over time. FIXME(offload): re-evaluate on LLVM 23
1014        let clang_dir = if !builder.config.llvm_clang {
1015            // We must have an external clang to use.
1016            assert!(&builder.build.config.llvm_clang_dir.is_some());
1017            builder.build.config.llvm_clang_dir.clone()
1018        } else {
1019            // No need to specify it, since we use the in-tree clang
1020            None
1021        };
1022
1023        // In the context of OpenMP offload, some libraries must be compiled for the gpu target,
1024        // some for the host, and others for both. We do not perform a full cross-compilation, since
1025        // we don't want to run rustc on a GPU.
1026        let omp_targets = vec![target.triple.as_ref(), "amdgcn-amd-amdhsa", "nvptx64-nvidia-cuda"];
1027        for omp_target in omp_targets {
1028            let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/runtimes/"));
1029
1030            // If we use an external clang as opposed to building our own llvm_clang, than that clang will
1031            // come with it's own set of default include directories, which are based on a potentially older
1032            // LLVM. This can cause issues, so we overwrite it to include headers based on our
1033            // `src/llvm-project` submodule instead.
1034            // FIXME(offload): With LLVM-22 we hopefully won't need an external clang anymore.
1035            let mut cflags = CcFlags::default();
1036            if !builder.config.llvm_clang {
1037                let base = builder.llvm_out(target).join("include");
1038                let inc_dir = base.display();
1039                cflags.push_all(format!(" -I {inc_dir}"));
1040            }
1041
1042            configure_cmake(builder, target, &mut cfg, true, LdFlags::default(), cflags, &[]);
1043
1044            // Re-use the same flags as llvm to control the level of debug information
1045            // generated for offload.
1046            let profile =
1047                match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
1048                    (false, _) => "Debug",
1049                    (true, false) => "Release",
1050                    (true, true) => "RelWithDebInfo",
1051                };
1052            trace!(?profile);
1053
1054            // FIXME(offload): Once we move from OMP to Offload (Ol) APIs, we should drop the openmp
1055            // runtime to simplify our build. So far, these are still under development.
1056            cfg.out_dir(&out_dir)
1057                .profile(profile)
1058                .env("LLVM_CONFIG_REAL", &host_llvm_config)
1059                .define("LLVM_ENABLE_ASSERTIONS", "ON")
1060                .define("LLVM_INCLUDE_TESTS", "OFF")
1061                .define("OFFLOAD_INCLUDE_TESTS", "OFF")
1062                .define("LLVM_ROOT", builder.llvm_out(target).join("build"))
1063                .define("LLVM_DIR", llvm_cmake_dir.clone())
1064                .define("LLVM_DEFAULT_TARGET_TRIPLE", omp_target);
1065            if let Some(p) = clang_dir.clone() {
1066                cfg.define("Clang_DIR", p);
1067            }
1068
1069            // We don't perform a full cross-compilation of rustc, therefore our target.triple
1070            // will still be a CPU target.
1071            if *omp_target == *target.triple {
1072                // The offload library provides functionality which only makes sense on the host.
1073                cfg.define("LLVM_ENABLE_RUNTIMES", "openmp;offload");
1074            } else {
1075                // OpenMP provides some device libraries, so we also compile it for all gpu targets.
1076                cfg.define("LLVM_USE_LINKER", "lld");
1077                cfg.define("LLVM_ENABLE_RUNTIMES", "openmp");
1078                cfg.define("CMAKE_C_COMPILER_TARGET", omp_target);
1079                cfg.define("CMAKE_CXX_COMPILER_TARGET", omp_target);
1080            }
1081            cfg.build();
1082        }
1083
1084        t!(stamp.write());
1085
1086        for p in &files {
1087            // At this point, `out_dir` should contain the built <offload-filename>.<dylib-ext>
1088            // files.
1089            if !p.exists() {
1090                eprintln!(
1091                    "`{p:?}` not found in `{}`. Either the build has failed or Offload was built with a wrong version of LLVM",
1092                    out_dir.display()
1093                );
1094                exit!(1);
1095            }
1096        }
1097        BuiltOmpOffload { offload: files }
1098    }
1099}
1100
1101#[derive(Clone)]
1102pub struct BuiltEnzyme {
1103    /// Path to the libEnzyme dylib.
1104    enzyme: PathBuf,
1105}
1106
1107impl BuiltEnzyme {
1108    pub fn enzyme_path(&self) -> PathBuf {
1109        self.enzyme.clone()
1110    }
1111    pub fn enzyme_filename(&self) -> String {
1112        self.enzyme.file_name().unwrap().to_str().unwrap().to_owned()
1113    }
1114}
1115
1116#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1117pub struct Enzyme {
1118    pub target: TargetSelection,
1119}
1120
1121impl Step for Enzyme {
1122    type Output = BuiltEnzyme;
1123    const IS_HOST: bool = true;
1124
1125    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1126        run.path("src/tools/enzyme/enzyme")
1127    }
1128
1129    fn make_run(run: RunConfig<'_>) {
1130        run.builder.ensure(Enzyme { target: run.target });
1131    }
1132
1133    /// Compile Enzyme for `target`.
1134    fn run(self, builder: &Builder<'_>) -> Self::Output {
1135        builder.require_submodule(
1136            "src/tools/enzyme",
1137            Some("The Enzyme sources are required for autodiff."),
1138        );
1139        let target = self.target;
1140
1141        if builder.config.dry_run() {
1142            return BuiltEnzyme { enzyme: builder.config.tempdir().join("enzyme-dryrun") };
1143        }
1144
1145        let LlvmResult { host_llvm_config, llvm_cmake_dir } = builder.ensure(Llvm { target });
1146
1147        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1148        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1149            generate_smart_stamp_hash(
1150                builder,
1151                &builder.config.src.join("src/tools/enzyme"),
1152                builder.enzyme_info.sha().unwrap_or_default(),
1153            )
1154        });
1155
1156        let out_dir = builder.enzyme_out(target);
1157        let stamp = BuildStamp::new(&out_dir).with_prefix("enzyme").add_stamp(smart_stamp_hash);
1158
1159        let llvm_version_major = llvm::get_llvm_version_major(builder, &host_llvm_config);
1160        let lib_ext = std::env::consts::DLL_EXTENSION;
1161        let libenzyme = format!("libEnzyme-{llvm_version_major}");
1162        let build_dir = out_dir.join("lib");
1163        let dylib = build_dir.join(&libenzyme).with_extension(lib_ext);
1164
1165        trace!("checking build stamp to see if we need to rebuild enzyme artifacts");
1166        if stamp.is_up_to_date() {
1167            trace!(?out_dir, "enzyme build artifacts are up to date");
1168            if stamp.stamp().is_empty() {
1169                builder.info(
1170                    "Could not determine the Enzyme submodule commit hash. \
1171                     Assuming that an Enzyme rebuild is not necessary.",
1172                );
1173                builder.info(&format!(
1174                    "To force Enzyme to rebuild, remove the file `{}`",
1175                    stamp.path().display()
1176                ));
1177            }
1178            return BuiltEnzyme { enzyme: dylib };
1179        }
1180
1181        if !builder.config.dry_run() && !llvm_cmake_dir.is_dir() {
1182            builder.info(&format!(
1183                "WARNING: {} does not exist, Enzyme build will likely fail",
1184                llvm_cmake_dir.display()
1185            ));
1186        }
1187
1188        trace!(?target, "(re)building enzyme artifacts");
1189        builder.info(&format!("Building Enzyme for {target}"));
1190        t!(stamp.remove());
1191        let _time = helpers::timeit(builder);
1192        t!(fs::create_dir_all(&out_dir));
1193
1194        let mut cfg = cmake::Config::new(builder.src.join("src/tools/enzyme/enzyme/"));
1195        // Enzyme devs maintain upstream compatibility, but only fix deprecations when they are about
1196        // to turn into a hard error. As such, Enzyme generates various warnings which could make it
1197        // hard to spot more relevant issues.
1198        let mut cflags = CcFlags::default();
1199        cflags.push_all("-Wno-deprecated");
1200        configure_cmake(builder, target, &mut cfg, true, LdFlags::default(), cflags, &[]);
1201
1202        // Re-use the same flags as llvm to control the level of debug information
1203        // generated by Enzyme.
1204        // FIXME(ZuseZ4): Find a nicer way to use Enzyme Debug builds.
1205        let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
1206            (false, _) => "Debug",
1207            (true, false) => "Release",
1208            (true, true) => "RelWithDebInfo",
1209        };
1210        trace!(?profile);
1211
1212        cfg.out_dir(&out_dir)
1213            .profile(profile)
1214            .env("LLVM_CONFIG_REAL", &host_llvm_config)
1215            .define("LLVM_ENABLE_ASSERTIONS", "ON")
1216            .define("ENZYME_EXTERNAL_SHARED_LIB", "ON")
1217            .define("ENZYME_BC_LOADER", "OFF")
1218            .define("LLVM_DIR", llvm_cmake_dir);
1219
1220        cfg.build();
1221
1222        // At this point, `out_dir` should contain the built libEnzyme-<LLVM-version>.<dylib-ext>
1223        // file.
1224        if !dylib.exists() {
1225            eprintln!(
1226                "`{libenzyme}` not found in `{}`. Either the build has failed or Enzyme was built with a wrong version of LLVM",
1227                build_dir.display()
1228            );
1229            exit!(1);
1230        }
1231
1232        t!(stamp.write());
1233        BuiltEnzyme { enzyme: dylib }
1234    }
1235}
1236
1237#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1238pub struct Lld {
1239    pub target: TargetSelection,
1240}
1241
1242impl Step for Lld {
1243    type Output = PathBuf;
1244    const IS_HOST: bool = true;
1245
1246    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1247        run.path("src/llvm-project/lld")
1248    }
1249
1250    fn make_run(run: RunConfig<'_>) {
1251        run.builder.ensure(Lld { target: run.target });
1252    }
1253
1254    /// Compile LLD for `target`.
1255    fn run(self, builder: &Builder<'_>) -> PathBuf {
1256        if builder.config.dry_run() {
1257            return PathBuf::from("lld-out-dir-test-gen");
1258        }
1259        let target = self.target;
1260
1261        let LlvmResult { host_llvm_config, llvm_cmake_dir } = builder.ensure(Llvm { target });
1262
1263        // The `dist` step packages LLD next to LLVM's binaries for download-ci-llvm. The root path
1264        // we usually expect here is `./build/$triple/ci-llvm/`, with the binaries in its `bin`
1265        // subfolder. We check if that's the case, and if LLD's binary already exists there next to
1266        // `llvm-config`: if so, we can use it instead of building LLVM/LLD from source.
1267        let ci_llvm_bin = host_llvm_config.parent().unwrap();
1268        if ci_llvm_bin.is_dir() && ci_llvm_bin.file_name().unwrap() == "bin" {
1269            let lld_path = ci_llvm_bin.join(exe("lld", target));
1270            if lld_path.exists() {
1271                // The following steps copying `lld` as `rust-lld` to the sysroot, expect it in the
1272                // `bin` subfolder of this step's out dir.
1273                return ci_llvm_bin.parent().unwrap().to_path_buf();
1274            }
1275        }
1276
1277        let out_dir = builder.lld_out(target);
1278
1279        let lld_stamp = BuildStamp::new(&out_dir).with_prefix("lld");
1280        if lld_stamp.path().exists() {
1281            return out_dir;
1282        }
1283
1284        let _guard = builder.msg_unstaged(Kind::Build, "LLD", target);
1285        let _time = helpers::timeit(builder);
1286        t!(fs::create_dir_all(&out_dir));
1287
1288        let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
1289        let mut ldflags = LdFlags::default();
1290
1291        // When building LLD as part of a build with instrumentation on windows, for example
1292        // when doing PGO on CI, cmake or clang-cl don't automatically link clang's
1293        // profiler runtime in. In that case, we need to manually ask cmake to do it, to avoid
1294        // linking errors, much like LLVM's cmake setup does in that situation.
1295        if builder.config.llvm_profile_generate
1296            && target.is_msvc()
1297            && let Some(clang_cl_path) = builder.config.llvm_clang_cl.as_ref()
1298        {
1299            // Find clang's runtime library directory and push that as a search path to the
1300            // cmake linker flags.
1301            let clang_rt_dir = get_clang_cl_resource_dir(builder, clang_cl_path);
1302            ldflags.push_all(format!("/libpath:{}", clang_rt_dir.display()));
1303        }
1304
1305        // LLD is built as an LLVM tool, but is distributed outside of the `llvm-tools` component,
1306        // which impacts where it expects to find LLVM's shared library. This causes #80703.
1307        //
1308        // LLD is distributed at "$root/lib/rustlib/$host/bin/rust-lld", but the `libLLVM-*.so` it
1309        // needs is distributed at "$root/lib". The default rpath of "$ORIGIN/../lib" points at the
1310        // lib path for LLVM tools, not the one for rust binaries.
1311        //
1312        // (The `llvm-tools` component copies the .so there for the other tools, and with that
1313        // component installed, one can successfully invoke `rust-lld` directly without rustup's
1314        // `LD_LIBRARY_PATH` overrides)
1315        //
1316        if builder.config.rpath_enabled(target)
1317            && helpers::use_host_linker(target)
1318            && builder.config.llvm_link_shared()
1319            && target.contains("linux")
1320        {
1321            // So we inform LLD where it can find LLVM's libraries by adding an rpath entry to the
1322            // expected parent `lib` directory.
1323            //
1324            // Be careful when changing this path, we need to ensure it's quoted or escaped:
1325            // `$ORIGIN` would otherwise be expanded when the `LdFlags` are passed verbatim to
1326            // cmake.
1327            ldflags.push_all("-Wl,-rpath,'$ORIGIN/../../../'");
1328        }
1329
1330        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
1331        configure_llvm(builder, target, &mut cfg);
1332
1333        // Re-use the same flags as llvm to control the level of debug information
1334        // generated for lld.
1335        let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
1336            (false, _) => "Debug",
1337            (true, false) => "Release",
1338            (true, true) => "RelWithDebInfo",
1339        };
1340
1341        cfg.out_dir(&out_dir)
1342            .profile(profile)
1343            .define("LLVM_CMAKE_DIR", llvm_cmake_dir)
1344            .define("LLVM_INCLUDE_TESTS", "OFF");
1345
1346        if !builder.config.is_host_target(target) {
1347            // Use the host llvm-tblgen binary.
1348            cfg.define(
1349                "LLVM_TABLEGEN_EXE",
1350                host_llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
1351            );
1352        }
1353
1354        cfg.build();
1355
1356        t!(lld_stamp.write());
1357        out_dir
1358    }
1359}
1360
1361#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1362pub struct Sanitizers {
1363    pub target: TargetSelection,
1364}
1365
1366impl Step for Sanitizers {
1367    type Output = Vec<SanitizerRuntime>;
1368
1369    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1370        run.alias("sanitizers")
1371    }
1372
1373    fn make_run(run: RunConfig<'_>) {
1374        run.builder.ensure(Sanitizers { target: run.target });
1375    }
1376
1377    /// Builds sanitizer runtime libraries.
1378    fn run(self, builder: &Builder<'_>) -> Self::Output {
1379        let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
1380        if !compiler_rt_dir.exists() {
1381            return Vec::new();
1382        }
1383
1384        let out_dir = builder.native_dir(self.target).join("sanitizers");
1385        let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
1386
1387        if builder.config.dry_run() || runtimes.is_empty() {
1388            return runtimes;
1389        }
1390
1391        let LlvmResult { host_llvm_config, .. } =
1392            builder.ensure(Llvm { target: builder.config.host_target });
1393
1394        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1395        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1396            generate_smart_stamp_hash(
1397                builder,
1398                &builder.config.src.join("src/llvm-project/compiler-rt"),
1399                builder.in_tree_llvm_info.sha().unwrap_or_default(),
1400            )
1401        });
1402
1403        let stamp = BuildStamp::new(&out_dir).with_prefix("sanitizers").add_stamp(smart_stamp_hash);
1404
1405        if stamp.is_up_to_date() {
1406            if stamp.stamp().is_empty() {
1407                builder.info(&format!(
1408                    "Rebuild sanitizers by removing the file `{}`",
1409                    stamp.path().display()
1410                ));
1411            }
1412
1413            return runtimes;
1414        }
1415
1416        let _guard = builder.msg_unstaged(Kind::Build, "sanitizers", self.target);
1417        t!(stamp.remove());
1418        let _time = helpers::timeit(builder);
1419
1420        let mut cfg = cmake::Config::new(&compiler_rt_dir);
1421        cfg.profile("Release");
1422        cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
1423        cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
1424        cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
1425        cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
1426        cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
1427        cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
1428        cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
1429        cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
1430        cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
1431        cfg.define("LLVM_CONFIG_PATH", &host_llvm_config);
1432
1433        if self.target.contains("ohos") {
1434            cfg.define("COMPILER_RT_USE_BUILTINS_LIBRARY", "ON");
1435        }
1436
1437        // On Darwin targets the sanitizer runtimes are build as universal binaries.
1438        // Unfortunately sccache currently lacks support to build them successfully.
1439        // Disable compiler launcher on Darwin targets to avoid potential issues.
1440        let use_compiler_launcher = !self.target.contains("apple-darwin");
1441        // Since v1.0.86, the cc crate adds -mmacosx-version-min to the default
1442        // flags on MacOS. A long-standing bug in the CMake rules for compiler-rt
1443        // causes architecture detection to be skipped when this flag is present,
1444        // and compilation fails. https://github.com/llvm/llvm-project/issues/88780
1445        let suppressed_compiler_flag_prefixes: &[&str] =
1446            if self.target.contains("apple-darwin") { &["-mmacosx-version-min="] } else { &[] };
1447        configure_cmake(
1448            builder,
1449            self.target,
1450            &mut cfg,
1451            use_compiler_launcher,
1452            LdFlags::default(),
1453            CcFlags::default(),
1454            suppressed_compiler_flag_prefixes,
1455        );
1456
1457        t!(fs::create_dir_all(&out_dir));
1458        cfg.out_dir(out_dir);
1459
1460        for runtime in &runtimes {
1461            cfg.build_target(&runtime.cmake_target);
1462            cfg.build();
1463        }
1464        t!(stamp.write());
1465
1466        runtimes
1467    }
1468}
1469
1470#[derive(Clone, Debug)]
1471pub struct SanitizerRuntime {
1472    /// CMake target used to build the runtime.
1473    pub cmake_target: String,
1474    /// Path to the built runtime library.
1475    pub path: PathBuf,
1476    /// Library filename that will be used rustc.
1477    pub name: String,
1478}
1479
1480/// Returns sanitizers available on a given target.
1481fn supported_sanitizers(
1482    out_dir: &Path,
1483    target: TargetSelection,
1484    channel: &str,
1485) -> Vec<SanitizerRuntime> {
1486    let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1487        components
1488            .iter()
1489            .map(move |c| SanitizerRuntime {
1490                cmake_target: format!("clang_rt.{c}_{os}_dynamic"),
1491                path: out_dir.join(format!("build/lib/darwin/libclang_rt.{c}_{os}_dynamic.dylib")),
1492                name: format!("librustc-{channel}_rt.{c}.dylib"),
1493            })
1494            .collect()
1495    };
1496
1497    let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1498        components
1499            .iter()
1500            .map(move |c| SanitizerRuntime {
1501                cmake_target: format!("clang_rt.{c}-{arch}"),
1502                path: out_dir.join(format!("build/lib/{os}/libclang_rt.{c}-{arch}.a")),
1503                name: format!("librustc-{channel}_rt.{c}.a"),
1504            })
1505            .collect()
1506    };
1507
1508    match &*target.triple {
1509        "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),
1510        "aarch64-apple-ios" => darwin_libs("ios", &["asan", "tsan", "rtsan"]),
1511        "aarch64-apple-ios-sim" => darwin_libs("iossim", &["asan", "tsan", "rtsan"]),
1512        "aarch64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1513        "aarch64-unknown-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
1514        "aarch64-unknown-linux-gnu" => {
1515            common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan", "rtsan"])
1516        }
1517        "aarch64-unknown-linux-ohos" => {
1518            common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
1519        }
1520        "loongarch64-unknown-linux-gnu" | "loongarch64-unknown-linux-musl" => {
1521            common_libs("linux", "loongarch64", &["asan", "lsan", "msan", "tsan"])
1522        }
1523        "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),
1524        "x86_64-unknown-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
1525        "x86_64-apple-ios" => darwin_libs("iossim", &["asan", "tsan"]),
1526        "x86_64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1527        "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
1528        "x86_64-unknown-netbsd" => {
1529            common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
1530        }
1531        "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
1532        "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
1533        "x86_64-unknown-linux-gnu" => common_libs(
1534            "linux",
1535            "x86_64",
1536            &["asan", "dfsan", "lsan", "msan", "safestack", "tsan", "rtsan"],
1537        ),
1538        "x86_64-unknown-linux-gnuasan" => common_libs("linux", "x86_64", &["asan"]),
1539        "x86_64-unknown-linux-musl" => {
1540            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1541        }
1542        "s390x-unknown-linux-gnu" => {
1543            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1544        }
1545        "s390x-unknown-linux-musl" => {
1546            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1547        }
1548        "x86_64-unknown-linux-ohos" => {
1549            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1550        }
1551        _ => Vec::new(),
1552    }
1553}
1554
1555#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1556pub struct CrtBeginEnd {
1557    pub target: TargetSelection,
1558}
1559
1560impl Step for CrtBeginEnd {
1561    type Output = PathBuf;
1562
1563    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1564        run.path("src/llvm-project/compiler-rt/lib/crt")
1565    }
1566
1567    fn make_run(run: RunConfig<'_>) {
1568        if run.target.needs_crt_begin_end() {
1569            run.builder.ensure(CrtBeginEnd { target: run.target });
1570        }
1571    }
1572
1573    /// Build crtbegin.o/crtend.o for musl target.
1574    fn run(self, builder: &Builder<'_>) -> Self::Output {
1575        builder.require_submodule(
1576            "src/llvm-project",
1577            Some("The LLVM sources are required for the CRT from `compiler-rt`."),
1578        );
1579
1580        let out_dir = builder.native_dir(self.target).join("crt");
1581
1582        if builder.config.dry_run() {
1583            return out_dir;
1584        }
1585
1586        let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtbegin.c");
1587        let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtend.c");
1588        if up_to_date(&crtbegin_src, &out_dir.join("crtbeginS.o"))
1589            && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
1590        {
1591            return out_dir;
1592        }
1593
1594        let _guard = builder.msg_unstaged(Kind::Build, "crtbegin.o and crtend.o", self.target);
1595        t!(fs::create_dir_all(&out_dir));
1596
1597        let mut cfg = cc::Build::new();
1598
1599        if let Some(ar) = builder.ar(self.target) {
1600            cfg.archiver(ar);
1601        }
1602        cfg.compiler(builder.cc(self.target));
1603        cfg.cargo_metadata(false)
1604            .out_dir(&out_dir)
1605            .target(&self.target.triple)
1606            .host(&builder.config.host_target.triple)
1607            .warnings(false)
1608            .debug(false)
1609            .opt_level(3)
1610            .file(crtbegin_src)
1611            .file(crtend_src);
1612
1613        // Those flags are defined in src/llvm-project/compiler-rt/lib/builtins/CMakeLists.txt
1614        // Currently only consumer of those objects is musl, which use .init_array/.fini_array
1615        // instead of .ctors/.dtors
1616        cfg.flag("-std=c11")
1617            .define("CRT_HAS_INITFINI_ARRAY", None)
1618            .define("EH_USE_FRAME_REGISTRY", None);
1619
1620        let objs = cfg.compile_intermediates();
1621        assert_eq!(objs.len(), 2);
1622        for obj in objs {
1623            let base_name = unhashed_basename(&obj);
1624            assert!(base_name == "crtbegin" || base_name == "crtend");
1625            t!(fs::copy(&obj, out_dir.join(format!("{base_name}S.o"))));
1626            t!(fs::rename(&obj, out_dir.join(format!("{base_name}.o"))));
1627        }
1628
1629        out_dir
1630    }
1631}
1632
1633#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1634pub struct Libunwind {
1635    pub target: TargetSelection,
1636}
1637
1638impl Step for Libunwind {
1639    type Output = PathBuf;
1640
1641    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1642        run.path("src/llvm-project/libunwind")
1643    }
1644
1645    fn make_run(run: RunConfig<'_>) {
1646        run.builder.ensure(Libunwind { target: run.target });
1647    }
1648
1649    /// Build libunwind.a
1650    fn run(self, builder: &Builder<'_>) -> Self::Output {
1651        builder.require_submodule(
1652            "src/llvm-project",
1653            Some("The LLVM sources are required for libunwind."),
1654        );
1655
1656        if builder.config.dry_run() {
1657            return PathBuf::new();
1658        }
1659
1660        let out_dir = builder.native_dir(self.target).join("libunwind");
1661        let root = builder.src.join("src/llvm-project/libunwind");
1662
1663        if up_to_date(&root, &out_dir.join("libunwind.a")) {
1664            return out_dir;
1665        }
1666
1667        let _guard = builder.msg_unstaged(Kind::Build, "libunwind.a", self.target);
1668        t!(fs::create_dir_all(&out_dir));
1669
1670        let mut cc_cfg = cc::Build::new();
1671        let mut cpp_cfg = cc::Build::new();
1672
1673        cpp_cfg.cpp(true);
1674        cpp_cfg.cpp_set_stdlib(None);
1675        cpp_cfg.flag("-nostdinc++");
1676        cpp_cfg.flag("-fno-exceptions");
1677        cpp_cfg.flag("-fno-rtti");
1678        cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
1679
1680        for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
1681            if let Some(ar) = builder.ar(self.target) {
1682                cfg.archiver(ar);
1683            }
1684            cfg.target(&self.target.triple);
1685            cfg.host(&builder.config.host_target.triple);
1686            cfg.warnings(false);
1687            cfg.debug(false);
1688            // get_compiler() need set opt_level first.
1689            cfg.opt_level(3);
1690            cfg.flag("-fstrict-aliasing");
1691            cfg.flag("-funwind-tables");
1692            cfg.flag("-fvisibility=hidden");
1693            cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1694            cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");
1695            cfg.include(root.join("include"));
1696            cfg.cargo_metadata(false);
1697            cfg.out_dir(&out_dir);
1698
1699            if self.target.contains("x86_64-fortanix-unknown-sgx") {
1700                cfg.static_flag(true);
1701                cfg.flag("-fno-stack-protector");
1702                cfg.flag("-ffreestanding");
1703                cfg.flag("-fexceptions");
1704
1705                // easiest way to undefine since no API available in cc::Build to undefine
1706                cfg.flag("-U_FORTIFY_SOURCE");
1707                cfg.define("_FORTIFY_SOURCE", "0");
1708                cfg.define("RUST_SGX", "1");
1709                cfg.define("__NO_STRING_INLINES", None);
1710                cfg.define("__NO_MATH_INLINES", None);
1711                cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1712                cfg.define("NDEBUG", None);
1713            }
1714            if self.target.is_windows() {
1715                cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");
1716            }
1717        }
1718
1719        cc_cfg.compiler(builder.cc(self.target));
1720        if let Ok(cxx) = builder.cxx(self.target) {
1721            cpp_cfg.compiler(cxx);
1722        } else {
1723            cc_cfg.compiler(builder.cc(self.target));
1724        }
1725
1726        // Don't set this for clang
1727        // By default, Clang builds C code in GNU C17 mode.
1728        // By default, Clang builds C++ code according to the C++98 standard,
1729        // with many C++11 features accepted as extensions.
1730        if cc_cfg.get_compiler().is_like_gnu() {
1731            cc_cfg.flag("-std=c99");
1732        }
1733        if cpp_cfg.get_compiler().is_like_gnu() {
1734            cpp_cfg.flag("-std=c++11");
1735        }
1736
1737        if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1738            // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1739            // C++ compiler env variables on the builders.
1740            // Don't set this for clang++, as clang++ is able to compile this without libc++.
1741            if cpp_cfg.get_compiler().is_like_gnu() {
1742                cpp_cfg.cpp(false);
1743                cpp_cfg.compiler(builder.cc(self.target));
1744            }
1745        }
1746
1747        let mut c_sources = vec![
1748            "Unwind-sjlj.c",
1749            "UnwindLevel1-gcc-ext.c",
1750            "UnwindLevel1.c",
1751            "UnwindRegistersRestore.S",
1752            "UnwindRegistersSave.S",
1753        ];
1754
1755        let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1756        let cpp_len = cpp_sources.len();
1757
1758        if self.target.contains("x86_64-fortanix-unknown-sgx") {
1759            c_sources.push("UnwindRustSgx.c");
1760        }
1761
1762        for src in c_sources {
1763            cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1764        }
1765
1766        for src in &cpp_sources {
1767            cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1768        }
1769
1770        cpp_cfg.compile("unwind-cpp");
1771
1772        // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1773        let mut count = 0;
1774        let mut files = fs::read_dir(&out_dir)
1775            .unwrap()
1776            .map(|entry| entry.unwrap().path().canonicalize().unwrap())
1777            .collect::<Vec<_>>();
1778        files.sort();
1779        for file in files {
1780            if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1781                // Object file name without the hash prefix is "Unwind-EHABI", "Unwind-seh" or "libunwind".
1782                let base_name = unhashed_basename(&file);
1783                if cpp_sources.iter().any(|f| *base_name == f[..f.len() - 4]) {
1784                    cc_cfg.object(&file);
1785                    count += 1;
1786                }
1787            }
1788        }
1789        assert_eq!(cpp_len, count, "Can't get object files from {out_dir:?}");
1790
1791        cc_cfg.compile("unwind");
1792        out_dir
1793    }
1794}