bootstrap/core/build_steps/
llvm.rs

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