bootstrap/core/build_steps/
llvm.rs

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