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