Skip to main content

bootstrap/core/build_steps/
llvm.rs

1//! Compilation of native dependencies like LLVM.
2//!
3//! Native projects like LLVM unfortunately aren't suited just yet for
4//! compilation in build scripts that Cargo has. This is because the
5//! compilation takes a *very* long time but also because we don't want to
6//! compile LLVM 3 times as part of a normal bootstrap (we want it cached).
7//!
8//! LLVM and compiler-rt are essentially just wired up to everything else to
9//! ensure that they're always in place if needed.
10
11use std::env::consts::EXE_EXTENSION;
12use std::ffi::{OsStr, OsString};
13use std::path::{Path, PathBuf};
14use std::sync::OnceLock;
15use std::{env, fs};
16
17use build_helper::git::PathFreshness;
18
19use crate::core::build_steps::llvm;
20use crate::core::builder::{
21    Builder, CommandLineStep, Kind, RunConfig, ShouldRun, Step, StepMetadata,
22};
23use crate::core::config::{Config, LlvmCiMode, LlvmPgoGenerationMode, TargetSelection};
24use crate::core::session::CLang;
25use crate::trace;
26use crate::utils::build_stamp::{BuildStamp, generate_smart_stamp_hash};
27use crate::utils::exec::command;
28use crate::utils::helpers::{
29    self, exe, get_clang_cl_resource_dir, libdir, t, unhashed_basename, up_to_date,
30};
31/// Path where a file containing the link type (dynamic or static) is stored in the LLVM CI tarball.
32pub const LLVM_CI_LINK_TYPE_PATH: &str = "link-type.txt";
33
34#[derive(Copy, Clone, PartialEq, Eq)]
35pub enum LlvmKind {
36    /// The LLVM was built from in-tree sources
37    BuiltLocally,
38    /// The LLVM was downloaded from the `rust-dev` CI artifact.
39    DownloadedFromCi,
40    /// The LLVM was provided externally through a `llvm-config` file.
41    External,
42}
43
44/// Result of building or downloading LLVM artifacts.
45#[derive(Clone)]
46pub struct LlvmOutput {
47    llvm_config: PathBuf,
48    link_shared: bool,
49    llvm_root_dir: PathBuf,
50    kind: LlvmKind,
51}
52
53impl LlvmOutput {
54    /// Directory containing the built LLVM artifacts.
55    /// Contains `bin`/`lib` directories.
56    pub fn root_dir(&self) -> &Path {
57        &self.llvm_root_dir
58    }
59
60    /// Path to LLVM cmake directory.
61    pub fn cmake_dir(&self) -> PathBuf {
62        self.llvm_root_dir.join("lib").join("cmake").join("llvm")
63    }
64
65    /// Should we link dynamically to the built LLVM?
66    pub fn link_shared(&self) -> bool {
67        self.link_shared
68    }
69
70    /// How was the LLVM produced?
71    pub fn kind(&self) -> LlvmKind {
72        self.kind
73    }
74
75    /// Path to the `llvm-config` binary.
76    ///
77    /// Note that this binary might not be executable on the current host, if LLVM was built for a
78    /// different target.
79    pub fn llvm_config(&self) -> &Path {
80        &self.llvm_config
81    }
82}
83
84pub struct LlvmBuildInfo {
85    stamp: BuildStamp,
86    output: LlvmOutput,
87}
88
89pub enum LlvmBuildStatus {
90    AlreadyBuilt(LlvmOutput),
91    ShouldBuild(LlvmBuildInfo),
92}
93
94impl LlvmBuildStatus {
95    pub fn llvm_output(&self) -> &LlvmOutput {
96        match self {
97            LlvmBuildStatus::AlreadyBuilt(res) => res,
98            LlvmBuildStatus::ShouldBuild(meta) => &meta.output,
99        }
100    }
101}
102
103/// Allows each step to add C/Cxx flags which are only used for a specific cmake invocation.
104#[derive(Debug, Clone, Default)]
105struct CcFlags {
106    /// Additional values for CMAKE_CC_FLAGS, to be added before all other values.
107    cflags: OsString,
108    /// Additional values for CMAKE_CXX_FLAGS, to be added before all other values.
109    cxxflags: OsString,
110}
111
112impl CcFlags {
113    fn push_all(&mut self, s: impl AsRef<OsStr>) {
114        let s = s.as_ref();
115        self.cflags.push(" ");
116        self.cflags.push(s);
117        self.cxxflags.push(" ");
118        self.cxxflags.push(s);
119    }
120}
121
122/// Linker flags to pass to LLVM's CMake invocation.
123#[derive(Debug, Clone, Default)]
124struct LdFlags {
125    /// CMAKE_EXE_LINKER_FLAGS
126    exe: OsString,
127    /// CMAKE_SHARED_LINKER_FLAGS
128    shared: OsString,
129    /// CMAKE_MODULE_LINKER_FLAGS
130    module: OsString,
131}
132
133impl LdFlags {
134    fn push_all(&mut self, s: impl AsRef<OsStr>) {
135        let s = s.as_ref();
136        self.exe.push(" ");
137        self.exe.push(s);
138        self.shared.push(" ");
139        self.shared.push(s);
140        self.module.push(" ");
141        self.module.push(s);
142    }
143}
144
145/// Attempt to return prebuilt LLVM output information, either downloaded from CI or through an
146/// externally provided LLVM.
147///
148/// It's used e.g. to avoid busting caches during x.py check -- if we've already built
149/// LLVM, it's fine for us to not try to avoid doing so.
150///
151/// Calling this function should never attempt to checkout the LLVM submodule.
152pub fn prebuilt_llvm_output(builder: &Builder<'_>, target: TargetSelection) -> Option<LlvmOutput> {
153    // Use an externally provided LLVM, if available
154    if let Some(config) = builder.config.target_config.get(&target)
155        && let Some(ref s) = config.llvm_config
156    {
157        // We execute the llvm-config, and we can only do that on the host target
158        if target == builder.host_target {
159            check_llvm_version(builder, s);
160        }
161        let llvm_config = s.to_path_buf();
162        let mut llvm_root_dir = llvm_config.clone();
163        llvm_root_dir.pop();
164        llvm_root_dir.pop();
165
166        return Some(LlvmOutput {
167            llvm_config,
168            link_shared: llvm_link_shared(&builder.config),
169            llvm_root_dir,
170            kind: LlvmKind::External,
171        });
172    }
173
174    // If external LLVM is not configured, try to download LLVM from CI, if possible
175    let llvm_ci = builder.ensure(LlvmFromCi { target });
176    if let Some(llvm) = llvm_ci {
177        return Some(llvm.output);
178    }
179
180    // If LLVM is not available from CI nor externally, it is still possible that it was already
181    // built locally before. In that case we still treat it as prebuilt config.
182    match get_locally_built_llvm_build_status(builder, target) {
183        LlvmBuildStatus::AlreadyBuilt(output) => Some(output),
184        LlvmBuildStatus::ShouldBuild(_) => None,
185    }
186}
187
188/// This returns whether we've already previously built LLVM.
189///
190/// This will return the llvm-config if it can get it (but it will not build it
191/// if not).
192///
193/// Note that calling this function *might* checkout the LLVM submodule!
194pub fn get_llvm_build_status(builder: &Builder<'_>, target: TargetSelection) -> LlvmBuildStatus {
195    if let Some(prebuilt_output) = prebuilt_llvm_output(builder, target) {
196        return LlvmBuildStatus::AlreadyBuilt(prebuilt_output);
197    }
198
199    // In remaining cases, build it locally
200    // If submodules are disabled, this does nothing.
201    builder.config.update_submodule("src/llvm-project");
202
203    get_locally_built_llvm_build_status(builder, target)
204}
205
206/// Return build status of LLVM, considering only the (possibly) locally built LLVM.
207///
208/// Calling this function should never attempt to checkout the LLVM submodule.
209fn get_locally_built_llvm_build_status(
210    builder: &Builder<'_>,
211    target: TargetSelection,
212) -> LlvmBuildStatus {
213    let out_dir = llvm_output_dir(builder, target);
214
215    let res = LlvmOutput {
216        llvm_config: out_dir.join("bin").join(exe("llvm-config", target)),
217        link_shared: llvm_link_shared(&builder.config),
218        llvm_root_dir: out_dir.clone(),
219        kind: LlvmKind::BuiltLocally,
220    };
221
222    static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
223    let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
224        generate_smart_stamp_hash(
225            builder,
226            &builder.config.src.join("src/llvm-project"),
227            builder.in_tree_llvm_info.sha().unwrap_or_default(),
228        )
229    });
230
231    let stamp = BuildStamp::new(&out_dir).with_prefix("llvm").add_stamp(smart_stamp_hash);
232
233    if stamp.is_up_to_date() {
234        if stamp.stamp().is_empty() {
235            builder.info(
236                "Could not determine the LLVM submodule commit hash. \
237                     Assuming that an LLVM rebuild is not necessary.",
238            );
239            builder.info(&format!(
240                "To force LLVM to rebuild, remove the file `{}`",
241                stamp.path().display()
242            ));
243        }
244        return LlvmBuildStatus::AlreadyBuilt(res);
245    }
246
247    LlvmBuildStatus::ShouldBuild(LlvmBuildInfo { stamp, output: res })
248}
249
250/// Output directory of *locally built* LLVM for the given `target`.
251/// Should only be used within this module, when building LLVM (or related tools).
252/// Otherwise, you should ensure the `Llvm` step and read its root directory.
253fn llvm_output_dir(builder: &Builder<'_>, target: TargetSelection) -> PathBuf {
254    builder.config.out.join(target).join("llvm")
255}
256
257fn try_download_ci_llvm(builder: &Builder<'_>, target: TargetSelection) -> Option<DownloadedLlvm> {
258    match builder.config.llvm_ci_mode {
259        LlvmCiMode::BuildLocally => return None,
260        LlvmCiMode::Download => {}
261        LlvmCiMode::DownloadIfUnchanged => {
262            builder.config.update_submodule("src/llvm-project");
263
264            // Check for untracked changes in `src/llvm-project` and other important places.
265            let has_changes = builder.config.has_changes_from_upstream(LLVM_INVALIDATION_PATHS);
266            if has_changes {
267                builder.info("Warning: LLVM will not be downloaded because of local changes");
268                return None;
269            }
270        }
271    }
272
273    if !is_ci_llvm_available_for_target(&target, builder.config.llvm_assertions) {
274        builder.info(&format!(
275            "Warning: LLVM not available on CI for target={target} and assertions={}",
276            builder.config.llvm_assertions
277        ));
278        return None;
279    }
280
281    let ci_llvm = builder.config.maybe_download_ci_llvm(target)?;
282    let link_shared = if !builder.config.dry_run() {
283        let link_type = t!(
284            std::fs::read_to_string(ci_llvm.join(LLVM_CI_LINK_TYPE_PATH)),
285            format!("LLVM downloaded from CI is missing the following file: {}", ci_llvm.display())
286        );
287        link_type == "dynamic"
288    } else {
289        false
290    };
291
292    Some(DownloadedLlvm {
293        output: LlvmOutput {
294            llvm_config: ci_llvm.join("bin").join(exe("llvm-config", target)),
295            link_shared,
296            llvm_root_dir: ci_llvm,
297            kind: LlvmKind::DownloadedFromCi,
298        },
299    })
300}
301
302/// Determine whether llvm should be linked dynamically.
303/// **NOTE**: This only contains the value from the config.
304/// If you need to figure out the correct value for a specific LLVM instance, use
305/// `prebuilt_llvm_config` instead.
306///
307/// This function is not a method on Config to discourage calling it from outside this module.
308fn llvm_link_shared(config: &Config) -> bool {
309    // unclear how thought-through this default is, but it maintains compatibility with
310    // previous behavior
311    config.llvm_link_shared.unwrap_or(false)
312}
313
314/// Paths whose changes invalidate LLVM downloads.
315pub const LLVM_INVALIDATION_PATHS: &[&str] = &[
316    "src/llvm-project",
317    "src/bootstrap/download-ci-llvm-stamp",
318    // the LLVM shared object file is named `LLVM-<LLVM-version>-rust-{version}-nightly`
319    "src/version",
320];
321
322/// Detect whether LLVM sources have been modified locally or not.
323pub(crate) fn detect_llvm_freshness(config: &Config, is_git: bool) -> PathFreshness {
324    assert!(cfg!(not(test)), "unit tests shouldn't care about LLVM freshness");
325
326    if is_git {
327        config.check_path_modifications(LLVM_INVALIDATION_PATHS)
328    } else if let Some(info) = crate::utils::channel::read_commit_info_file(&config.src) {
329        PathFreshness::LastModifiedUpstream { upstream: info.sha.trim().to_owned() }
330    } else {
331        PathFreshness::MissingUpstream
332    }
333}
334
335/// Returns whether the CI-found LLVM is currently usable.
336///
337/// This checks the build triple platform to confirm we're usable at all, and if LLVM
338/// with/without assertions is available.
339pub(crate) fn is_ci_llvm_available_for_target(
340    host_target: &TargetSelection,
341    asserts: bool,
342) -> bool {
343    // This is currently all tier 1 targets and tier 2 targets with host tools
344    // (since others may not have CI artifacts)
345    // https://doc.rust-lang.org/rustc/platform-support.html#tier-1
346    let supported_platforms = [
347        // tier 1
348        ("aarch64-unknown-linux-gnu", false),
349        ("aarch64-apple-darwin", false),
350        ("aarch64-pc-windows-msvc", false),
351        ("i686-pc-windows-msvc", false),
352        ("i686-unknown-linux-gnu", false),
353        ("x86_64-unknown-linux-gnu", true),
354        ("x86_64-apple-darwin", true),
355        ("x86_64-pc-windows-gnu", false),
356        ("x86_64-pc-windows-msvc", true),
357        // tier 2 with host tools
358        ("aarch64-unknown-linux-musl", false),
359        ("aarch64-pc-windows-gnullvm", false),
360        ("arm-unknown-linux-gnueabi", false),
361        ("arm-unknown-linux-gnueabihf", false),
362        ("armv7-unknown-linux-gnueabihf", false),
363        ("i686-pc-windows-gnu", false),
364        ("loongarch64-unknown-linux-gnu", false),
365        ("loongarch64-unknown-linux-musl", false),
366        ("powerpc-unknown-linux-gnu", false),
367        ("powerpc64-unknown-linux-gnu", false),
368        ("powerpc64-unknown-linux-musl", false),
369        ("powerpc64le-unknown-linux-gnu", false),
370        ("powerpc64le-unknown-linux-musl", false),
371        ("riscv64gc-unknown-linux-gnu", false),
372        ("riscv64gc-unknown-linux-musl", false),
373        ("s390x-unknown-linux-gnu", false),
374        ("x86_64-pc-windows-gnullvm", false),
375        ("x86_64-unknown-freebsd", false),
376        ("x86_64-unknown-illumos", false),
377        ("x86_64-unknown-linux-musl", false),
378        ("x86_64-unknown-netbsd", false),
379    ];
380
381    // Check if the host target is available with the requested assertions (true/false),
382    supported_platforms.contains(&(&*host_target.triple, asserts))
383        // if it is not available for the given `asserts`, check if it is available with assertions (superset).
384        || supported_platforms.contains(&(&*host_target.triple, true))
385}
386
387#[derive(Clone)]
388pub struct DownloadedLlvm {
389    pub output: LlvmOutput,
390}
391
392/// This step explicitly represents the output of *downloaded* LLVM.
393/// The step will provide an output only if all the following is true:
394/// - `llvm.download-ci-llvm` is `true` or `if-unchanged`
395/// - If the previous value is `if-unchanged`, the local LLVM inputs are not modified
396/// - Artifacts for LLVM for the given target (and debug assertions) are available on CI
397///
398/// There are some places in bootstrap that explicitly want to do something special about the
399/// downloaded LLVM, this step serves for them to do it in an explicit way.
400/// For all other use-cases, the normal `Llvm` step should be used.
401#[derive(Debug, Clone, Hash, PartialEq, Eq)]
402pub struct LlvmFromCi {
403    pub target: TargetSelection,
404}
405
406impl Step for LlvmFromCi {
407    type Output = Option<DownloadedLlvm>;
408
409    fn run(self, builder: &Builder<'_>) -> Self::Output {
410        let llvm_ci = try_download_ci_llvm(builder, self.target)?;
411
412        // Sanity check (we execute the llvm-config, so we can only do it on the host target).
413        if builder.host_target == self.target {
414            check_llvm_version(builder, llvm_ci.output.llvm_config());
415        }
416
417        Some(llvm_ci)
418    }
419}
420
421#[derive(Debug, Clone, Hash, PartialEq, Eq)]
422pub struct Llvm {
423    pub target: TargetSelection,
424}
425
426impl CommandLineStep for Llvm {
427    type Output = LlvmOutput;
428
429    const IS_HOST: bool = true;
430
431    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
432        run.path("src/llvm-project").path("src/llvm-project/llvm")
433    }
434
435    fn make_run(run: RunConfig<'_>) {
436        run.builder.ensure(Llvm { target: run.target });
437    }
438
439    /// Compile LLVM for `target`.
440    fn run(self, builder: &Builder<'_>) -> LlvmOutput {
441        let target = self.target;
442        let target_native = if self.target.starts_with("riscv") {
443            // RISC-V target triples in Rust is not named the same as C compiler target triples.
444            // This converts Rust RISC-V target triples to C compiler triples.
445            let idx = target.triple.find('-').unwrap();
446
447            format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
448        } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
449            // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
450            // Set the version suffix to 13.0 so the correct target details are used.
451            format!("{}{}", self.target, "13.0")
452        } else {
453            target.to_string()
454        };
455
456        // If LLVM has already been built or been downloaded through download-ci-llvm, we avoid building it again.
457        let LlvmBuildInfo { stamp, output } = match get_llvm_build_status(builder, target) {
458            LlvmBuildStatus::AlreadyBuilt(p) => return p,
459            LlvmBuildStatus::ShouldBuild(m) => m,
460        };
461
462        let link_shared = llvm_link_shared(&builder.config);
463
464        if link_shared && target.is_windows() && !target.is_windows_gnullvm() {
465            panic!("shared linking to LLVM is not currently supported on {}", target.triple);
466        }
467
468        let _guard = builder.msg_unstaged(Kind::Build, "LLVM", target);
469        t!(stamp.remove());
470        let _time = helpers::timeit(builder);
471        t!(fs::create_dir_all(output.root_dir()));
472
473        // https://llvm.org/docs/CMake.html
474        let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/llvm"));
475        let mut ldflags = LdFlags::default();
476
477        let profile = get_llvm_profile(&builder.config);
478
479        // NOTE: remember to also update `bootstrap.example.toml` when changing the
480        // defaults!
481        let llvm_targets = match &builder.config.llvm_targets {
482            Some(s) => s,
483            None => {
484                "AArch64;AMDGPU;ARM;BPF;Hexagon;LoongArch;MSP430;Mips;NVPTX;PowerPC;RISCV;\
485                     Sparc;SystemZ;WebAssembly;X86"
486            }
487        };
488
489        let llvm_exp_targets = match builder.config.llvm_experimental_targets {
490            Some(ref s) => s,
491            None => "AVR;M68k;CSKY;Xtensa",
492        };
493
494        let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
495        let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
496        let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
497        let enable_warnings = if builder.config.llvm_enable_warnings { "ON" } else { "OFF" };
498
499        cfg.out_dir(output.root_dir())
500            .profile(profile)
501            .define("LLVM_ENABLE_ASSERTIONS", assertions)
502            .define("LLVM_UNREACHABLE_OPTIMIZE", "OFF")
503            .define("LLVM_ENABLE_PLUGINS", plugins)
504            .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
505            .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
506            .define("LLVM_INCLUDE_EXAMPLES", "OFF")
507            .define("LLVM_INCLUDE_DOCS", "OFF")
508            .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
509            .define("LLVM_INCLUDE_TESTS", enable_tests)
510            .define("LLVM_ENABLE_LIBEDIT", "OFF")
511            .define("LLVM_ENABLE_BINDINGS", "OFF")
512            .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
513            .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
514            .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
515            .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native)
516            .define("LLVM_ENABLE_WARNINGS", enable_warnings);
517
518        // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
519        // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
520        // This flag makes sure `FileCheck` is copied in the final binaries directory.
521        cfg.define("LLVM_INSTALL_UTILS", "ON");
522
523        if let Some(mode) = builder.config.llvm_pgo.generate_profile.as_ref() {
524            cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
525            match mode {
526                LlvmPgoGenerationMode::Implicit => {}
527                LlvmPgoGenerationMode::Directory(llvm_profile_dir) => {
528                    cfg.define("LLVM_PROFILE_DATA_DIR", llvm_profile_dir);
529                }
530            }
531            cfg.define("LLVM_BUILD_RUNTIME", "No");
532        }
533        if let Some(path) = builder.config.llvm_pgo.use_profile.as_ref() {
534            cfg.define("LLVM_PROFDATA_FILE", path);
535        }
536
537        // Libraries for ELF section compression and profraw files merging.
538        if !target.is_msvc() {
539            cfg.define("LLVM_ENABLE_ZLIB", "ON");
540        } else {
541            cfg.define("LLVM_ENABLE_ZLIB", "OFF");
542        }
543
544        // Are we compiling for iOS/tvOS/watchOS/visionOS?
545        if target.contains("apple-ios")
546            || target.contains("apple-tvos")
547            || target.contains("apple-watchos")
548            || target.contains("apple-visionos")
549        {
550            // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
551            cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
552            // Zlib fails to link properly, leading to a compiler error.
553            cfg.define("LLVM_ENABLE_ZLIB", "OFF");
554        }
555
556        // This setting makes the LLVM tools link to the dynamic LLVM library,
557        // which saves both memory during parallel links and overall disk space
558        // for the tools. We don't do this on every platform as it doesn't work
559        // equally well everywhere.
560        //
561        // Under normal circumstances, the dylib LINK and BUILD vars below should
562        // be set to the same value. See #160597
563        let llvm_dylib = if link_shared { "ON" } else { "OFF" };
564        cfg.define("LLVM_LINK_LLVM_DYLIB", llvm_dylib);
565        cfg.define("LLVM_BUILD_LLVM_DYLIB", llvm_dylib);
566        // Keep the pre-LLVM23 behavior for now.
567        cfg.define("LLVM_VERSIONED_DYLIB_NAME_ON_DARWIN", "OFF");
568
569        if link_shared {
570            // We inform LLVM tools where they can find the LLVM library
571            // by adding an rpath entry to the expected parent `lib` directory,
572            // e.g. `rust-objcopy` is shipped in `lib/rustlib/<host>/bin`.
573            if let Some(rpath) = llvm_lib_rpath(builder, target) {
574                ldflags.exe.push(" ");
575                ldflags.exe.push(rpath);
576            }
577        }
578
579        if (target.starts_with("csky")
580            || target.starts_with("riscv")
581            || target.starts_with("sparc-"))
582            && !target.contains("freebsd")
583            && !target.contains("openbsd")
584            && !target.contains("netbsd")
585        {
586            // CSKY and RISC-V GCC erroneously requires linking against
587            // `libatomic` when using 1-byte and 2-byte C++
588            // atomics but the LLVM build system check cannot
589            // detect this. Therefore it is set manually here.
590            // Some BSD uses Clang as its system compiler and
591            // provides no libatomic in its base system so does
592            // not want this. 32-bit SPARC requires linking against
593            // libatomic as well.
594            ldflags.exe.push(" -latomic");
595            ldflags.shared.push(" -latomic");
596        }
597
598        if target.starts_with("mips") && target.contains("netbsd") {
599            // LLVM wants 64-bit atomics, while mipsel is 32-bit only, so needs -latomic
600            ldflags.exe.push(" -latomic");
601            ldflags.shared.push(" -latomic");
602        }
603
604        if target.starts_with("arm64ec") {
605            // MSVC linker requires the -machine:arm64ec flag to be passed to
606            // know it's linking as Arm64EC (vs Arm64X).
607            ldflags.exe.push(" -machine:arm64ec");
608            ldflags.shared.push(" -machine:arm64ec");
609        }
610
611        // cc-rs deprecated `static_flag`, which used to supply `-static` for musl
612        // targets, so pass it here instead.
613        if target.contains("musl") && builder.crt_static(target).unwrap_or(true) {
614            ldflags.exe.push(" -static");
615        }
616
617        if target.is_msvc() {
618            cfg.define("CMAKE_MSVC_RUNTIME_LIBRARY", "MultiThreaded");
619            cfg.static_crt(true);
620        }
621
622        if target.starts_with("i686") {
623            cfg.define("LLVM_BUILD_32_BITS", "ON");
624        }
625
626        if target.starts_with("x86_64") && target.contains("ohos") {
627            cfg.define("LLVM_TOOL_LLVM_RTDYLD_BUILD", "OFF");
628        }
629
630        let mut enabled_llvm_projects = Vec::new();
631
632        if helpers::forcing_clang_based_tests() {
633            enabled_llvm_projects.push("clang");
634        }
635
636        if builder.config.llvm_polly {
637            enabled_llvm_projects.push("polly");
638        }
639
640        if builder.config.llvm_clang {
641            enabled_llvm_projects.push("clang");
642        }
643
644        // We want libxml to be disabled.
645        // See https://github.com/rust-lang/rust/pull/50104
646        cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
647
648        let mut enabled_llvm_runtimes = Vec::new();
649
650        if helpers::forcing_clang_based_tests() {
651            enabled_llvm_runtimes.push("compiler-rt");
652        }
653
654        if !enabled_llvm_projects.is_empty() {
655            enabled_llvm_projects.sort();
656            enabled_llvm_projects.dedup();
657            cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
658        }
659
660        if !enabled_llvm_runtimes.is_empty() {
661            enabled_llvm_runtimes.sort();
662            enabled_llvm_runtimes.dedup();
663            cfg.define("LLVM_ENABLE_RUNTIMES", enabled_llvm_runtimes.join(";"));
664        }
665
666        if let Some(num_linkers) = builder.config.llvm_link_jobs
667            && num_linkers > 0
668        {
669            cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
670        }
671
672        // https://llvm.org/docs/HowToCrossCompileLLVM.html
673        if !builder.config.is_host_target(target) {
674            let llvm_host = builder.ensure(Llvm { target: builder.config.host_target });
675            if !builder.config.dry_run() {
676                let llvm_bindir = command(llvm_host.llvm_config())
677                    .arg("--bindir")
678                    .cached()
679                    .run_capture_stdout(builder)
680                    .stdout();
681                let host_bin = Path::new(llvm_bindir.trim());
682                cfg.define(
683                    "LLVM_TABLEGEN",
684                    host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION),
685                );
686                // LLVM_NM is required for cross compiling using MSVC
687                cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
688            }
689            cfg.define("LLVM_CONFIG_PATH", llvm_host.llvm_config());
690            if builder.config.llvm_clang {
691                let build_bin = llvm_host.root_dir().join("bin");
692                let clang_tblgen = build_bin.join("clang-tblgen").with_extension(EXE_EXTENSION);
693                if !builder.config.dry_run() && !clang_tblgen.exists() {
694                    panic!("unable to find {}", clang_tblgen.display());
695                }
696                cfg.define("CLANG_TABLEGEN", clang_tblgen);
697            }
698        }
699
700        let llvm_version_suffix = if let Some(ref suffix) = builder.config.llvm_version_suffix {
701            // Allow version-suffix="" to not define a version suffix at all.
702            if !suffix.is_empty() { Some(suffix.to_string()) } else { None }
703        } else if builder.config.channel == "dev" {
704            // Changes to a version suffix require a complete rebuild of the LLVM.
705            // To avoid rebuilds during a time of version bump, don't include rustc
706            // release number on the dev channel.
707            Some("-rust-dev".to_string())
708        } else {
709            Some(format!("-rust-{}-{}", builder.version, builder.config.channel))
710        };
711        if let Some(ref suffix) = llvm_version_suffix {
712            cfg.define("LLVM_VERSION_SUFFIX", suffix);
713        }
714
715        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
716        configure_llvm(builder, target, &mut cfg);
717
718        for (key, val) in &builder.config.llvm_build_config {
719            cfg.define(key, val);
720        }
721
722        if builder.config.dry_run() {
723            return output;
724        }
725
726        cfg.build();
727
728        // Helper to find the name of LLVM's shared library on darwin and linux.
729        let find_llvm_lib_name = |extension| {
730            let llvm_config = if target == builder.host_target {
731                output.llvm_config().to_path_buf()
732            } else {
733                builder.ensure(Llvm { target: builder.host_target }).llvm_config().to_path_buf()
734            };
735
736            let major = get_llvm_version_major(builder, &llvm_config);
737            match &llvm_version_suffix {
738                Some(version_suffix) => format!("libLLVM-{major}{version_suffix}.{extension}"),
739                None => format!("libLLVM-{major}.{extension}"),
740            }
741        };
742
743        // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
744        // libLLVM.dylib will be built. However, llvm-config will still look
745        // for a versioned path like libLLVM-14.dylib. Manually create a symbolic
746        // link to make llvm-config happy.
747        if link_shared && target.contains("apple-darwin") {
748            let lib_name = find_llvm_lib_name("dylib");
749            let lib_llvm = output.root_dir().join("build").join("lib").join(lib_name);
750            if !lib_llvm.exists() {
751                t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));
752            }
753        }
754
755        // When building LLVM as a shared library on linux, it can contain unexpected debuginfo:
756        // some can come from the C++ standard library. Unless we're explicitly requesting LLVM to
757        // be built with debuginfo, strip it away after the fact, to make dist artifacts smaller.
758        if link_shared && builder.config.llvm_optimize && !builder.config.llvm_release_debuginfo {
759            // Find the name of the LLVM shared library that we just built.
760            let lib_name = find_llvm_lib_name("so");
761
762            // If the shared library exists in LLVM's `/build/lib/` or `/lib/` folders, strip its
763            // debuginfo.
764            crate::core::build_steps::compile::strip_debug(
765                builder,
766                target,
767                &output.root_dir().join("lib").join(&lib_name),
768            );
769            crate::core::build_steps::compile::strip_debug(
770                builder,
771                target,
772                &output.root_dir().join("build").join("lib").join(&lib_name),
773            );
774        }
775
776        t!(stamp.write());
777
778        output
779    }
780
781    fn metadata(&self) -> Option<StepMetadata> {
782        Some(StepMetadata::build("llvm", self.target))
783    }
784}
785
786/// This has to be called with the **host** llvm-config!
787pub fn get_llvm_version(builder: &Builder<'_>, llvm_config: &Path) -> String {
788    command(llvm_config)
789        .arg("--version")
790        .cached()
791        .run_capture_stdout(builder)
792        .stdout()
793        .trim()
794        .to_owned()
795}
796
797/// This has to be called with the **host** llvm-config!
798pub fn get_llvm_version_major(builder: &Builder<'_>, llvm_config: &Path) -> u8 {
799    let version = get_llvm_version(builder, llvm_config);
800    let major_str = version.split_once('.').expect("Failed to parse LLVM version").0;
801    major_str.parse().unwrap()
802}
803
804fn get_llvm_profile(config: &Config) -> &'static str {
805    match (config.llvm_optimize, config.llvm_release_debuginfo) {
806        (false, _) => "Debug",
807        (true, false) => "Release",
808        (true, true) => "RelWithDebInfo",
809    }
810}
811
812fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
813    if builder.config.dry_run() {
814        return;
815    }
816
817    let version = get_llvm_version(builder, llvm_config);
818    let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
819    if let (Some(major), Some(_minor)) = (parts.next(), parts.next())
820        && major >= 22
821    {
822        return;
823    }
824    panic!("\n\nbad LLVM version: {version}, need >=22\n\n")
825}
826
827/// C/C++ debug info remap flags for LLVM build.
828///
829/// The remap is observable when LLVM is compiled with debug info,
830/// for example, with `llvm.release-debuginfo = true`.
831fn debuginfo_map_cflags(builder: &Builder<'_>, target: TargetSelection) -> Vec<String> {
832    if !builder.config.rust_remap_debuginfo {
833        return Vec::new();
834    }
835
836    let mut flags = Vec::new();
837    let map = format!("{}=/rustc/llvm", builder.src.display());
838    let cc = builder.cc_tool(target);
839    if cc.is_like_clang() || cc.is_like_gnu() {
840        flags.push(format!("-fdebug-prefix-map={map}"));
841    } else if cc.is_like_clang_cl() {
842        flags.push("-Xclang".into());
843        flags.push(format!("-fdebug-prefix-map={map}"));
844    }
845    flags
846}
847
848/// Tries to reuse a locally built LLD as a linker.
849/// If it is not available, uses a global LLD from PATH.
850fn try_link_with_in_tree_lld(
851    builder: &Builder<'_>,
852    target: TargetSelection,
853    llvm_output: &LlvmOutput,
854    cfg: &mut cmake::Config,
855    ldflags: &mut LdFlags,
856) {
857    // Apple has it's own ld64 linker, so don't use LLD on Darwin.
858    if target.contains("apple") {
859        return;
860    }
861
862    if builder.config.llvm_use_linker.is_some() || !builder.config.lld_enabled || target.is_msvc() {
863        // Logic derived from `configure_llvm`
864        // ThinLTO is only available when building with LLVM, enabling LLD is required.
865        if builder.config.llvm_thin_lto {
866            ldflags.push_all("-fuse-ld=lld");
867        }
868        return;
869    }
870
871    let lld_bin = builder.ensure(Lld { target }).join("bin");
872    ldflags.push_all(format!("-B{} -fuse-ld=lld", lld_bin.display()));
873
874    if llvm_output.link_shared() {
875        // LLD in this case needs the LLVM lib, so tell where to look for it.
876        let mut dylib_path = helpers::dylib_path();
877        dylib_path.insert(0, llvm_output.root_dir().join("lib"));
878        cfg.env(helpers::dylib_path_var(), t!(env::join_paths(&dylib_path)));
879    }
880}
881
882fn configure_cmake(
883    builder: &Builder<'_>,
884    target: TargetSelection,
885    cfg: &mut cmake::Config,
886    use_compiler_launcher: bool,
887    mut ldflags: LdFlags,
888    ccflags: CcFlags,
889    suppressed_compiler_flag_prefixes: &[&str],
890) {
891    // Do not print installation messages for up-to-date files.
892    // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
893    cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
894
895    if builder.config.quiet {
896        // Only log errors and warnings from `cmake`.
897        cfg.define("CMAKE_MESSAGE_LOG_LEVEL", "WARNING");
898
899        // If we're configuring llvm to build with `ninja`, we can suppress output from it with
900        // `--quiet`. Otherwise don't add anything since we don't know which build system is going
901        // to use.
902        if builder.ninja() {
903            cfg.build_arg("--quiet");
904        }
905    }
906
907    // Do not allow the user's value of DESTDIR to influence where
908    // LLVM will install itself. LLVM must always be installed in our
909    // own build directories.
910    cfg.env("DESTDIR", "");
911
912    if builder.ninja() {
913        cfg.generator("Ninja");
914    }
915    cfg.target(&target.triple).host(&builder.config.host_target.triple);
916
917    if !builder.config.is_host_target(target) {
918        cfg.define("CMAKE_CROSSCOMPILING", "True");
919
920        // NOTE: Ideally, we wouldn't have to do this, and `cmake-rs` would just handle it for us.
921        // But it currently determines this based on the `CARGO_CFG_TARGET_OS` environment variable,
922        // which isn't set when compiling outside `build.rs` (like bootstrap is).
923        //
924        // So for now, we define `CMAKE_SYSTEM_NAME` ourselves, to panicking in `cmake-rs`.
925        if target.contains("netbsd") {
926            cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
927        } else if target.contains("dragonfly") {
928            cfg.define("CMAKE_SYSTEM_NAME", "DragonFly");
929        } else if target.contains("openbsd") {
930            cfg.define("CMAKE_SYSTEM_NAME", "OpenBSD");
931        } else if target.contains("freebsd") {
932            cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
933        } else if target.is_windows() {
934            cfg.define("CMAKE_SYSTEM_NAME", "Windows");
935        } else if target.contains("haiku") {
936            cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
937        } else if target.contains("solaris") || target.contains("illumos") {
938            cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
939        } else if target.contains("linux") {
940            cfg.define("CMAKE_SYSTEM_NAME", "Linux");
941        } else if target.contains("darwin") {
942            // macOS
943            cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
944        } else if target.contains("ios") {
945            cfg.define("CMAKE_SYSTEM_NAME", "iOS");
946        } else if target.contains("tvos") {
947            cfg.define("CMAKE_SYSTEM_NAME", "tvOS");
948        } else if target.contains("visionos") {
949            cfg.define("CMAKE_SYSTEM_NAME", "visionOS");
950        } else if target.contains("watchos") {
951            cfg.define("CMAKE_SYSTEM_NAME", "watchOS");
952        } else if target.contains("none") {
953            // "none" should be the last branch
954            cfg.define("CMAKE_SYSTEM_NAME", "Generic");
955        } else {
956            builder.info(&format!(
957                "could not determine CMAKE_SYSTEM_NAME from the target `{target}`, build may fail",
958            ));
959            // Fallback, set `CMAKE_SYSTEM_NAME` anyhow to avoid the logic `cmake-rs` tries, and
960            // to avoid CMAKE_SYSTEM_NAME being inferred from the host.
961            cfg.define("CMAKE_SYSTEM_NAME", "Generic");
962        }
963
964        // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
965        // that case like CMake we cannot easily determine system version either.
966        //
967        // Since, the LLVM itself makes rather limited use of version checks in
968        // CMakeFiles (and then only in tests), and so far no issues have been
969        // reported, the system version is currently left unset.
970
971        if target.contains("apple") {
972            if !target.contains("darwin") {
973                // FIXME(madsmtm): compiler-rt's CMake setup is kinda weird, it seems like they do
974                // version testing etc. for macOS (i.e. Darwin), even while building for iOS?
975                //
976                // So for now we set it to "Darwin" on all Apple platforms.
977                cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
978
979                // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
980                cfg.define("CMAKE_OSX_SYSROOT", "/");
981                cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
982            }
983
984            // Make sure that CMake does not build universal binaries on macOS.
985            // Explicitly specify the one single target architecture.
986            if target.starts_with("aarch64") {
987                // macOS uses a different name for building arm64
988                cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
989            } else if target.starts_with("i686") {
990                // macOS uses a different name for building i386
991                cfg.define("CMAKE_OSX_ARCHITECTURES", "i386");
992            } else {
993                cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
994            }
995        }
996    }
997
998    let sanitize_cc = |cc: &Path| {
999        if target.is_msvc() {
1000            OsString::from(cc.to_str().unwrap().replace('\\', "/"))
1001        } else {
1002            cc.as_os_str().to_owned()
1003        }
1004    };
1005
1006    // MSVC with CMake uses msbuild by default which doesn't respect these
1007    // vars that we'd otherwise configure. In that case we just skip this
1008    // entirely.
1009    if target.is_msvc() && !builder.ninja() {
1010        return;
1011    }
1012
1013    let (cc, cxx) = match builder.config.llvm_clang_cl {
1014        Some(ref cl) => (cl.into(), cl.into()),
1015        None => (builder.cc(target), builder.cxx(target).unwrap()),
1016    };
1017
1018    // If ccache is configured we inform the build a little differently how
1019    // to invoke ccache while also invoking our compilers.
1020    if use_compiler_launcher && let Some(ref ccache) = builder.config.ccache {
1021        cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
1022            .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
1023    }
1024    cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
1025        .define("CMAKE_CXX_COMPILER", sanitize_cc(&cxx))
1026        .define("CMAKE_ASM_COMPILER", sanitize_cc(&cc));
1027
1028    // If we are running under a FIFO jobserver, we should not pass -j to CMake; otherwise it
1029    // overrides the jobserver settings and can lead to oversubscription.
1030    let has_modern_jobserver = env::var("MAKEFLAGS")
1031        .map(|flags| flags.contains("--jobserver-auth=fifo:"))
1032        .unwrap_or(false);
1033
1034    if !has_modern_jobserver {
1035        cfg.build_arg("-j").build_arg(builder.jobs().to_string());
1036    }
1037    let mut cflags = ccflags.cflags.clone();
1038    // FIXME(madsmtm): Allow `cmake-rs` to select flags by itself by passing
1039    // our flags via `.cflag`/`.cxxflag` instead.
1040    //
1041    // Needs `suppressed_compiler_flag_prefixes` to be gone, and hence
1042    // https://github.com/llvm/llvm-project/issues/88780 to be fixed.
1043    for flag in builder
1044        .cc_handled_cflags(target, CLang::C)
1045        .into_iter()
1046        .chain(builder.cc_unhandled_cflags(target, CLang::C))
1047        .chain(debuginfo_map_cflags(builder, target))
1048        .filter(|flag| !suppressed_compiler_flag_prefixes.iter().any(|p| flag.starts_with(p)))
1049    {
1050        cflags.push(" ");
1051        cflags.push(flag);
1052    }
1053    if let Some(ref s) = builder.config.llvm_cflags {
1054        cflags.push(" ");
1055        cflags.push(s);
1056    }
1057    if target.contains("ohos") {
1058        cflags.push(" -D_LINUX_SYSINFO_H");
1059    }
1060    if builder.config.llvm_clang_cl.is_some() {
1061        cflags.push(format!(" --target={target}"));
1062    }
1063    cfg.define("CMAKE_C_FLAGS", cflags);
1064    let mut cxxflags = ccflags.cxxflags.clone();
1065    for flag in builder
1066        .cc_handled_cflags(target, CLang::Cxx)
1067        .into_iter()
1068        .chain(builder.cc_unhandled_cflags(target, CLang::Cxx))
1069        .chain(debuginfo_map_cflags(builder, target))
1070        .filter(|flag| {
1071            !suppressed_compiler_flag_prefixes
1072                .iter()
1073                .any(|suppressed_prefix| flag.starts_with(suppressed_prefix))
1074        })
1075    {
1076        cxxflags.push(" ");
1077        cxxflags.push(flag);
1078    }
1079    if let Some(ref s) = builder.config.llvm_cxxflags {
1080        cxxflags.push(" ");
1081        cxxflags.push(s);
1082    }
1083    if target.contains("ohos") {
1084        cxxflags.push(" -D_LINUX_SYSINFO_H");
1085    }
1086    if builder.config.llvm_clang_cl.is_some() {
1087        cxxflags.push(format!(" --target={target}"));
1088    }
1089
1090    cfg.define("CMAKE_CXX_FLAGS", cxxflags);
1091    if let Some(ar) = builder.ar(target)
1092        && ar.is_absolute()
1093    {
1094        // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
1095        // tries to resolve this path in the LLVM build directory.
1096        cfg.define("CMAKE_AR", sanitize_cc(&ar));
1097    }
1098
1099    if let Some(ranlib) = builder.ranlib(target)
1100        && ranlib.is_absolute()
1101    {
1102        // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
1103        // tries to resolve this path in the LLVM build directory.
1104        cfg.define("CMAKE_RANLIB", sanitize_cc(&ranlib));
1105    }
1106
1107    if let Some(ref flags) = builder.config.llvm_ldflags {
1108        ldflags.push_all(flags);
1109    }
1110
1111    if let Some(flags) = get_var("LDFLAGS", &builder.config.host_target.triple, &target.triple) {
1112        ldflags.push_all(&flags);
1113    }
1114
1115    // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
1116    // We also do this if the user explicitly requested static libstdc++.
1117    if builder.config.llvm_static_stdcpp
1118        && !target.is_msvc()
1119        && !target.contains("netbsd")
1120        && !target.contains("solaris")
1121    {
1122        if target.contains("apple") || target.is_windows() {
1123            ldflags.push_all("-static-libstdc++");
1124        } else {
1125            ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
1126        }
1127    }
1128
1129    cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
1130    cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
1131    cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
1132
1133    if env::var_os("SCCACHE_ERROR_LOG").is_some() {
1134        cfg.env("RUSTC_LOG", "sccache=warn");
1135    }
1136}
1137
1138fn configure_llvm(builder: &Builder<'_>, target: TargetSelection, cfg: &mut cmake::Config) {
1139    // ThinLTO is only available when building with LLVM, enabling LLD is required.
1140    // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
1141    if builder.config.llvm_thin_lto {
1142        cfg.define("LLVM_ENABLE_LTO", "Thin");
1143        if !target.contains("apple") {
1144            cfg.define("LLVM_ENABLE_LLD", "ON");
1145        }
1146    }
1147
1148    // Libraries for ELF section compression.
1149    if builder.config.llvm_libzstd {
1150        cfg.define("LLVM_ENABLE_ZSTD", "FORCE_ON");
1151        cfg.define("LLVM_USE_STATIC_ZSTD", "TRUE");
1152    } else {
1153        cfg.define("LLVM_ENABLE_ZSTD", "OFF");
1154    }
1155
1156    if let Some(ref linker) = builder.config.llvm_use_linker {
1157        cfg.define("LLVM_USE_LINKER", linker);
1158    }
1159
1160    if builder.config.llvm_allow_old_toolchain {
1161        cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
1162    }
1163}
1164
1165// Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
1166fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
1167    let kind = if host == target { "HOST" } else { "TARGET" };
1168    let target_u = target.replace('-', "_");
1169    env::var_os(format!("{var_base}_{target}"))
1170        .or_else(|| env::var_os(format!("{var_base}_{target_u}")))
1171        .or_else(|| env::var_os(format!("{kind}_{var_base}")))
1172        .or_else(|| env::var_os(var_base))
1173}
1174
1175/// Generate a RPATH entry for a binary that will link to LLVM (libLLVM.so) dynamically.
1176/// This will make it possible to execute the binary outside Rustup, so that it can still find the libLLVM.so file.
1177fn llvm_lib_rpath(builder: &Builder<'_>, target: TargetSelection) -> Option<&'static str> {
1178    if builder.config.rpath_enabled(target) && helpers::use_host_linker(target) {
1179        // Be careful when changing this path, we need to ensure it's quoted or escaped:
1180        // `$ORIGIN` would otherwise be expanded when the `LdFlags` are passed verbatim to
1181        // cmake.
1182        if target.contains("linux") {
1183            return Some("-Wl,-rpath,'$ORIGIN/../../../'");
1184        }
1185        if target.contains("apple-darwin") {
1186            return Some("-Wl,-rpath,'@loader_path/../../../'");
1187        }
1188    }
1189    None
1190}
1191
1192#[derive(Clone)]
1193pub struct BuiltRustOffload {
1194    /// Path to the rust offload dylib
1195    offload: PathBuf,
1196}
1197
1198impl BuiltRustOffload {
1199    pub fn rust_offload_path(&self) -> PathBuf {
1200        self.offload.clone()
1201    }
1202
1203    pub fn rust_offload_filename(&self) -> String {
1204        self.offload.file_name().unwrap().to_str().unwrap().to_owned()
1205    }
1206}
1207
1208#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1209pub struct RustOffload {
1210    pub target: TargetSelection,
1211}
1212
1213impl CommandLineStep for RustOffload {
1214    type Output = BuiltRustOffload;
1215    const IS_HOST: bool = true;
1216
1217    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1218        run.alias("rust-offload")
1219    }
1220
1221    fn make_run(run: RunConfig<'_>) {
1222        run.builder.ensure(RustOffload { target: run.target });
1223    }
1224
1225    fn run(self, builder: &Builder<'_>) -> Self::Output {
1226        if builder.config.dry_run() {
1227            return BuiltRustOffload {
1228                offload: builder.config.tempdir().join("rust-offload-dry-run"),
1229            };
1230        }
1231
1232        let target = self.target;
1233
1234        let llvm_output = builder.ensure(Llvm { target });
1235
1236        let out_dir = builder.out.join(self.target.triple).join("rust-offload");
1237
1238        let llvm_version_major = get_llvm_version_major(builder, &builder.host_llvm_config());
1239        let lib_ext = std::env::consts::DLL_EXTENSION;
1240        let lib_rust_offload = format!("libRustOffload-{llvm_version_major}");
1241        let build_dir = out_dir.join(libdir(target));
1242        let dylib = build_dir.join(&lib_rust_offload).with_extension(lib_ext);
1243
1244        let mut cfg =
1245            cmake::Config::new(builder.src.join("compiler/rustc_llvm/llvm-wrapper/offload/"));
1246
1247        let mut ldflags = LdFlags::default();
1248        try_link_with_in_tree_lld(builder, target, &llvm_output, &mut cfg, &mut ldflags);
1249
1250        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
1251
1252        let profile = get_llvm_profile(&builder.config);
1253
1254        cfg.out_dir(&out_dir).profile(profile).define("LLVM_DIR", llvm_output.cmake_dir());
1255
1256        cfg.build();
1257
1258        if !dylib.exists() {
1259            eprintln!(
1260                "`{lib_rust_offload}` not found in `{}`. Either the build has failed or RustOffload was built with a wrong version of LLVM",
1261                build_dir.display()
1262            );
1263            helpers::exit_process(1);
1264        }
1265
1266        BuiltRustOffload { offload: dylib }
1267    }
1268}
1269
1270#[derive(Clone)]
1271pub struct BuiltOmpOffload {
1272    /// Path to the omp and offload dylibs.
1273    offload: Vec<PathBuf>,
1274    /// Directory the dylibs were installed into.
1275    lib_dir: PathBuf,
1276}
1277
1278impl BuiltOmpOffload {
1279    pub fn lib_dir(&self) -> &Path {
1280        &self.lib_dir
1281    }
1282
1283    pub fn artifact_paths_with_symlink_targets(&self) -> Vec<PathBuf> {
1284        let mut paths = self.offload.clone();
1285
1286        for path in &self.offload {
1287            let mut current = path.clone();
1288
1289            while t!(fs::symlink_metadata(&current)).file_type().is_symlink() {
1290                let target = t!(fs::read_link(&current));
1291                current = current.parent().unwrap().join(target);
1292
1293                if paths.contains(&current) {
1294                    break;
1295                }
1296
1297                paths.push(current.clone());
1298            }
1299        }
1300
1301        paths
1302    }
1303}
1304
1305// FIXME(offload): In an ideal world, we would just enable the offload runtime in our previous LLVM
1306// build step. For now, we still depend on the openmp runtime since we use some of it's API, so we
1307// build both. However, when building those runtimes as part of the LLVM step, then LLVM's cmake
1308// implicitly assumes that Clang has also been build and will try to use it. In the Rust CI, we
1309// don't always build clang (due to compile times), but instead use a slightly older external clang.
1310// LLVM tries to remove this build dependency of offload/openmp on Clang for LLVM-22, so in the
1311// future we might be able to integrate this step into the LLVM step. For now, we instead introduce
1312// a Clang_DIR bootstrap option, which allows us tell CMake to use an external clang for these two
1313// runtimes. This external clang will try to use it's own (older) include dirs when building our
1314// in-tree LLVM submodule, which will cause build failures. To prevent those, we now also
1315// explicitly set our include dirs.
1316#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1317pub struct OmpOffload {
1318    pub target: TargetSelection,
1319}
1320
1321impl CommandLineStep for OmpOffload {
1322    type Output = BuiltOmpOffload;
1323    const IS_HOST: bool = true;
1324
1325    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1326        run.path("src/llvm-project/offload")
1327    }
1328
1329    fn make_run(run: RunConfig<'_>) {
1330        run.builder.ensure(OmpOffload { target: run.target });
1331    }
1332
1333    /// Compile OpenMP offload runtimes for `target`.
1334    #[allow(unused)]
1335    fn run(self, builder: &Builder<'_>) -> Self::Output {
1336        if builder.config.dry_run() {
1337            let dry_run = builder.config.tempdir().join("llvm-offload-dry-run");
1338            return BuiltOmpOffload { offload: vec![dry_run.clone()], lib_dir: dry_run };
1339        }
1340        let target = self.target;
1341
1342        let llvm_output = builder.ensure(Llvm { target });
1343
1344        let out_dir = builder.out.join(self.target.triple).join("offload");
1345
1346        let lib_ext = std::env::consts::DLL_EXTENSION;
1347        let files = vec![
1348            out_dir.join("lib").join("libLLVMOffload").with_extension(lib_ext),
1349            out_dir.join("lib").join("libomp").with_extension(lib_ext),
1350            out_dir.join("lib").join("libomptarget").with_extension(lib_ext),
1351        ];
1352
1353        // Offload/OpenMP are just subfolders of LLVM, so we can use the LLVM sha.
1354        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1355        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1356            generate_smart_stamp_hash(
1357                builder,
1358                &builder.config.src.join("src/llvm-project/offload"),
1359                builder.in_tree_llvm_info.sha().unwrap_or_default(),
1360            )
1361        });
1362        let stamp = BuildStamp::new(&out_dir).with_prefix("offload").add_stamp(smart_stamp_hash);
1363
1364        trace!("checking build stamp to see if we need to rebuild offload/openmp artifacts");
1365        if stamp.is_up_to_date() {
1366            trace!(?out_dir, "offload/openmp build artifacts are up to date");
1367            if stamp.stamp().is_empty() {
1368                builder.info(
1369                    "Could not determine the Offload submodule commit hash. \
1370                     Assuming that an Offload rebuild is not necessary.",
1371                );
1372                builder.info(&format!(
1373                    "To force Offload/OpenMP to rebuild, remove the file `{}`",
1374                    stamp.path().display()
1375                ));
1376            }
1377            return BuiltOmpOffload { offload: files, lib_dir: out_dir.join("lib") };
1378        }
1379
1380        trace!(?target, "(re)building offload/openmp artifacts");
1381        builder.info(&format!("Building OpenMP/Offload for {target}"));
1382        t!(stamp.remove());
1383        let _time = helpers::timeit(builder);
1384        t!(fs::create_dir_all(&out_dir));
1385
1386        builder.config.update_submodule("src/llvm-project");
1387
1388        let offload_clang_dir = if !builder.config.llvm_clang {
1389            // We must have an external clang to use.
1390            builder.sess.config.offload_clang_dir.clone()
1391        } else {
1392            // No need to specify it, since we use the in-tree clang
1393            None
1394        };
1395
1396        // We currently build libompdevice by accident. It includes bitcode for our amd/nvptx
1397        // targets, and only the latest clang compiler can build those. We could stop building those
1398        // to fix this requirement, but we plan on instead building libc-for-gpu very soon, which
1399        // will have the same clang requirement, so we wouldn't save much. There are two ways in
1400        // which we can find a suitable clang. Either a user enabled the llvm.clang, in which case
1401        // we built our own clang based on the llvm submodule first, this always works. The
1402        // alternative is that the user sets the offload_clang_dir path, in which case they hopefully point
1403        // to a suitable clang, otherwise the build will fail.
1404        let clang_bin_dir = if builder.config.llvm_clang {
1405            llvm_output.llvm_config().parent().map(Path::to_path_buf)
1406        } else {
1407            // We expect the following (default) structure of the offload_clang_dir:
1408            // <prefix>/lib/cmake/clang, with a ClangConfig.cmake inside.
1409            // The clang binary is located in <prefix>/bin, so we go up three levels to find it.
1410            // This hardcodes the ClangConfig.cmake logic, which isn't great, so we filter for the
1411            // binary and error if we can't find it (presumably because LLVM build layout changed?).
1412            offload_clang_dir
1413                .as_deref()
1414                .and_then(|dir| dir.ancestors().nth(3))
1415                .map(|prefix| prefix.join("bin"))
1416        }
1417        .filter(|dir| dir.join(exe("clang", target)).exists());
1418
1419        let Some(clang_bin_dir) = clang_bin_dir else {
1420            eprintln!(
1421                "Building Offload requires a clang binary. Please either set `llvm.offload-clang-dir` or enable `llvm.clang` to build it."
1422            );
1423            helpers::exit_process(1);
1424        };
1425        let clang = clang_bin_dir.join(exe("clang", target));
1426        let clangxx = clang_bin_dir.join(exe("clang++", target));
1427
1428        // This was encountered when using gcc 13 to build the llvm submodule on a server, where no
1429        // clang was available. We first built clang along with llvm, and then switched over to use
1430        // the newly built clang to build the offload runtimes. Since we switched compiler, we have
1431        // to make sure that we're still using the same libstdc++ we used before. Without this
1432        // change, clang picked up a system libstdc++ from a different gcc and failed.
1433        let cxx_lib_dir = builder.cxx(target).ok().and_then(|cxx| {
1434            let stdout = command(&cxx)
1435                .arg("-print-file-name=libstdc++.so")
1436                .cached()
1437                .run_capture_stdout(builder)
1438                .stdout();
1439            let libstdcxx = PathBuf::from(stdout.trim());
1440            if !libstdcxx.is_absolute() {
1441                return None;
1442            }
1443            libstdcxx.parent().map(Path::to_path_buf)
1444        });
1445
1446        let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/runtimes/"));
1447
1448        // If we use an external clang as opposed to building our own llvm_clang, than that clang will
1449        // come with it's own set of default include directories, which are based on a potentially older
1450        // LLVM. This can cause issues, so we overwrite it to include headers based on our
1451        // `src/llvm-project` submodule instead.
1452        let mut cflags = CcFlags::default();
1453        if !builder.config.llvm_clang {
1454            let base = llvm_output.root_dir().join("include");
1455            let inc_dir = base.display();
1456            cflags.push_all(format!(" -I {inc_dir}"));
1457        }
1458
1459        let mut ldflags = LdFlags::default();
1460        try_link_with_in_tree_lld(builder, target, &llvm_output, &mut cfg, &mut ldflags);
1461
1462        if let Some(dir) = &cxx_lib_dir {
1463            ldflags.push_all(format!("-L{}", dir.display()));
1464        }
1465
1466        if llvm_output.link_shared() {
1467            // We inform libomptarget.so where it can find LLVM's libraries
1468            // by adding an rpath entry to the expected parent `lib` directory.
1469            if let Some(rpath) = llvm_lib_rpath(builder, target) {
1470                ldflags.push_all(rpath);
1471            }
1472        }
1473
1474        configure_cmake(builder, target, &mut cfg, true, ldflags, cflags, &[]);
1475
1476        cfg.define("CMAKE_C_COMPILER", &clang)
1477            .define("CMAKE_CXX_COMPILER", &clangxx)
1478            .define("CMAKE_ASM_COMPILER", &clang);
1479
1480        // Re-use the same flags as llvm to control the level of debug information
1481        // generated for offload.
1482        let profile = get_llvm_profile(&builder.config);
1483        trace!(?profile);
1484
1485        // FIXME(offload): Once we move from OMP to Offload (Ol) APIs, we should drop the openmp
1486        // runtime to simplify our build. So far, these are still under development.
1487        cfg.out_dir(&out_dir)
1488            .profile(profile)
1489            .define("LLVM_ENABLE_ASSERTIONS", "ON")
1490            .define("LLVM_INCLUDE_TESTS", "OFF")
1491            .define("OFFLOAD_INCLUDE_TESTS", "OFF")
1492            .define("LLVM_ROOT", llvm_output.root_dir().join("build"))
1493            .define("LLVM_DIR", llvm_output.cmake_dir())
1494            .define("LLVM_DEFAULT_TARGET_TRIPLE", &*target.triple);
1495        if let Some(p) = offload_clang_dir {
1496            cfg.define("Clang_DIR", p);
1497        }
1498
1499        // The offload library provides functionality which only makes sense on the host.
1500        cfg.define("LLVM_ENABLE_RUNTIMES", "openmp;offload");
1501
1502        cfg.build();
1503
1504        t!(stamp.write());
1505
1506        for p in &files {
1507            // At this point, `out_dir` should contain the built <offload-filename>.<dylib-ext>
1508            // files.
1509            if !p.exists() {
1510                eprintln!(
1511                    "`{p:?}` not found in `{}`. Either the build has failed or Offload was built with a wrong version of LLVM",
1512                    out_dir.display()
1513                );
1514                helpers::exit_process(1);
1515            }
1516        }
1517        BuiltOmpOffload { offload: files, lib_dir: out_dir.join("lib") }
1518    }
1519}
1520
1521#[derive(Clone)]
1522pub struct BuiltEnzyme {
1523    /// Path to the libEnzyme dylib.
1524    enzyme: PathBuf,
1525}
1526
1527impl BuiltEnzyme {
1528    pub fn enzyme_path(&self) -> PathBuf {
1529        self.enzyme.clone()
1530    }
1531    pub fn enzyme_filename(&self) -> String {
1532        self.enzyme.file_name().unwrap().to_str().unwrap().to_owned()
1533    }
1534}
1535
1536#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1537pub struct Enzyme {
1538    pub target: TargetSelection,
1539}
1540
1541impl CommandLineStep for Enzyme {
1542    type Output = BuiltEnzyme;
1543    const IS_HOST: bool = true;
1544
1545    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1546        run.path("src/tools/enzyme/enzyme")
1547    }
1548
1549    fn make_run(run: RunConfig<'_>) {
1550        run.builder.ensure(Enzyme { target: run.target });
1551    }
1552
1553    /// Compile Enzyme for `target`.
1554    fn run(self, builder: &Builder<'_>) -> Self::Output {
1555        builder.require_submodule(
1556            "src/tools/enzyme",
1557            Some("The Enzyme sources are required for autodiff."),
1558        );
1559        let target = self.target;
1560
1561        if builder.config.dry_run() {
1562            return BuiltEnzyme { enzyme: builder.config.tempdir().join("enzyme-dryrun") };
1563        }
1564
1565        let llvm_output = builder.ensure(Llvm { target });
1566
1567        // Enzyme links against LLVM. If we update the LLVM submodule libLLVM might get a new
1568        // version number, in which case Enzyme will now fail to find LLVM. By including the LLVM
1569        // hash into the Enzyme hash we force a rebuild of Enzyme when updating LLVM.
1570        let enzyme_hash_input = builder.in_tree_llvm_info.sha().unwrap_or_default().to_owned()
1571            + builder.enzyme_info.sha().unwrap_or_default();
1572
1573        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1574        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1575            generate_smart_stamp_hash(
1576                builder,
1577                &builder.config.src.join("src/tools/enzyme"),
1578                &enzyme_hash_input,
1579            )
1580        });
1581
1582        let out_dir = builder.out.join(self.target.triple).join("enzyme");
1583        let stamp = BuildStamp::new(&out_dir).with_prefix("enzyme").add_stamp(smart_stamp_hash);
1584
1585        let llvm_version_major = llvm::get_llvm_version_major(builder, &builder.host_llvm_config());
1586        let lib_ext = std::env::consts::DLL_EXTENSION;
1587        let libenzyme = format!("libEnzyme-{llvm_version_major}");
1588        let build_dir = out_dir.join(libdir(target));
1589        let dylib = build_dir.join(&libenzyme).with_extension(lib_ext);
1590
1591        trace!("checking build stamp to see if we need to rebuild enzyme artifacts");
1592        if stamp.is_up_to_date() {
1593            trace!(?out_dir, "enzyme build artifacts are up to date");
1594            if stamp.stamp().is_empty() {
1595                builder.info(
1596                    "Could not determine the Enzyme submodule commit hash. \
1597                     Assuming that an Enzyme rebuild is not necessary.",
1598                );
1599                builder.info(&format!(
1600                    "To force Enzyme to rebuild, remove the file `{}`",
1601                    stamp.path().display()
1602                ));
1603            }
1604            return BuiltEnzyme { enzyme: dylib };
1605        }
1606
1607        let llvm_cmake_dir = llvm_output.cmake_dir();
1608        if !builder.config.dry_run() && !llvm_cmake_dir.is_dir() {
1609            builder.info(&format!(
1610                "WARNING: {:?} does not exist, Enzyme build will likely fail",
1611                llvm_cmake_dir
1612            ));
1613        }
1614
1615        trace!(?target, "(re)building enzyme artifacts");
1616        builder.info(&format!("Building Enzyme for {target}"));
1617        t!(stamp.remove());
1618        let _time = helpers::timeit(builder);
1619        t!(fs::create_dir_all(&out_dir));
1620
1621        let mut cfg = cmake::Config::new(builder.src.join("src/tools/enzyme/enzyme/"));
1622        // Enzyme devs maintain upstream compatibility, but only fix deprecations when they are about
1623        // to turn into a hard error. As such, Enzyme generates various warnings which could make it
1624        // hard to spot more relevant issues.
1625        let mut cflags = CcFlags::default();
1626        cflags.push_all("-Wno-deprecated");
1627
1628        // Logic copied from `configure_llvm`
1629        // ThinLTO is only available when building with LLVM, enabling LLD is required.
1630        // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
1631        let mut ldflags = LdFlags::default();
1632        if builder.config.llvm_thin_lto && !target.contains("apple") {
1633            ldflags.push_all("-fuse-ld=lld");
1634        }
1635
1636        configure_cmake(builder, target, &mut cfg, true, ldflags, cflags, &[]);
1637
1638        // Re-use the same flags as llvm to control the level of debug information
1639        // generated by Enzyme.
1640        // FIXME(ZuseZ4): Find a nicer way to use Enzyme Debug builds.
1641        let profile = get_llvm_profile(&builder.config);
1642        trace!(?profile);
1643
1644        cfg.out_dir(&out_dir)
1645            .profile(profile)
1646            .define("LLVM_ENABLE_ASSERTIONS", "ON")
1647            .define("ENZYME_EXTERNAL_SHARED_LIB", "ON")
1648            .define("ENZYME_BC_LOADER", "OFF")
1649            .define("LLVM_DIR", llvm_cmake_dir);
1650
1651        cfg.build();
1652
1653        // At this point, `out_dir` should contain the built libEnzyme-<LLVM-version>.<dylib-ext>
1654        // file.
1655        if !dylib.exists() {
1656            eprintln!(
1657                "`{libenzyme}` not found in `{}`. Either the build has failed or Enzyme was built with a wrong version of LLVM",
1658                build_dir.display()
1659            );
1660            helpers::exit_process(1);
1661        }
1662
1663        t!(stamp.write());
1664        BuiltEnzyme { enzyme: dylib }
1665    }
1666}
1667
1668#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1669pub struct Lld {
1670    pub target: TargetSelection,
1671}
1672
1673impl CommandLineStep for Lld {
1674    type Output = PathBuf;
1675    const IS_HOST: bool = true;
1676
1677    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1678        run.path("src/llvm-project/lld")
1679    }
1680
1681    fn make_run(run: RunConfig<'_>) {
1682        run.builder.ensure(Lld { target: run.target });
1683    }
1684
1685    /// Compile LLD for `target`.
1686    fn run(self, builder: &Builder<'_>) -> PathBuf {
1687        if builder.config.dry_run() {
1688            return PathBuf::from("lld-out-dir-test-gen");
1689        }
1690        let target = self.target;
1691
1692        let llvm_output = builder.ensure(Llvm { target });
1693
1694        // The `dist` step packages LLD next to LLVM's binaries for download-ci-llvm. The root path
1695        // we usually expect here is `./build/$triple/ci-llvm/`, with the binaries in its `bin`
1696        // subfolder. We check if that's the case, and if LLD's binary already exists there next to
1697        // `llvm-config`: if so, we can use it instead of building LLVM/LLD from source.
1698        if matches!(llvm_output.kind, LlvmKind::DownloadedFromCi) {
1699            let bin_dir = llvm_output.root_dir().join("bin");
1700            let lld_path = bin_dir.join(exe("lld", target));
1701            if lld_path.exists() {
1702                // The following steps copying `lld` as `rust-lld` to the sysroot, expect it in the
1703                // `bin` subfolder of this step's out dir.
1704                return bin_dir.parent().unwrap().to_path_buf();
1705            }
1706        }
1707
1708        let out_dir = builder.out.join(target).join("lld");
1709
1710        let lld_stamp = BuildStamp::new(&out_dir).with_prefix("lld");
1711        if lld_stamp.path().exists() {
1712            return out_dir;
1713        }
1714
1715        let _guard = builder.msg_unstaged(Kind::Build, "LLD", target);
1716        let _time = helpers::timeit(builder);
1717        t!(fs::create_dir_all(&out_dir));
1718
1719        let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
1720        let mut ldflags = LdFlags::default();
1721
1722        // When building LLD as part of a build with instrumentation on windows, for example
1723        // when doing PGO on CI, cmake or clang-cl don't automatically link clang's
1724        // profiler runtime in. In that case, we need to manually ask cmake to do it, to avoid
1725        // linking errors, much like LLVM's cmake setup does in that situation.
1726        if builder.config.llvm_pgo.generate_profile.is_some()
1727            && target.is_msvc()
1728            && let Some(clang_cl_path) = builder.config.llvm_clang_cl.as_ref()
1729        {
1730            // Find clang's runtime library directory and push that as a search path to the
1731            // cmake linker flags.
1732            let clang_rt_dir = get_clang_cl_resource_dir(builder, clang_cl_path);
1733            ldflags.push_all(format!("/libpath:{}", clang_rt_dir.display()));
1734        }
1735
1736        // LLD is built as an LLVM tool, but is distributed outside of the `llvm-tools` component,
1737        // which impacts where it expects to find LLVM's shared library. This causes #80703.
1738        //
1739        // LLD is distributed at "$root/lib/rustlib/$host/bin/rust-lld", but the `libLLVM-*.so` it
1740        // needs is distributed at "$root/lib". The default rpath of "$ORIGIN/../lib" points at the
1741        // lib path for LLVM tools, not the one for rust binaries.
1742        //
1743        // (The `llvm-tools` component copies the .so there for the other tools, and with that
1744        // component installed, one can successfully invoke `rust-lld` directly without rustup's
1745        // `LD_LIBRARY_PATH` overrides)
1746        //
1747        if llvm_output.link_shared() {
1748            // So we inform LLD where it can find LLVM's libraries by adding an rpath entry to the
1749            // expected parent `lib` directory.
1750            if let Some(rpath) = llvm_lib_rpath(builder, target) {
1751                ldflags.push_all(rpath);
1752            }
1753        }
1754
1755        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
1756        configure_llvm(builder, target, &mut cfg);
1757
1758        // Re-use the same flags as llvm to control the level of debug information
1759        // generated for lld.
1760        let profile = get_llvm_profile(&builder.config);
1761
1762        cfg.out_dir(&out_dir)
1763            .profile(profile)
1764            .define("LLVM_CMAKE_DIR", llvm_output.cmake_dir())
1765            .define("LLVM_INCLUDE_TESTS", "OFF");
1766
1767        if !builder.config.is_host_target(target) {
1768            // Use the host llvm-tblgen binary.
1769            cfg.define(
1770                "LLVM_TABLEGEN_EXE",
1771                builder
1772                    .host_llvm_config()
1773                    .with_file_name("llvm-tblgen")
1774                    .with_extension(EXE_EXTENSION),
1775            );
1776        }
1777
1778        cfg.build();
1779
1780        t!(lld_stamp.write());
1781        out_dir
1782    }
1783}
1784
1785#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1786pub struct Sanitizers {
1787    pub target: TargetSelection,
1788}
1789
1790impl CommandLineStep for Sanitizers {
1791    type Output = Vec<SanitizerRuntime>;
1792
1793    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1794        run.alias("sanitizers")
1795    }
1796
1797    fn make_run(run: RunConfig<'_>) {
1798        run.builder.ensure(Sanitizers { target: run.target });
1799    }
1800
1801    /// Builds sanitizer runtime libraries.
1802    fn run(self, builder: &Builder<'_>) -> Self::Output {
1803        let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
1804        if !compiler_rt_dir.exists() {
1805            return Vec::new();
1806        }
1807
1808        let out_dir = builder.native_dir(self.target).join("sanitizers");
1809        let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
1810
1811        if builder.config.dry_run() || runtimes.is_empty() {
1812            return runtimes;
1813        }
1814
1815        let llvm_host = builder.ensure(Llvm { target: builder.config.host_target });
1816
1817        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1818        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1819            generate_smart_stamp_hash(
1820                builder,
1821                &builder.config.src.join("src/llvm-project/compiler-rt"),
1822                builder.in_tree_llvm_info.sha().unwrap_or_default(),
1823            )
1824        });
1825
1826        let stamp = BuildStamp::new(&out_dir).with_prefix("sanitizers").add_stamp(smart_stamp_hash);
1827
1828        if stamp.is_up_to_date() {
1829            if stamp.stamp().is_empty() {
1830                builder.info(&format!(
1831                    "Rebuild sanitizers by removing the file `{}`",
1832                    stamp.path().display()
1833                ));
1834            }
1835
1836            return runtimes;
1837        }
1838
1839        let _guard = builder.msg_unstaged(Kind::Build, "sanitizers", self.target);
1840        t!(stamp.remove());
1841        let _time = helpers::timeit(builder);
1842
1843        let mut cfg = cmake::Config::new(&compiler_rt_dir);
1844        cfg.profile("Release");
1845        cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
1846        cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
1847        cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
1848        cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
1849        cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
1850        cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
1851        cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
1852        cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
1853        cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
1854        cfg.define("LLVM_CONFIG_PATH", llvm_host.llvm_config());
1855
1856        if self.target.contains("ohos") {
1857            cfg.define("COMPILER_RT_USE_BUILTINS_LIBRARY", "ON");
1858        }
1859
1860        // On Darwin targets the sanitizer runtimes are build as universal binaries.
1861        // Unfortunately sccache currently lacks support to build them successfully.
1862        // Disable compiler launcher on Darwin targets to avoid potential issues.
1863        let use_compiler_launcher = !self.target.contains("apple-darwin");
1864        // Since v1.0.86, the cc crate adds -mmacosx-version-min to the default
1865        // flags on MacOS. A long-standing bug in the CMake rules for compiler-rt
1866        // causes architecture detection to be skipped when this flag is present,
1867        // and compilation fails. https://github.com/llvm/llvm-project/issues/88780
1868        let suppressed_compiler_flag_prefixes: &[&str] =
1869            if self.target.contains("apple-darwin") { &["-mmacosx-version-min="] } else { &[] };
1870        configure_cmake(
1871            builder,
1872            self.target,
1873            &mut cfg,
1874            use_compiler_launcher,
1875            LdFlags::default(),
1876            CcFlags::default(),
1877            suppressed_compiler_flag_prefixes,
1878        );
1879
1880        t!(fs::create_dir_all(&out_dir));
1881        cfg.out_dir(out_dir);
1882
1883        for runtime in &runtimes {
1884            cfg.build_target(&runtime.cmake_target);
1885            cfg.build();
1886        }
1887        t!(stamp.write());
1888
1889        runtimes
1890    }
1891}
1892
1893#[derive(Clone, Debug)]
1894pub struct SanitizerRuntime {
1895    /// CMake target used to build the runtime.
1896    pub cmake_target: String,
1897    /// Path to the built runtime library.
1898    pub path: PathBuf,
1899    /// Library filename that will be used rustc.
1900    pub name: String,
1901}
1902
1903/// Returns sanitizers available on a given target.
1904fn supported_sanitizers(
1905    out_dir: &Path,
1906    target: TargetSelection,
1907    channel: &str,
1908) -> Vec<SanitizerRuntime> {
1909    let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1910        components
1911            .iter()
1912            .map(move |c| {
1913                let cmake_c = if *c == "ubsan" { "ubsan_standalone" } else { *c };
1914                SanitizerRuntime {
1915                    cmake_target: format!("clang_rt.{cmake_c}_{os}_dynamic"),
1916                    path: out_dir
1917                        .join(format!("build/lib/darwin/libclang_rt.{cmake_c}_{os}_dynamic.dylib")),
1918                    name: format!("librustc-{channel}_rt.{c}.dylib"),
1919                }
1920            })
1921            .collect()
1922    };
1923
1924    let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1925        components
1926            .iter()
1927            .map(move |c| {
1928                let cmake_c = if *c == "ubsan" { "ubsan_standalone" } else { *c };
1929                SanitizerRuntime {
1930                    cmake_target: format!("clang_rt.{cmake_c}-{arch}"),
1931                    path: out_dir.join(format!("build/lib/{os}/libclang_rt.{cmake_c}-{arch}.a")),
1932                    name: format!("librustc-{channel}_rt.{c}.a"),
1933                }
1934            })
1935            .collect()
1936    };
1937
1938    match &*target.triple {
1939        "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),
1940        "aarch64-apple-ios" => darwin_libs("ios", &["asan", "tsan", "rtsan"]),
1941        "aarch64-apple-ios-sim" => darwin_libs("iossim", &["asan", "tsan", "rtsan"]),
1942        "aarch64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1943        "aarch64-unknown-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
1944        "aarch64-unknown-linux-gnu" => common_libs(
1945            "linux",
1946            "aarch64",
1947            &["asan", "lsan", "msan", "tsan", "hwasan", "rtsan", "ubsan", "ubsan_minimal"],
1948        ),
1949        "aarch64-unknown-linux-ohos" => {
1950            common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
1951        }
1952        "loongarch64-unknown-linux-gnu" | "loongarch64-unknown-linux-musl" => {
1953            common_libs("linux", "loongarch64", &["asan", "lsan", "msan", "tsan"])
1954        }
1955        "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),
1956        "x86_64-unknown-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
1957        "x86_64-apple-ios" => darwin_libs("iossim", &["asan", "tsan"]),
1958        "x86_64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1959        "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
1960        "x86_64-unknown-netbsd" => {
1961            common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
1962        }
1963        "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
1964        "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
1965        "x86_64-unknown-linux-gnu" => common_libs(
1966            "linux",
1967            "x86_64",
1968            &[
1969                "asan",
1970                "dfsan",
1971                "lsan",
1972                "msan",
1973                "safestack",
1974                "tsan",
1975                "rtsan",
1976                "ubsan",
1977                "ubsan_minimal",
1978            ],
1979        ),
1980        "x86_64-unknown-linux-gnuasan" => common_libs("linux", "x86_64", &["asan"]),
1981        "x86_64-unknown-linux-gnumsan" => common_libs("linux", "x86_64", &["msan"]),
1982        "x86_64-unknown-linux-gnutsan" => common_libs("linux", "x86_64", &["tsan"]),
1983        "x86_64-unknown-linux-musl" => {
1984            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1985        }
1986        "s390x-unknown-linux-gnu" => {
1987            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1988        }
1989        "s390x-unknown-linux-musl" => {
1990            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1991        }
1992        "x86_64-unknown-linux-ohos" => {
1993            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1994        }
1995        _ => Vec::new(),
1996    }
1997}
1998
1999#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2000pub struct CrtBeginEnd {
2001    pub target: TargetSelection,
2002}
2003
2004impl CommandLineStep for CrtBeginEnd {
2005    type Output = PathBuf;
2006
2007    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2008        run.path("src/llvm-project/compiler-rt/lib/crt")
2009    }
2010
2011    fn make_run(run: RunConfig<'_>) {
2012        if run.target.needs_crt_begin_end() {
2013            run.builder.ensure(CrtBeginEnd { target: run.target });
2014        }
2015    }
2016
2017    /// Build crtbegin.o/crtend.o for musl target.
2018    fn run(self, builder: &Builder<'_>) -> Self::Output {
2019        builder.require_submodule(
2020            "src/llvm-project",
2021            Some("The LLVM sources are required for the CRT from `compiler-rt`."),
2022        );
2023
2024        let out_dir = builder.native_dir(self.target).join("crt");
2025
2026        if builder.config.dry_run() {
2027            return out_dir;
2028        }
2029
2030        let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtbegin.c");
2031        let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtend.c");
2032        if up_to_date(&crtbegin_src, &out_dir.join("crtbeginS.o"))
2033            && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
2034        {
2035            return out_dir;
2036        }
2037
2038        let _guard = builder.msg_unstaged(Kind::Build, "crtbegin.o and crtend.o", self.target);
2039        t!(fs::create_dir_all(&out_dir));
2040
2041        let mut cfg = cc::Build::new();
2042
2043        if let Some(ar) = builder.ar(self.target) {
2044            cfg.archiver(ar);
2045        }
2046        cfg.compiler(builder.cc(self.target));
2047        cfg.cargo_metadata(false)
2048            .out_dir(&out_dir)
2049            .target(&self.target.triple)
2050            .host(&builder.config.host_target.triple)
2051            .warnings(false)
2052            .debug(false)
2053            .opt_level(3)
2054            .file(crtbegin_src)
2055            .file(crtend_src);
2056
2057        // Those flags are defined in src/llvm-project/compiler-rt/lib/builtins/CMakeLists.txt
2058        // Currently only consumer of those objects is musl, which use .init_array/.fini_array
2059        // instead of .ctors/.dtors
2060        cfg.flag("-std=c11")
2061            .define("CRT_HAS_INITFINI_ARRAY", None)
2062            .define("EH_USE_FRAME_REGISTRY", None);
2063
2064        let objs = cfg.compile_intermediates();
2065        assert_eq!(objs.len(), 2);
2066        for obj in objs {
2067            let base_name = unhashed_basename(&obj);
2068            assert!(base_name == "crtbegin" || base_name == "crtend");
2069            t!(fs::copy(&obj, out_dir.join(format!("{base_name}S.o"))));
2070            t!(fs::rename(&obj, out_dir.join(format!("{base_name}.o"))));
2071        }
2072
2073        out_dir
2074    }
2075}
2076
2077#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2078pub struct Libunwind {
2079    pub target: TargetSelection,
2080}
2081
2082impl CommandLineStep for Libunwind {
2083    type Output = PathBuf;
2084
2085    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2086        run.path("src/llvm-project/libunwind")
2087    }
2088
2089    fn make_run(run: RunConfig<'_>) {
2090        run.builder.ensure(Libunwind { target: run.target });
2091    }
2092
2093    /// Build libunwind.a
2094    fn run(self, builder: &Builder<'_>) -> Self::Output {
2095        builder.require_submodule(
2096            "src/llvm-project",
2097            Some("The LLVM sources are required for libunwind."),
2098        );
2099
2100        if builder.config.dry_run() {
2101            return PathBuf::new();
2102        }
2103
2104        let out_dir = builder.native_dir(self.target).join("libunwind");
2105        let root = builder.src.join("src/llvm-project/libunwind");
2106
2107        if up_to_date(&root, &out_dir.join("libunwind.a")) {
2108            return out_dir;
2109        }
2110
2111        let _guard = builder.msg_unstaged(Kind::Build, "libunwind.a", self.target);
2112        t!(fs::create_dir_all(&out_dir));
2113
2114        let mut cc_cfg = cc::Build::new();
2115        let mut cpp_cfg = cc::Build::new();
2116
2117        cpp_cfg.cpp(true);
2118        cpp_cfg.cpp_set_stdlib(None);
2119        cpp_cfg.flag("-nostdinc++");
2120        cpp_cfg.flag("-fno-exceptions");
2121        cpp_cfg.flag("-fno-rtti");
2122        cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
2123
2124        for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
2125            if let Some(ar) = builder.ar(self.target) {
2126                cfg.archiver(ar);
2127            }
2128            cfg.target(&self.target.triple);
2129            cfg.host(&builder.config.host_target.triple);
2130            cfg.warnings(false);
2131            cfg.debug(false);
2132            // get_compiler() need set opt_level first.
2133            cfg.opt_level(3);
2134            cfg.flag("-fstrict-aliasing");
2135            cfg.flag("-funwind-tables");
2136            cfg.flag("-fvisibility=hidden");
2137            cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
2138            cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");
2139            cfg.include(root.join("include"));
2140            cfg.cargo_metadata(false);
2141            cfg.out_dir(&out_dir);
2142
2143            if self.target.contains("x86_64-fortanix-unknown-sgx") {
2144                cfg.flag("-fno-stack-protector");
2145                cfg.flag("-ffreestanding");
2146                cfg.flag("-fexceptions");
2147
2148                // easiest way to undefine since no API available in cc::Build to undefine
2149                cfg.flag("-U_FORTIFY_SOURCE");
2150                cfg.define("_FORTIFY_SOURCE", "0");
2151                cfg.define("RUST_SGX", "1");
2152                cfg.define("__NO_STRING_INLINES", None);
2153                cfg.define("__NO_MATH_INLINES", None);
2154                cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
2155                cfg.define("NDEBUG", None);
2156            }
2157            if self.target.is_windows() {
2158                cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");
2159            }
2160        }
2161
2162        cc_cfg.compiler(builder.cc(self.target));
2163        if let Ok(cxx) = builder.cxx(self.target) {
2164            cpp_cfg.compiler(cxx);
2165        } else {
2166            cc_cfg.compiler(builder.cc(self.target));
2167        }
2168
2169        // Don't set this for clang
2170        // By default, Clang builds C code in GNU C17 mode.
2171        // By default, Clang builds C++ code according to the C++98 standard,
2172        // with many C++11 features accepted as extensions.
2173        if cc_cfg.get_compiler().is_like_gnu() {
2174            cc_cfg.flag("-std=c99");
2175        }
2176        if cpp_cfg.get_compiler().is_like_gnu() {
2177            cpp_cfg.flag("-std=c++11");
2178        }
2179
2180        if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
2181            // use the same GCC C compiler command to compile C++ code so we do not need to setup the
2182            // C++ compiler env variables on the builders.
2183            // Don't set this for clang++, as clang++ is able to compile this without libc++.
2184            if cpp_cfg.get_compiler().is_like_gnu() {
2185                cpp_cfg.cpp(false);
2186                cpp_cfg.compiler(builder.cc(self.target));
2187            }
2188        }
2189
2190        let mut c_sources = vec![
2191            "Unwind-sjlj.c",
2192            "UnwindLevel1-gcc-ext.c",
2193            "UnwindLevel1.c",
2194            "UnwindRegistersRestore.S",
2195            "UnwindRegistersSave.S",
2196        ];
2197
2198        let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
2199        let cpp_len = cpp_sources.len();
2200
2201        if self.target.contains("x86_64-fortanix-unknown-sgx") {
2202            c_sources.push("UnwindRustSgx.c");
2203        }
2204
2205        for src in c_sources {
2206            cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
2207        }
2208
2209        for src in &cpp_sources {
2210            cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
2211        }
2212
2213        cpp_cfg.compile("unwind-cpp");
2214
2215        // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
2216        let mut count = 0;
2217        let mut files = fs::read_dir(&out_dir)
2218            .unwrap()
2219            .map(|entry| entry.unwrap().path().canonicalize().unwrap())
2220            .collect::<Vec<_>>();
2221        files.sort();
2222        for file in files {
2223            if file.is_file() && file.extension() == Some(OsStr::new("o")) {
2224                // Object file name without the hash prefix is "Unwind-EHABI", "Unwind-seh" or "libunwind".
2225                let base_name = unhashed_basename(&file);
2226                if cpp_sources.iter().any(|f| *base_name == f[..f.len() - 4]) {
2227                    cc_cfg.object(&file);
2228                    count += 1;
2229                }
2230            }
2231        }
2232        assert_eq!(cpp_len, count, "Can't get object files from {out_dir:?}");
2233
2234        cc_cfg.compile("unwind");
2235        out_dir
2236    }
2237}
2238
2239/// Returns the path to `FileCheck` LLVM binary for the specified target.
2240#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2241pub struct FileCheck {
2242    pub target: TargetSelection,
2243}
2244
2245impl Step for FileCheck {
2246    type Output = PathBuf;
2247
2248    fn run(self, builder: &Builder<'_>) -> Self::Output {
2249        let target_config = builder.config.target_config.get(&self.target);
2250
2251        // The target configured filecheck, prefer it
2252        if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
2253            return s.clone();
2254        };
2255
2256        // There is a LLVM config set, take filecheck from it
2257        if let Some(llvm_config) = target_config.and_then(|c| c.llvm_config.as_ref()) {
2258            // We can only execute llvm-config if we're on the same host target
2259            return if builder.is_host_target(self.target) {
2260                let llvm_bindir =
2261                    command(llvm_config).arg("--bindir").run_capture_stdout(builder).stdout();
2262                let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", self.target));
2263
2264                if filecheck.exists() {
2265                    filecheck
2266                } else {
2267                    // On Fedora the system LLVM installs FileCheck in the
2268                    // llvm subdirectory of the libdir.
2269                    let llvm_libdir =
2270                        command(llvm_config).arg("--libdir").run_capture_stdout(builder).stdout();
2271                    let lib_filecheck = Path::new(llvm_libdir.trim())
2272                        .join("llvm")
2273                        .join(exe("FileCheck", self.target));
2274                    if lib_filecheck.exists() {
2275                        lib_filecheck
2276                    } else {
2277                        // Return the most normal file name, even though
2278                        // it doesn't exist, so that any error message
2279                        // refers to that.
2280                        filecheck
2281                    }
2282                }
2283            } else {
2284                // In other cases, just guess that Filecheck is available in the same directory
2285                // as the llvm-config
2286                llvm_config.parent().unwrap().join(exe("FileCheck", self.target))
2287            };
2288        }
2289        // Here we take the filecheck from LLVM directly
2290        let llvm_output = builder.ensure(Llvm { target: self.target });
2291        llvm_output.root_dir().join("bin").join(exe("FileCheck", self.target))
2292    }
2293}