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        if link_shared {
561            cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
562            // Keep the pre-LLVM23 behavior for now.
563            cfg.define("LLVM_VERSIONED_DYLIB_NAME_ON_DARWIN", "OFF");
564        }
565
566        if (target.starts_with("csky")
567            || target.starts_with("riscv")
568            || target.starts_with("sparc-"))
569            && !target.contains("freebsd")
570            && !target.contains("openbsd")
571            && !target.contains("netbsd")
572        {
573            // CSKY and RISC-V GCC erroneously requires linking against
574            // `libatomic` when using 1-byte and 2-byte C++
575            // atomics but the LLVM build system check cannot
576            // detect this. Therefore it is set manually here.
577            // Some BSD uses Clang as its system compiler and
578            // provides no libatomic in its base system so does
579            // not want this. 32-bit SPARC requires linking against
580            // libatomic as well.
581            ldflags.exe.push(" -latomic");
582            ldflags.shared.push(" -latomic");
583        }
584
585        if target.starts_with("mips") && target.contains("netbsd") {
586            // LLVM wants 64-bit atomics, while mipsel is 32-bit only, so needs -latomic
587            ldflags.exe.push(" -latomic");
588            ldflags.shared.push(" -latomic");
589        }
590
591        if target.starts_with("arm64ec") {
592            // MSVC linker requires the -machine:arm64ec flag to be passed to
593            // know it's linking as Arm64EC (vs Arm64X).
594            ldflags.exe.push(" -machine:arm64ec");
595            ldflags.shared.push(" -machine:arm64ec");
596        }
597
598        // cc-rs deprecated `static_flag`, which used to supply `-static` for musl
599        // targets, so pass it here instead.
600        if target.contains("musl") && builder.crt_static(target).unwrap_or(true) {
601            ldflags.exe.push(" -static");
602        }
603
604        if target.is_msvc() {
605            cfg.define("CMAKE_MSVC_RUNTIME_LIBRARY", "MultiThreaded");
606            cfg.static_crt(true);
607        }
608
609        if target.starts_with("i686") {
610            cfg.define("LLVM_BUILD_32_BITS", "ON");
611        }
612
613        if target.starts_with("x86_64") && target.contains("ohos") {
614            cfg.define("LLVM_TOOL_LLVM_RTDYLD_BUILD", "OFF");
615        }
616
617        let mut enabled_llvm_projects = Vec::new();
618
619        if helpers::forcing_clang_based_tests() {
620            enabled_llvm_projects.push("clang");
621        }
622
623        if builder.config.llvm_polly {
624            enabled_llvm_projects.push("polly");
625        }
626
627        if builder.config.llvm_clang {
628            enabled_llvm_projects.push("clang");
629        }
630
631        // We want libxml to be disabled.
632        // See https://github.com/rust-lang/rust/pull/50104
633        cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
634
635        let mut enabled_llvm_runtimes = Vec::new();
636
637        if helpers::forcing_clang_based_tests() {
638            enabled_llvm_runtimes.push("compiler-rt");
639        }
640
641        if !enabled_llvm_projects.is_empty() {
642            enabled_llvm_projects.sort();
643            enabled_llvm_projects.dedup();
644            cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
645        }
646
647        if !enabled_llvm_runtimes.is_empty() {
648            enabled_llvm_runtimes.sort();
649            enabled_llvm_runtimes.dedup();
650            cfg.define("LLVM_ENABLE_RUNTIMES", enabled_llvm_runtimes.join(";"));
651        }
652
653        if let Some(num_linkers) = builder.config.llvm_link_jobs
654            && num_linkers > 0
655        {
656            cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
657        }
658
659        // https://llvm.org/docs/HowToCrossCompileLLVM.html
660        if !builder.config.is_host_target(target) {
661            let llvm_host = builder.ensure(Llvm { target: builder.config.host_target });
662            if !builder.config.dry_run() {
663                let llvm_bindir = command(llvm_host.llvm_config())
664                    .arg("--bindir")
665                    .cached()
666                    .run_capture_stdout(builder)
667                    .stdout();
668                let host_bin = Path::new(llvm_bindir.trim());
669                cfg.define(
670                    "LLVM_TABLEGEN",
671                    host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION),
672                );
673                // LLVM_NM is required for cross compiling using MSVC
674                cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
675            }
676            cfg.define("LLVM_CONFIG_PATH", llvm_host.llvm_config());
677            if builder.config.llvm_clang {
678                let build_bin = llvm_host.root_dir().join("bin");
679                let clang_tblgen = build_bin.join("clang-tblgen").with_extension(EXE_EXTENSION);
680                if !builder.config.dry_run() && !clang_tblgen.exists() {
681                    panic!("unable to find {}", clang_tblgen.display());
682                }
683                cfg.define("CLANG_TABLEGEN", clang_tblgen);
684            }
685        }
686
687        let llvm_version_suffix = if let Some(ref suffix) = builder.config.llvm_version_suffix {
688            // Allow version-suffix="" to not define a version suffix at all.
689            if !suffix.is_empty() { Some(suffix.to_string()) } else { None }
690        } else if builder.config.channel == "dev" {
691            // Changes to a version suffix require a complete rebuild of the LLVM.
692            // To avoid rebuilds during a time of version bump, don't include rustc
693            // release number on the dev channel.
694            Some("-rust-dev".to_string())
695        } else {
696            Some(format!("-rust-{}-{}", builder.version, builder.config.channel))
697        };
698        if let Some(ref suffix) = llvm_version_suffix {
699            cfg.define("LLVM_VERSION_SUFFIX", suffix);
700        }
701
702        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
703        configure_llvm(builder, target, &mut cfg);
704
705        for (key, val) in &builder.config.llvm_build_config {
706            cfg.define(key, val);
707        }
708
709        if builder.config.dry_run() {
710            return output;
711        }
712
713        cfg.build();
714
715        // Helper to find the name of LLVM's shared library on darwin and linux.
716        let find_llvm_lib_name = |extension| {
717            let llvm_config = if target == builder.host_target {
718                output.llvm_config().to_path_buf()
719            } else {
720                builder.ensure(Llvm { target: builder.host_target }).llvm_config().to_path_buf()
721            };
722
723            let major = get_llvm_version_major(builder, &llvm_config);
724            match &llvm_version_suffix {
725                Some(version_suffix) => format!("libLLVM-{major}{version_suffix}.{extension}"),
726                None => format!("libLLVM-{major}.{extension}"),
727            }
728        };
729
730        // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
731        // libLLVM.dylib will be built. However, llvm-config will still look
732        // for a versioned path like libLLVM-14.dylib. Manually create a symbolic
733        // link to make llvm-config happy.
734        if link_shared && target.contains("apple-darwin") {
735            let lib_name = find_llvm_lib_name("dylib");
736            let lib_llvm = output.root_dir().join("build").join("lib").join(lib_name);
737            if !lib_llvm.exists() {
738                t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));
739            }
740        }
741
742        // When building LLVM as a shared library on linux, it can contain unexpected debuginfo:
743        // some can come from the C++ standard library. Unless we're explicitly requesting LLVM to
744        // be built with debuginfo, strip it away after the fact, to make dist artifacts smaller.
745        if link_shared && builder.config.llvm_optimize && !builder.config.llvm_release_debuginfo {
746            // Find the name of the LLVM shared library that we just built.
747            let lib_name = find_llvm_lib_name("so");
748
749            // If the shared library exists in LLVM's `/build/lib/` or `/lib/` folders, strip its
750            // debuginfo.
751            crate::core::build_steps::compile::strip_debug(
752                builder,
753                target,
754                &output.root_dir().join("lib").join(&lib_name),
755            );
756            crate::core::build_steps::compile::strip_debug(
757                builder,
758                target,
759                &output.root_dir().join("build").join("lib").join(&lib_name),
760            );
761        }
762
763        t!(stamp.write());
764
765        output
766    }
767
768    fn metadata(&self) -> Option<StepMetadata> {
769        Some(StepMetadata::build("llvm", self.target))
770    }
771}
772
773/// This has to be called with the **host** llvm-config!
774pub fn get_llvm_version(builder: &Builder<'_>, llvm_config: &Path) -> String {
775    command(llvm_config)
776        .arg("--version")
777        .cached()
778        .run_capture_stdout(builder)
779        .stdout()
780        .trim()
781        .to_owned()
782}
783
784/// This has to be called with the **host** llvm-config!
785pub fn get_llvm_version_major(builder: &Builder<'_>, llvm_config: &Path) -> u8 {
786    let version = get_llvm_version(builder, llvm_config);
787    let major_str = version.split_once('.').expect("Failed to parse LLVM version").0;
788    major_str.parse().unwrap()
789}
790
791fn get_llvm_profile(config: &Config) -> &'static str {
792    match (config.llvm_optimize, config.llvm_release_debuginfo) {
793        (false, _) => "Debug",
794        (true, false) => "Release",
795        (true, true) => "RelWithDebInfo",
796    }
797}
798
799fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
800    if builder.config.dry_run() {
801        return;
802    }
803
804    let version = get_llvm_version(builder, llvm_config);
805    let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
806    if let (Some(major), Some(_minor)) = (parts.next(), parts.next())
807        && major >= 21
808    {
809        return;
810    }
811    panic!("\n\nbad LLVM version: {version}, need >=21\n\n")
812}
813
814/// C/C++ debug info remap flags for LLVM build.
815///
816/// The remap is observable when LLVM is compiled with debug info,
817/// for example, with `llvm.release-debuginfo = true`.
818fn debuginfo_map_cflags(builder: &Builder<'_>, target: TargetSelection) -> Vec<String> {
819    if !builder.config.rust_remap_debuginfo {
820        return Vec::new();
821    }
822
823    let mut flags = Vec::new();
824    let map = format!("{}=/rustc/llvm", builder.src.display());
825    let cc = builder.cc_tool(target);
826    if cc.is_like_clang() || cc.is_like_gnu() {
827        flags.push(format!("-fdebug-prefix-map={map}"));
828    } else if cc.is_like_clang_cl() {
829        flags.push("-Xclang".into());
830        flags.push(format!("-fdebug-prefix-map={map}"));
831    }
832    flags
833}
834
835/// Tries to reuse a locally built LLD as a linker.
836/// If it is not available, uses a global LLD from PATH.
837fn try_link_with_in_tree_lld(
838    builder: &Builder<'_>,
839    target: TargetSelection,
840    llvm_output: &LlvmOutput,
841    cfg: &mut cmake::Config,
842    ldflags: &mut LdFlags,
843) {
844    // Apple has it's own ld64 linker, so don't use LLD on Darwin.
845    if target.contains("apple") {
846        return;
847    }
848
849    if builder.config.llvm_use_linker.is_some() || !builder.config.lld_enabled || target.is_msvc() {
850        // Logic derived from `configure_llvm`
851        // ThinLTO is only available when building with LLVM, enabling LLD is required.
852        if builder.config.llvm_thin_lto {
853            ldflags.push_all("-fuse-ld=lld");
854        }
855        return;
856    }
857
858    let lld_bin = builder.ensure(Lld { target }).join("bin");
859    ldflags.push_all(format!("-B{} -fuse-ld=lld", lld_bin.display()));
860
861    if llvm_output.link_shared() {
862        // LLD in this case needs the LLVM lib, so tell where to look for it.
863        let mut dylib_path = helpers::dylib_path();
864        dylib_path.insert(0, llvm_output.root_dir().join("lib"));
865        cfg.env(helpers::dylib_path_var(), t!(env::join_paths(&dylib_path)));
866    }
867}
868
869fn configure_cmake(
870    builder: &Builder<'_>,
871    target: TargetSelection,
872    cfg: &mut cmake::Config,
873    use_compiler_launcher: bool,
874    mut ldflags: LdFlags,
875    ccflags: CcFlags,
876    suppressed_compiler_flag_prefixes: &[&str],
877) {
878    // Do not print installation messages for up-to-date files.
879    // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
880    cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
881
882    if builder.config.quiet {
883        // Only log errors and warnings from `cmake`.
884        cfg.define("CMAKE_MESSAGE_LOG_LEVEL", "WARNING");
885
886        // If we're configuring llvm to build with `ninja`, we can suppress output from it with
887        // `--quiet`. Otherwise don't add anything since we don't know which build system is going
888        // to use.
889        if builder.ninja() {
890            cfg.build_arg("--quiet");
891        }
892    }
893
894    // Do not allow the user's value of DESTDIR to influence where
895    // LLVM will install itself. LLVM must always be installed in our
896    // own build directories.
897    cfg.env("DESTDIR", "");
898
899    if builder.ninja() {
900        cfg.generator("Ninja");
901    }
902    cfg.target(&target.triple).host(&builder.config.host_target.triple);
903
904    if !builder.config.is_host_target(target) {
905        cfg.define("CMAKE_CROSSCOMPILING", "True");
906
907        // NOTE: Ideally, we wouldn't have to do this, and `cmake-rs` would just handle it for us.
908        // But it currently determines this based on the `CARGO_CFG_TARGET_OS` environment variable,
909        // which isn't set when compiling outside `build.rs` (like bootstrap is).
910        //
911        // So for now, we define `CMAKE_SYSTEM_NAME` ourselves, to panicking in `cmake-rs`.
912        if target.contains("netbsd") {
913            cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
914        } else if target.contains("dragonfly") {
915            cfg.define("CMAKE_SYSTEM_NAME", "DragonFly");
916        } else if target.contains("openbsd") {
917            cfg.define("CMAKE_SYSTEM_NAME", "OpenBSD");
918        } else if target.contains("freebsd") {
919            cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
920        } else if target.is_windows() {
921            cfg.define("CMAKE_SYSTEM_NAME", "Windows");
922        } else if target.contains("haiku") {
923            cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
924        } else if target.contains("solaris") || target.contains("illumos") {
925            cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
926        } else if target.contains("linux") {
927            cfg.define("CMAKE_SYSTEM_NAME", "Linux");
928        } else if target.contains("darwin") {
929            // macOS
930            cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
931        } else if target.contains("ios") {
932            cfg.define("CMAKE_SYSTEM_NAME", "iOS");
933        } else if target.contains("tvos") {
934            cfg.define("CMAKE_SYSTEM_NAME", "tvOS");
935        } else if target.contains("visionos") {
936            cfg.define("CMAKE_SYSTEM_NAME", "visionOS");
937        } else if target.contains("watchos") {
938            cfg.define("CMAKE_SYSTEM_NAME", "watchOS");
939        } else if target.contains("none") {
940            // "none" should be the last branch
941            cfg.define("CMAKE_SYSTEM_NAME", "Generic");
942        } else {
943            builder.info(&format!(
944                "could not determine CMAKE_SYSTEM_NAME from the target `{target}`, build may fail",
945            ));
946            // Fallback, set `CMAKE_SYSTEM_NAME` anyhow to avoid the logic `cmake-rs` tries, and
947            // to avoid CMAKE_SYSTEM_NAME being inferred from the host.
948            cfg.define("CMAKE_SYSTEM_NAME", "Generic");
949        }
950
951        // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
952        // that case like CMake we cannot easily determine system version either.
953        //
954        // Since, the LLVM itself makes rather limited use of version checks in
955        // CMakeFiles (and then only in tests), and so far no issues have been
956        // reported, the system version is currently left unset.
957
958        if target.contains("apple") {
959            if !target.contains("darwin") {
960                // FIXME(madsmtm): compiler-rt's CMake setup is kinda weird, it seems like they do
961                // version testing etc. for macOS (i.e. Darwin), even while building for iOS?
962                //
963                // So for now we set it to "Darwin" on all Apple platforms.
964                cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
965
966                // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
967                cfg.define("CMAKE_OSX_SYSROOT", "/");
968                cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
969            }
970
971            // Make sure that CMake does not build universal binaries on macOS.
972            // Explicitly specify the one single target architecture.
973            if target.starts_with("aarch64") {
974                // macOS uses a different name for building arm64
975                cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
976            } else if target.starts_with("i686") {
977                // macOS uses a different name for building i386
978                cfg.define("CMAKE_OSX_ARCHITECTURES", "i386");
979            } else {
980                cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
981            }
982        }
983    }
984
985    let sanitize_cc = |cc: &Path| {
986        if target.is_msvc() {
987            OsString::from(cc.to_str().unwrap().replace('\\', "/"))
988        } else {
989            cc.as_os_str().to_owned()
990        }
991    };
992
993    // MSVC with CMake uses msbuild by default which doesn't respect these
994    // vars that we'd otherwise configure. In that case we just skip this
995    // entirely.
996    if target.is_msvc() && !builder.ninja() {
997        return;
998    }
999
1000    let (cc, cxx) = match builder.config.llvm_clang_cl {
1001        Some(ref cl) => (cl.into(), cl.into()),
1002        None => (builder.cc(target), builder.cxx(target).unwrap()),
1003    };
1004
1005    // If ccache is configured we inform the build a little differently how
1006    // to invoke ccache while also invoking our compilers.
1007    if use_compiler_launcher && let Some(ref ccache) = builder.config.ccache {
1008        cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
1009            .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
1010    }
1011    cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
1012        .define("CMAKE_CXX_COMPILER", sanitize_cc(&cxx))
1013        .define("CMAKE_ASM_COMPILER", sanitize_cc(&cc));
1014
1015    // If we are running under a FIFO jobserver, we should not pass -j to CMake; otherwise it
1016    // overrides the jobserver settings and can lead to oversubscription.
1017    let has_modern_jobserver = env::var("MAKEFLAGS")
1018        .map(|flags| flags.contains("--jobserver-auth=fifo:"))
1019        .unwrap_or(false);
1020
1021    if !has_modern_jobserver {
1022        cfg.build_arg("-j").build_arg(builder.jobs().to_string());
1023    }
1024    let mut cflags = ccflags.cflags.clone();
1025    // FIXME(madsmtm): Allow `cmake-rs` to select flags by itself by passing
1026    // our flags via `.cflag`/`.cxxflag` instead.
1027    //
1028    // Needs `suppressed_compiler_flag_prefixes` to be gone, and hence
1029    // https://github.com/llvm/llvm-project/issues/88780 to be fixed.
1030    for flag in builder
1031        .cc_handled_cflags(target, CLang::C)
1032        .into_iter()
1033        .chain(builder.cc_unhandled_cflags(target, CLang::C))
1034        .chain(debuginfo_map_cflags(builder, target))
1035        .filter(|flag| !suppressed_compiler_flag_prefixes.iter().any(|p| flag.starts_with(p)))
1036    {
1037        cflags.push(" ");
1038        cflags.push(flag);
1039    }
1040    if let Some(ref s) = builder.config.llvm_cflags {
1041        cflags.push(" ");
1042        cflags.push(s);
1043    }
1044    if target.contains("ohos") {
1045        cflags.push(" -D_LINUX_SYSINFO_H");
1046    }
1047    if builder.config.llvm_clang_cl.is_some() {
1048        cflags.push(format!(" --target={target}"));
1049    }
1050    cfg.define("CMAKE_C_FLAGS", cflags);
1051    let mut cxxflags = ccflags.cxxflags.clone();
1052    for flag in builder
1053        .cc_handled_cflags(target, CLang::Cxx)
1054        .into_iter()
1055        .chain(builder.cc_unhandled_cflags(target, CLang::Cxx))
1056        .chain(debuginfo_map_cflags(builder, target))
1057        .filter(|flag| {
1058            !suppressed_compiler_flag_prefixes
1059                .iter()
1060                .any(|suppressed_prefix| flag.starts_with(suppressed_prefix))
1061        })
1062    {
1063        cxxflags.push(" ");
1064        cxxflags.push(flag);
1065    }
1066    if let Some(ref s) = builder.config.llvm_cxxflags {
1067        cxxflags.push(" ");
1068        cxxflags.push(s);
1069    }
1070    if target.contains("ohos") {
1071        cxxflags.push(" -D_LINUX_SYSINFO_H");
1072    }
1073    if builder.config.llvm_clang_cl.is_some() {
1074        cxxflags.push(format!(" --target={target}"));
1075    }
1076
1077    cfg.define("CMAKE_CXX_FLAGS", cxxflags);
1078    if let Some(ar) = builder.ar(target)
1079        && ar.is_absolute()
1080    {
1081        // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
1082        // tries to resolve this path in the LLVM build directory.
1083        cfg.define("CMAKE_AR", sanitize_cc(&ar));
1084    }
1085
1086    if let Some(ranlib) = builder.ranlib(target)
1087        && ranlib.is_absolute()
1088    {
1089        // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
1090        // tries to resolve this path in the LLVM build directory.
1091        cfg.define("CMAKE_RANLIB", sanitize_cc(&ranlib));
1092    }
1093
1094    if let Some(ref flags) = builder.config.llvm_ldflags {
1095        ldflags.push_all(flags);
1096    }
1097
1098    if let Some(flags) = get_var("LDFLAGS", &builder.config.host_target.triple, &target.triple) {
1099        ldflags.push_all(&flags);
1100    }
1101
1102    // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
1103    // We also do this if the user explicitly requested static libstdc++.
1104    if builder.config.llvm_static_stdcpp
1105        && !target.is_msvc()
1106        && !target.contains("netbsd")
1107        && !target.contains("solaris")
1108    {
1109        if target.contains("apple") || target.is_windows() {
1110            ldflags.push_all("-static-libstdc++");
1111        } else {
1112            ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
1113        }
1114    }
1115
1116    cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
1117    cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
1118    cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
1119
1120    if env::var_os("SCCACHE_ERROR_LOG").is_some() {
1121        cfg.env("RUSTC_LOG", "sccache=warn");
1122    }
1123}
1124
1125fn configure_llvm(builder: &Builder<'_>, target: TargetSelection, cfg: &mut cmake::Config) {
1126    // ThinLTO is only available when building with LLVM, enabling LLD is required.
1127    // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
1128    if builder.config.llvm_thin_lto {
1129        cfg.define("LLVM_ENABLE_LTO", "Thin");
1130        if !target.contains("apple") {
1131            cfg.define("LLVM_ENABLE_LLD", "ON");
1132        }
1133    }
1134
1135    // Libraries for ELF section compression.
1136    if builder.config.llvm_libzstd {
1137        cfg.define("LLVM_ENABLE_ZSTD", "FORCE_ON");
1138        cfg.define("LLVM_USE_STATIC_ZSTD", "TRUE");
1139    } else {
1140        cfg.define("LLVM_ENABLE_ZSTD", "OFF");
1141    }
1142
1143    if let Some(ref linker) = builder.config.llvm_use_linker {
1144        cfg.define("LLVM_USE_LINKER", linker);
1145    }
1146
1147    if builder.config.llvm_allow_old_toolchain {
1148        cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
1149    }
1150}
1151
1152// Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
1153fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
1154    let kind = if host == target { "HOST" } else { "TARGET" };
1155    let target_u = target.replace('-', "_");
1156    env::var_os(format!("{var_base}_{target}"))
1157        .or_else(|| env::var_os(format!("{var_base}_{target_u}")))
1158        .or_else(|| env::var_os(format!("{kind}_{var_base}")))
1159        .or_else(|| env::var_os(var_base))
1160}
1161
1162#[derive(Clone)]
1163pub struct BuiltRustOffload {
1164    /// Path to the rust offload dylib
1165    offload: PathBuf,
1166}
1167
1168impl BuiltRustOffload {
1169    pub fn rust_offload_path(&self) -> PathBuf {
1170        self.offload.clone()
1171    }
1172
1173    pub fn rust_offload_filename(&self) -> String {
1174        self.offload.file_name().unwrap().to_str().unwrap().to_owned()
1175    }
1176}
1177
1178#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1179pub struct RustOffload {
1180    pub target: TargetSelection,
1181}
1182
1183impl CommandLineStep for RustOffload {
1184    type Output = BuiltRustOffload;
1185    const IS_HOST: bool = true;
1186
1187    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1188        run.alias("rust-offload")
1189    }
1190
1191    fn make_run(run: RunConfig<'_>) {
1192        run.builder.ensure(RustOffload { target: run.target });
1193    }
1194
1195    fn run(self, builder: &Builder<'_>) -> Self::Output {
1196        if builder.config.dry_run() {
1197            return BuiltRustOffload {
1198                offload: builder.config.tempdir().join("rust-offload-dry-run"),
1199            };
1200        }
1201
1202        let target = self.target;
1203
1204        let llvm_output = builder.ensure(Llvm { target });
1205
1206        let out_dir = builder.out.join(self.target.triple).join("rust-offload");
1207
1208        let llvm_version_major = get_llvm_version_major(builder, &builder.host_llvm_config());
1209        let lib_ext = std::env::consts::DLL_EXTENSION;
1210        let lib_rust_offload = format!("libRustOffload-{llvm_version_major}");
1211        let build_dir = out_dir.join(libdir(target));
1212        let dylib = build_dir.join(&lib_rust_offload).with_extension(lib_ext);
1213
1214        let mut cfg =
1215            cmake::Config::new(builder.src.join("compiler/rustc_llvm/llvm-wrapper/offload/"));
1216
1217        let mut ldflags = LdFlags::default();
1218        try_link_with_in_tree_lld(builder, target, &llvm_output, &mut cfg, &mut ldflags);
1219
1220        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
1221
1222        let profile = get_llvm_profile(&builder.config);
1223
1224        cfg.out_dir(&out_dir).profile(profile).define("LLVM_DIR", llvm_output.cmake_dir());
1225
1226        cfg.build();
1227
1228        if !dylib.exists() {
1229            eprintln!(
1230                "`{lib_rust_offload}` not found in `{}`. Either the build has failed or RustOffload was built with a wrong version of LLVM",
1231                build_dir.display()
1232            );
1233            helpers::exit_process(1);
1234        }
1235
1236        BuiltRustOffload { offload: dylib }
1237    }
1238}
1239
1240#[derive(Clone)]
1241pub struct BuiltOmpOffload {
1242    /// Path to the omp and offload dylibs.
1243    offload: Vec<PathBuf>,
1244    /// Directory the dylibs were installed into.
1245    lib_dir: PathBuf,
1246}
1247
1248impl BuiltOmpOffload {
1249    pub fn lib_dir(&self) -> &Path {
1250        &self.lib_dir
1251    }
1252
1253    pub fn artifact_paths_with_symlink_targets(&self) -> Vec<PathBuf> {
1254        let mut paths = self.offload.clone();
1255
1256        for path in &self.offload {
1257            let mut current = path.clone();
1258
1259            while t!(fs::symlink_metadata(&current)).file_type().is_symlink() {
1260                let target = t!(fs::read_link(&current));
1261                current = current.parent().unwrap().join(target);
1262
1263                if paths.contains(&current) {
1264                    break;
1265                }
1266
1267                paths.push(current.clone());
1268            }
1269        }
1270
1271        paths
1272    }
1273}
1274
1275// FIXME(offload): In an ideal world, we would just enable the offload runtime in our previous LLVM
1276// build step. For now, we still depend on the openmp runtime since we use some of it's API, so we
1277// build both. However, when building those runtimes as part of the LLVM step, then LLVM's cmake
1278// implicitly assumes that Clang has also been build and will try to use it. In the Rust CI, we
1279// don't always build clang (due to compile times), but instead use a slightly older external clang.
1280// LLVM tries to remove this build dependency of offload/openmp on Clang for LLVM-22, so in the
1281// future we might be able to integrate this step into the LLVM step. For now, we instead introduce
1282// a Clang_DIR bootstrap option, which allows us tell CMake to use an external clang for these two
1283// runtimes. This external clang will try to use it's own (older) include dirs when building our
1284// in-tree LLVM submodule, which will cause build failures. To prevent those, we now also
1285// explicitly set our include dirs.
1286#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1287pub struct OmpOffload {
1288    pub target: TargetSelection,
1289}
1290
1291impl CommandLineStep for OmpOffload {
1292    type Output = BuiltOmpOffload;
1293    const IS_HOST: bool = true;
1294
1295    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1296        run.path("src/llvm-project/offload")
1297    }
1298
1299    fn make_run(run: RunConfig<'_>) {
1300        run.builder.ensure(OmpOffload { target: run.target });
1301    }
1302
1303    /// Compile OpenMP offload runtimes for `target`.
1304    #[allow(unused)]
1305    fn run(self, builder: &Builder<'_>) -> Self::Output {
1306        if builder.config.dry_run() {
1307            let dry_run = builder.config.tempdir().join("llvm-offload-dry-run");
1308            return BuiltOmpOffload { offload: vec![dry_run.clone()], lib_dir: dry_run };
1309        }
1310        let target = self.target;
1311
1312        let llvm_output = builder.ensure(Llvm { target });
1313
1314        let out_dir = builder.out.join(self.target.triple).join("offload");
1315
1316        let lib_ext = std::env::consts::DLL_EXTENSION;
1317        let files = vec![
1318            out_dir.join("lib").join("libLLVMOffload").with_extension(lib_ext),
1319            out_dir.join("lib").join("libomp").with_extension(lib_ext),
1320            out_dir.join("lib").join("libomptarget").with_extension(lib_ext),
1321        ];
1322
1323        // Offload/OpenMP are just subfolders of LLVM, so we can use the LLVM sha.
1324        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1325        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1326            generate_smart_stamp_hash(
1327                builder,
1328                &builder.config.src.join("src/llvm-project/offload"),
1329                builder.in_tree_llvm_info.sha().unwrap_or_default(),
1330            )
1331        });
1332        let stamp = BuildStamp::new(&out_dir).with_prefix("offload").add_stamp(smart_stamp_hash);
1333
1334        trace!("checking build stamp to see if we need to rebuild offload/openmp artifacts");
1335        if stamp.is_up_to_date() {
1336            trace!(?out_dir, "offload/openmp build artifacts are up to date");
1337            if stamp.stamp().is_empty() {
1338                builder.info(
1339                    "Could not determine the Offload submodule commit hash. \
1340                     Assuming that an Offload rebuild is not necessary.",
1341                );
1342                builder.info(&format!(
1343                    "To force Offload/OpenMP to rebuild, remove the file `{}`",
1344                    stamp.path().display()
1345                ));
1346            }
1347            return BuiltOmpOffload { offload: files, lib_dir: out_dir.join("lib") };
1348        }
1349
1350        trace!(?target, "(re)building offload/openmp artifacts");
1351        builder.info(&format!("Building OpenMP/Offload for {target}"));
1352        t!(stamp.remove());
1353        let _time = helpers::timeit(builder);
1354        t!(fs::create_dir_all(&out_dir));
1355
1356        builder.config.update_submodule("src/llvm-project");
1357
1358        let offload_clang_dir = if !builder.config.llvm_clang {
1359            // We must have an external clang to use.
1360            builder.sess.config.offload_clang_dir.clone()
1361        } else {
1362            // No need to specify it, since we use the in-tree clang
1363            None
1364        };
1365
1366        // We currently build libompdevice by accident. It includes bitcode for our amd/nvptx
1367        // targets, and only the latest clang compiler can build those. We could stop building those
1368        // to fix this requirement, but we plan on instead building libc-for-gpu very soon, which
1369        // will have the same clang requirement, so we wouldn't save much. There are two ways in
1370        // which we can find a suitable clang. Either a user enabled the llvm.clang, in which case
1371        // we built our own clang based on the llvm submodule first, this always works. The
1372        // alternative is that the user sets the offload_clang_dir path, in which case they hopefully point
1373        // to a suitable clang, otherwise the build will fail.
1374        let clang_bin_dir = if builder.config.llvm_clang {
1375            llvm_output.llvm_config().parent().map(Path::to_path_buf)
1376        } else {
1377            // We expect the following (default) structure of the offload_clang_dir:
1378            // <prefix>/lib/cmake/clang, with a ClangConfig.cmake inside.
1379            // The clang binary is located in <prefix>/bin, so we go up three levels to find it.
1380            // This hardcodes the ClangConfig.cmake logic, which isn't great, so we filter for the
1381            // binary and error if we can't find it (presumably because LLVM build layout changed?).
1382            offload_clang_dir
1383                .as_deref()
1384                .and_then(|dir| dir.ancestors().nth(3))
1385                .map(|prefix| prefix.join("bin"))
1386        }
1387        .filter(|dir| dir.join(exe("clang", target)).exists());
1388
1389        let Some(clang_bin_dir) = clang_bin_dir else {
1390            eprintln!(
1391                "Building Offload requires a clang binary. Please either set `llvm.offload-clang-dir` or enable `llvm.clang` to build it."
1392            );
1393            helpers::exit_process(1);
1394        };
1395        let clang = clang_bin_dir.join(exe("clang", target));
1396        let clangxx = clang_bin_dir.join(exe("clang++", target));
1397
1398        // This was encountered when using gcc 13 to build the llvm submodule on a server, where no
1399        // clang was available. We first built clang along with llvm, and then switched over to use
1400        // the newly built clang to build the offload runtimes. Since we switched compiler, we have
1401        // to make sure that we're still using the same libstdc++ we used before. Without this
1402        // change, clang picked up a system libstdc++ from a different gcc and failed.
1403        let cxx_lib_dir = builder.cxx(target).ok().and_then(|cxx| {
1404            let stdout = command(&cxx)
1405                .arg("-print-file-name=libstdc++.so")
1406                .cached()
1407                .run_capture_stdout(builder)
1408                .stdout();
1409            let libstdcxx = PathBuf::from(stdout.trim());
1410            if !libstdcxx.is_absolute() {
1411                return None;
1412            }
1413            libstdcxx.parent().map(Path::to_path_buf)
1414        });
1415
1416        let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/runtimes/"));
1417
1418        // If we use an external clang as opposed to building our own llvm_clang, than that clang will
1419        // come with it's own set of default include directories, which are based on a potentially older
1420        // LLVM. This can cause issues, so we overwrite it to include headers based on our
1421        // `src/llvm-project` submodule instead.
1422        let mut cflags = CcFlags::default();
1423        if !builder.config.llvm_clang {
1424            let base = llvm_output.root_dir().join("include");
1425            let inc_dir = base.display();
1426            cflags.push_all(format!(" -I {inc_dir}"));
1427        }
1428
1429        let mut ldflags = LdFlags::default();
1430        try_link_with_in_tree_lld(builder, target, &llvm_output, &mut cfg, &mut ldflags);
1431
1432        if let Some(dir) = &cxx_lib_dir {
1433            ldflags.push_all(format!("-L{}", dir.display()));
1434        }
1435
1436        if builder.config.rpath_enabled(target)
1437            && helpers::use_host_linker(target)
1438            && llvm_output.link_shared()
1439            && target.contains("linux")
1440        {
1441            // Same logic as in Lld::run
1442            // We inform libomptarget.so where it can find LLVM's libraries
1443            // by adding an rpath entry to the expected parent `lib` directory.
1444            //
1445            // Be careful when changing this path, we need to ensure it's quoted or escaped:
1446            // `$ORIGIN` would otherwise be expanded when the `LdFlags` are passed verbatim to
1447            // cmake.
1448            ldflags.push_all("-Wl,-rpath,'$ORIGIN/../../../'");
1449        }
1450
1451        configure_cmake(builder, target, &mut cfg, true, ldflags, cflags, &[]);
1452
1453        cfg.define("CMAKE_C_COMPILER", &clang)
1454            .define("CMAKE_CXX_COMPILER", &clangxx)
1455            .define("CMAKE_ASM_COMPILER", &clang);
1456
1457        // Re-use the same flags as llvm to control the level of debug information
1458        // generated for offload.
1459        let profile = get_llvm_profile(&builder.config);
1460        trace!(?profile);
1461
1462        // FIXME(offload): Once we move from OMP to Offload (Ol) APIs, we should drop the openmp
1463        // runtime to simplify our build. So far, these are still under development.
1464        cfg.out_dir(&out_dir)
1465            .profile(profile)
1466            .define("LLVM_ENABLE_ASSERTIONS", "ON")
1467            .define("LLVM_INCLUDE_TESTS", "OFF")
1468            .define("OFFLOAD_INCLUDE_TESTS", "OFF")
1469            .define("LLVM_ROOT", llvm_output.root_dir().join("build"))
1470            .define("LLVM_DIR", llvm_output.cmake_dir())
1471            .define("LLVM_DEFAULT_TARGET_TRIPLE", &*target.triple);
1472        if let Some(p) = offload_clang_dir {
1473            cfg.define("Clang_DIR", p);
1474        }
1475
1476        // The offload library provides functionality which only makes sense on the host.
1477        cfg.define("LLVM_ENABLE_RUNTIMES", "openmp;offload");
1478
1479        cfg.build();
1480
1481        t!(stamp.write());
1482
1483        for p in &files {
1484            // At this point, `out_dir` should contain the built <offload-filename>.<dylib-ext>
1485            // files.
1486            if !p.exists() {
1487                eprintln!(
1488                    "`{p:?}` not found in `{}`. Either the build has failed or Offload was built with a wrong version of LLVM",
1489                    out_dir.display()
1490                );
1491                helpers::exit_process(1);
1492            }
1493        }
1494        BuiltOmpOffload { offload: files, lib_dir: out_dir.join("lib") }
1495    }
1496}
1497
1498#[derive(Clone)]
1499pub struct BuiltEnzyme {
1500    /// Path to the libEnzyme dylib.
1501    enzyme: PathBuf,
1502}
1503
1504impl BuiltEnzyme {
1505    pub fn enzyme_path(&self) -> PathBuf {
1506        self.enzyme.clone()
1507    }
1508    pub fn enzyme_filename(&self) -> String {
1509        self.enzyme.file_name().unwrap().to_str().unwrap().to_owned()
1510    }
1511}
1512
1513#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1514pub struct Enzyme {
1515    pub target: TargetSelection,
1516}
1517
1518impl CommandLineStep for Enzyme {
1519    type Output = BuiltEnzyme;
1520    const IS_HOST: bool = true;
1521
1522    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1523        run.path("src/tools/enzyme/enzyme")
1524    }
1525
1526    fn make_run(run: RunConfig<'_>) {
1527        run.builder.ensure(Enzyme { target: run.target });
1528    }
1529
1530    /// Compile Enzyme for `target`.
1531    fn run(self, builder: &Builder<'_>) -> Self::Output {
1532        builder.require_submodule(
1533            "src/tools/enzyme",
1534            Some("The Enzyme sources are required for autodiff."),
1535        );
1536        let target = self.target;
1537
1538        if builder.config.dry_run() {
1539            return BuiltEnzyme { enzyme: builder.config.tempdir().join("enzyme-dryrun") };
1540        }
1541
1542        let llvm_output = builder.ensure(Llvm { target });
1543
1544        // Enzyme links against LLVM. If we update the LLVM submodule libLLVM might get a new
1545        // version number, in which case Enzyme will now fail to find LLVM. By including the LLVM
1546        // hash into the Enzyme hash we force a rebuild of Enzyme when updating LLVM.
1547        let enzyme_hash_input = builder.in_tree_llvm_info.sha().unwrap_or_default().to_owned()
1548            + builder.enzyme_info.sha().unwrap_or_default();
1549
1550        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1551        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1552            generate_smart_stamp_hash(
1553                builder,
1554                &builder.config.src.join("src/tools/enzyme"),
1555                &enzyme_hash_input,
1556            )
1557        });
1558
1559        let out_dir = builder.out.join(self.target.triple).join("enzyme");
1560        let stamp = BuildStamp::new(&out_dir).with_prefix("enzyme").add_stamp(smart_stamp_hash);
1561
1562        let llvm_version_major = llvm::get_llvm_version_major(builder, &builder.host_llvm_config());
1563        let lib_ext = std::env::consts::DLL_EXTENSION;
1564        let libenzyme = format!("libEnzyme-{llvm_version_major}");
1565        let build_dir = out_dir.join(libdir(target));
1566        let dylib = build_dir.join(&libenzyme).with_extension(lib_ext);
1567
1568        trace!("checking build stamp to see if we need to rebuild enzyme artifacts");
1569        if stamp.is_up_to_date() {
1570            trace!(?out_dir, "enzyme build artifacts are up to date");
1571            if stamp.stamp().is_empty() {
1572                builder.info(
1573                    "Could not determine the Enzyme submodule commit hash. \
1574                     Assuming that an Enzyme rebuild is not necessary.",
1575                );
1576                builder.info(&format!(
1577                    "To force Enzyme to rebuild, remove the file `{}`",
1578                    stamp.path().display()
1579                ));
1580            }
1581            return BuiltEnzyme { enzyme: dylib };
1582        }
1583
1584        let llvm_cmake_dir = llvm_output.cmake_dir();
1585        if !builder.config.dry_run() && !llvm_cmake_dir.is_dir() {
1586            builder.info(&format!(
1587                "WARNING: {:?} does not exist, Enzyme build will likely fail",
1588                llvm_cmake_dir
1589            ));
1590        }
1591
1592        trace!(?target, "(re)building enzyme artifacts");
1593        builder.info(&format!("Building Enzyme for {target}"));
1594        t!(stamp.remove());
1595        let _time = helpers::timeit(builder);
1596        t!(fs::create_dir_all(&out_dir));
1597
1598        let mut cfg = cmake::Config::new(builder.src.join("src/tools/enzyme/enzyme/"));
1599        // Enzyme devs maintain upstream compatibility, but only fix deprecations when they are about
1600        // to turn into a hard error. As such, Enzyme generates various warnings which could make it
1601        // hard to spot more relevant issues.
1602        let mut cflags = CcFlags::default();
1603        cflags.push_all("-Wno-deprecated");
1604
1605        // Logic copied from `configure_llvm`
1606        // ThinLTO is only available when building with LLVM, enabling LLD is required.
1607        // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
1608        let mut ldflags = LdFlags::default();
1609        if builder.config.llvm_thin_lto && !target.contains("apple") {
1610            ldflags.push_all("-fuse-ld=lld");
1611        }
1612
1613        configure_cmake(builder, target, &mut cfg, true, ldflags, cflags, &[]);
1614
1615        // Re-use the same flags as llvm to control the level of debug information
1616        // generated by Enzyme.
1617        // FIXME(ZuseZ4): Find a nicer way to use Enzyme Debug builds.
1618        let profile = get_llvm_profile(&builder.config);
1619        trace!(?profile);
1620
1621        cfg.out_dir(&out_dir)
1622            .profile(profile)
1623            .define("LLVM_ENABLE_ASSERTIONS", "ON")
1624            .define("ENZYME_EXTERNAL_SHARED_LIB", "ON")
1625            .define("ENZYME_BC_LOADER", "OFF")
1626            .define("LLVM_DIR", llvm_cmake_dir);
1627
1628        cfg.build();
1629
1630        // At this point, `out_dir` should contain the built libEnzyme-<LLVM-version>.<dylib-ext>
1631        // file.
1632        if !dylib.exists() {
1633            eprintln!(
1634                "`{libenzyme}` not found in `{}`. Either the build has failed or Enzyme was built with a wrong version of LLVM",
1635                build_dir.display()
1636            );
1637            helpers::exit_process(1);
1638        }
1639
1640        t!(stamp.write());
1641        BuiltEnzyme { enzyme: dylib }
1642    }
1643}
1644
1645#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1646pub struct Lld {
1647    pub target: TargetSelection,
1648}
1649
1650impl CommandLineStep for Lld {
1651    type Output = PathBuf;
1652    const IS_HOST: bool = true;
1653
1654    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1655        run.path("src/llvm-project/lld")
1656    }
1657
1658    fn make_run(run: RunConfig<'_>) {
1659        run.builder.ensure(Lld { target: run.target });
1660    }
1661
1662    /// Compile LLD for `target`.
1663    fn run(self, builder: &Builder<'_>) -> PathBuf {
1664        if builder.config.dry_run() {
1665            return PathBuf::from("lld-out-dir-test-gen");
1666        }
1667        let target = self.target;
1668
1669        let llvm_output = builder.ensure(Llvm { target });
1670
1671        // The `dist` step packages LLD next to LLVM's binaries for download-ci-llvm. The root path
1672        // we usually expect here is `./build/$triple/ci-llvm/`, with the binaries in its `bin`
1673        // subfolder. We check if that's the case, and if LLD's binary already exists there next to
1674        // `llvm-config`: if so, we can use it instead of building LLVM/LLD from source.
1675        if matches!(llvm_output.kind, LlvmKind::DownloadedFromCi) {
1676            let bin_dir = llvm_output.root_dir().join("bin");
1677            let lld_path = bin_dir.join(exe("lld", target));
1678            if lld_path.exists() {
1679                // The following steps copying `lld` as `rust-lld` to the sysroot, expect it in the
1680                // `bin` subfolder of this step's out dir.
1681                return bin_dir.parent().unwrap().to_path_buf();
1682            }
1683        }
1684
1685        let out_dir = builder.out.join(target).join("lld");
1686
1687        let lld_stamp = BuildStamp::new(&out_dir).with_prefix("lld");
1688        if lld_stamp.path().exists() {
1689            return out_dir;
1690        }
1691
1692        let _guard = builder.msg_unstaged(Kind::Build, "LLD", target);
1693        let _time = helpers::timeit(builder);
1694        t!(fs::create_dir_all(&out_dir));
1695
1696        let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
1697        let mut ldflags = LdFlags::default();
1698
1699        // When building LLD as part of a build with instrumentation on windows, for example
1700        // when doing PGO on CI, cmake or clang-cl don't automatically link clang's
1701        // profiler runtime in. In that case, we need to manually ask cmake to do it, to avoid
1702        // linking errors, much like LLVM's cmake setup does in that situation.
1703        if builder.config.llvm_pgo.generate_profile.is_some()
1704            && target.is_msvc()
1705            && let Some(clang_cl_path) = builder.config.llvm_clang_cl.as_ref()
1706        {
1707            // Find clang's runtime library directory and push that as a search path to the
1708            // cmake linker flags.
1709            let clang_rt_dir = get_clang_cl_resource_dir(builder, clang_cl_path);
1710            ldflags.push_all(format!("/libpath:{}", clang_rt_dir.display()));
1711        }
1712
1713        // LLD is built as an LLVM tool, but is distributed outside of the `llvm-tools` component,
1714        // which impacts where it expects to find LLVM's shared library. This causes #80703.
1715        //
1716        // LLD is distributed at "$root/lib/rustlib/$host/bin/rust-lld", but the `libLLVM-*.so` it
1717        // needs is distributed at "$root/lib". The default rpath of "$ORIGIN/../lib" points at the
1718        // lib path for LLVM tools, not the one for rust binaries.
1719        //
1720        // (The `llvm-tools` component copies the .so there for the other tools, and with that
1721        // component installed, one can successfully invoke `rust-lld` directly without rustup's
1722        // `LD_LIBRARY_PATH` overrides)
1723        //
1724        if builder.config.rpath_enabled(target)
1725            && helpers::use_host_linker(target)
1726            && llvm_output.link_shared()
1727        {
1728            // So we inform LLD where it can find LLVM's libraries by adding an rpath entry to the
1729            // expected parent `lib` directory.
1730            //
1731            // Be careful when changing this path, we need to ensure it's quoted or escaped:
1732            // `$ORIGIN` would otherwise be expanded when the `LdFlags` are passed verbatim to
1733            // cmake.
1734            if target.contains("linux") {
1735                ldflags.push_all("-Wl,-rpath,'$ORIGIN/../../../'");
1736            }
1737            if target.contains("apple-darwin") {
1738                ldflags.push_all("-Wl,-rpath,'@loader_path/../../../'");
1739            }
1740        }
1741
1742        configure_cmake(builder, target, &mut cfg, true, ldflags, CcFlags::default(), &[]);
1743        configure_llvm(builder, target, &mut cfg);
1744
1745        // Re-use the same flags as llvm to control the level of debug information
1746        // generated for lld.
1747        let profile = get_llvm_profile(&builder.config);
1748
1749        cfg.out_dir(&out_dir)
1750            .profile(profile)
1751            .define("LLVM_CMAKE_DIR", llvm_output.cmake_dir())
1752            .define("LLVM_INCLUDE_TESTS", "OFF");
1753
1754        if !builder.config.is_host_target(target) {
1755            // Use the host llvm-tblgen binary.
1756            cfg.define(
1757                "LLVM_TABLEGEN_EXE",
1758                builder
1759                    .host_llvm_config()
1760                    .with_file_name("llvm-tblgen")
1761                    .with_extension(EXE_EXTENSION),
1762            );
1763        }
1764
1765        cfg.build();
1766
1767        t!(lld_stamp.write());
1768        out_dir
1769    }
1770}
1771
1772#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1773pub struct Sanitizers {
1774    pub target: TargetSelection,
1775}
1776
1777impl CommandLineStep for Sanitizers {
1778    type Output = Vec<SanitizerRuntime>;
1779
1780    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1781        run.alias("sanitizers")
1782    }
1783
1784    fn make_run(run: RunConfig<'_>) {
1785        run.builder.ensure(Sanitizers { target: run.target });
1786    }
1787
1788    /// Builds sanitizer runtime libraries.
1789    fn run(self, builder: &Builder<'_>) -> Self::Output {
1790        let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
1791        if !compiler_rt_dir.exists() {
1792            return Vec::new();
1793        }
1794
1795        let out_dir = builder.native_dir(self.target).join("sanitizers");
1796        let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
1797
1798        if builder.config.dry_run() || runtimes.is_empty() {
1799            return runtimes;
1800        }
1801
1802        let llvm_host = builder.ensure(Llvm { target: builder.config.host_target });
1803
1804        static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
1805        let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
1806            generate_smart_stamp_hash(
1807                builder,
1808                &builder.config.src.join("src/llvm-project/compiler-rt"),
1809                builder.in_tree_llvm_info.sha().unwrap_or_default(),
1810            )
1811        });
1812
1813        let stamp = BuildStamp::new(&out_dir).with_prefix("sanitizers").add_stamp(smart_stamp_hash);
1814
1815        if stamp.is_up_to_date() {
1816            if stamp.stamp().is_empty() {
1817                builder.info(&format!(
1818                    "Rebuild sanitizers by removing the file `{}`",
1819                    stamp.path().display()
1820                ));
1821            }
1822
1823            return runtimes;
1824        }
1825
1826        let _guard = builder.msg_unstaged(Kind::Build, "sanitizers", self.target);
1827        t!(stamp.remove());
1828        let _time = helpers::timeit(builder);
1829
1830        let mut cfg = cmake::Config::new(&compiler_rt_dir);
1831        cfg.profile("Release");
1832        cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
1833        cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
1834        cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
1835        cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
1836        cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
1837        cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
1838        cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
1839        cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
1840        cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
1841        cfg.define("LLVM_CONFIG_PATH", llvm_host.llvm_config());
1842
1843        if self.target.contains("ohos") {
1844            cfg.define("COMPILER_RT_USE_BUILTINS_LIBRARY", "ON");
1845        }
1846
1847        // On Darwin targets the sanitizer runtimes are build as universal binaries.
1848        // Unfortunately sccache currently lacks support to build them successfully.
1849        // Disable compiler launcher on Darwin targets to avoid potential issues.
1850        let use_compiler_launcher = !self.target.contains("apple-darwin");
1851        // Since v1.0.86, the cc crate adds -mmacosx-version-min to the default
1852        // flags on MacOS. A long-standing bug in the CMake rules for compiler-rt
1853        // causes architecture detection to be skipped when this flag is present,
1854        // and compilation fails. https://github.com/llvm/llvm-project/issues/88780
1855        let suppressed_compiler_flag_prefixes: &[&str] =
1856            if self.target.contains("apple-darwin") { &["-mmacosx-version-min="] } else { &[] };
1857        configure_cmake(
1858            builder,
1859            self.target,
1860            &mut cfg,
1861            use_compiler_launcher,
1862            LdFlags::default(),
1863            CcFlags::default(),
1864            suppressed_compiler_flag_prefixes,
1865        );
1866
1867        t!(fs::create_dir_all(&out_dir));
1868        cfg.out_dir(out_dir);
1869
1870        for runtime in &runtimes {
1871            cfg.build_target(&runtime.cmake_target);
1872            cfg.build();
1873        }
1874        t!(stamp.write());
1875
1876        runtimes
1877    }
1878}
1879
1880#[derive(Clone, Debug)]
1881pub struct SanitizerRuntime {
1882    /// CMake target used to build the runtime.
1883    pub cmake_target: String,
1884    /// Path to the built runtime library.
1885    pub path: PathBuf,
1886    /// Library filename that will be used rustc.
1887    pub name: String,
1888}
1889
1890/// Returns sanitizers available on a given target.
1891fn supported_sanitizers(
1892    out_dir: &Path,
1893    target: TargetSelection,
1894    channel: &str,
1895) -> Vec<SanitizerRuntime> {
1896    let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1897        components
1898            .iter()
1899            .map(move |c| {
1900                let cmake_c = if *c == "ubsan" { "ubsan_standalone" } else { *c };
1901                SanitizerRuntime {
1902                    cmake_target: format!("clang_rt.{cmake_c}_{os}_dynamic"),
1903                    path: out_dir
1904                        .join(format!("build/lib/darwin/libclang_rt.{cmake_c}_{os}_dynamic.dylib")),
1905                    name: format!("librustc-{channel}_rt.{c}.dylib"),
1906                }
1907            })
1908            .collect()
1909    };
1910
1911    let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1912        components
1913            .iter()
1914            .map(move |c| {
1915                let cmake_c = if *c == "ubsan" { "ubsan_standalone" } else { *c };
1916                SanitizerRuntime {
1917                    cmake_target: format!("clang_rt.{cmake_c}-{arch}"),
1918                    path: out_dir.join(format!("build/lib/{os}/libclang_rt.{cmake_c}-{arch}.a")),
1919                    name: format!("librustc-{channel}_rt.{c}.a"),
1920                }
1921            })
1922            .collect()
1923    };
1924
1925    match &*target.triple {
1926        "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),
1927        "aarch64-apple-ios" => darwin_libs("ios", &["asan", "tsan", "rtsan"]),
1928        "aarch64-apple-ios-sim" => darwin_libs("iossim", &["asan", "tsan", "rtsan"]),
1929        "aarch64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1930        "aarch64-unknown-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
1931        "aarch64-unknown-linux-gnu" => common_libs(
1932            "linux",
1933            "aarch64",
1934            &["asan", "lsan", "msan", "tsan", "hwasan", "rtsan", "ubsan"],
1935        ),
1936        "aarch64-unknown-linux-ohos" => {
1937            common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
1938        }
1939        "loongarch64-unknown-linux-gnu" | "loongarch64-unknown-linux-musl" => {
1940            common_libs("linux", "loongarch64", &["asan", "lsan", "msan", "tsan"])
1941        }
1942        "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan", "rtsan"]),
1943        "x86_64-unknown-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
1944        "x86_64-apple-ios" => darwin_libs("iossim", &["asan", "tsan"]),
1945        "x86_64-apple-ios-macabi" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1946        "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
1947        "x86_64-unknown-netbsd" => {
1948            common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
1949        }
1950        "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
1951        "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
1952        "x86_64-unknown-linux-gnu" => common_libs(
1953            "linux",
1954            "x86_64",
1955            &["asan", "dfsan", "lsan", "msan", "safestack", "tsan", "rtsan", "ubsan"],
1956        ),
1957        "x86_64-unknown-linux-gnuasan" => common_libs("linux", "x86_64", &["asan"]),
1958        "x86_64-unknown-linux-gnumsan" => common_libs("linux", "x86_64", &["msan"]),
1959        "x86_64-unknown-linux-gnutsan" => common_libs("linux", "x86_64", &["tsan"]),
1960        "x86_64-unknown-linux-musl" => {
1961            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1962        }
1963        "s390x-unknown-linux-gnu" => {
1964            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1965        }
1966        "s390x-unknown-linux-musl" => {
1967            common_libs("linux", "s390x", &["asan", "lsan", "msan", "tsan"])
1968        }
1969        "x86_64-unknown-linux-ohos" => {
1970            common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1971        }
1972        _ => Vec::new(),
1973    }
1974}
1975
1976#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1977pub struct CrtBeginEnd {
1978    pub target: TargetSelection,
1979}
1980
1981impl CommandLineStep for CrtBeginEnd {
1982    type Output = PathBuf;
1983
1984    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1985        run.path("src/llvm-project/compiler-rt/lib/crt")
1986    }
1987
1988    fn make_run(run: RunConfig<'_>) {
1989        if run.target.needs_crt_begin_end() {
1990            run.builder.ensure(CrtBeginEnd { target: run.target });
1991        }
1992    }
1993
1994    /// Build crtbegin.o/crtend.o for musl target.
1995    fn run(self, builder: &Builder<'_>) -> Self::Output {
1996        builder.require_submodule(
1997            "src/llvm-project",
1998            Some("The LLVM sources are required for the CRT from `compiler-rt`."),
1999        );
2000
2001        let out_dir = builder.native_dir(self.target).join("crt");
2002
2003        if builder.config.dry_run() {
2004            return out_dir;
2005        }
2006
2007        let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtbegin.c");
2008        let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/builtins/crtend.c");
2009        if up_to_date(&crtbegin_src, &out_dir.join("crtbeginS.o"))
2010            && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
2011        {
2012            return out_dir;
2013        }
2014
2015        let _guard = builder.msg_unstaged(Kind::Build, "crtbegin.o and crtend.o", self.target);
2016        t!(fs::create_dir_all(&out_dir));
2017
2018        let mut cfg = cc::Build::new();
2019
2020        if let Some(ar) = builder.ar(self.target) {
2021            cfg.archiver(ar);
2022        }
2023        cfg.compiler(builder.cc(self.target));
2024        cfg.cargo_metadata(false)
2025            .out_dir(&out_dir)
2026            .target(&self.target.triple)
2027            .host(&builder.config.host_target.triple)
2028            .warnings(false)
2029            .debug(false)
2030            .opt_level(3)
2031            .file(crtbegin_src)
2032            .file(crtend_src);
2033
2034        // Those flags are defined in src/llvm-project/compiler-rt/lib/builtins/CMakeLists.txt
2035        // Currently only consumer of those objects is musl, which use .init_array/.fini_array
2036        // instead of .ctors/.dtors
2037        cfg.flag("-std=c11")
2038            .define("CRT_HAS_INITFINI_ARRAY", None)
2039            .define("EH_USE_FRAME_REGISTRY", None);
2040
2041        let objs = cfg.compile_intermediates();
2042        assert_eq!(objs.len(), 2);
2043        for obj in objs {
2044            let base_name = unhashed_basename(&obj);
2045            assert!(base_name == "crtbegin" || base_name == "crtend");
2046            t!(fs::copy(&obj, out_dir.join(format!("{base_name}S.o"))));
2047            t!(fs::rename(&obj, out_dir.join(format!("{base_name}.o"))));
2048        }
2049
2050        out_dir
2051    }
2052}
2053
2054#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2055pub struct Libunwind {
2056    pub target: TargetSelection,
2057}
2058
2059impl CommandLineStep for Libunwind {
2060    type Output = PathBuf;
2061
2062    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2063        run.path("src/llvm-project/libunwind")
2064    }
2065
2066    fn make_run(run: RunConfig<'_>) {
2067        run.builder.ensure(Libunwind { target: run.target });
2068    }
2069
2070    /// Build libunwind.a
2071    fn run(self, builder: &Builder<'_>) -> Self::Output {
2072        builder.require_submodule(
2073            "src/llvm-project",
2074            Some("The LLVM sources are required for libunwind."),
2075        );
2076
2077        if builder.config.dry_run() {
2078            return PathBuf::new();
2079        }
2080
2081        let out_dir = builder.native_dir(self.target).join("libunwind");
2082        let root = builder.src.join("src/llvm-project/libunwind");
2083
2084        if up_to_date(&root, &out_dir.join("libunwind.a")) {
2085            return out_dir;
2086        }
2087
2088        let _guard = builder.msg_unstaged(Kind::Build, "libunwind.a", self.target);
2089        t!(fs::create_dir_all(&out_dir));
2090
2091        let mut cc_cfg = cc::Build::new();
2092        let mut cpp_cfg = cc::Build::new();
2093
2094        cpp_cfg.cpp(true);
2095        cpp_cfg.cpp_set_stdlib(None);
2096        cpp_cfg.flag("-nostdinc++");
2097        cpp_cfg.flag("-fno-exceptions");
2098        cpp_cfg.flag("-fno-rtti");
2099        cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
2100
2101        for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
2102            if let Some(ar) = builder.ar(self.target) {
2103                cfg.archiver(ar);
2104            }
2105            cfg.target(&self.target.triple);
2106            cfg.host(&builder.config.host_target.triple);
2107            cfg.warnings(false);
2108            cfg.debug(false);
2109            // get_compiler() need set opt_level first.
2110            cfg.opt_level(3);
2111            cfg.flag("-fstrict-aliasing");
2112            cfg.flag("-funwind-tables");
2113            cfg.flag("-fvisibility=hidden");
2114            cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
2115            cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");
2116            cfg.include(root.join("include"));
2117            cfg.cargo_metadata(false);
2118            cfg.out_dir(&out_dir);
2119
2120            if self.target.contains("x86_64-fortanix-unknown-sgx") {
2121                cfg.flag("-fno-stack-protector");
2122                cfg.flag("-ffreestanding");
2123                cfg.flag("-fexceptions");
2124
2125                // easiest way to undefine since no API available in cc::Build to undefine
2126                cfg.flag("-U_FORTIFY_SOURCE");
2127                cfg.define("_FORTIFY_SOURCE", "0");
2128                cfg.define("RUST_SGX", "1");
2129                cfg.define("__NO_STRING_INLINES", None);
2130                cfg.define("__NO_MATH_INLINES", None);
2131                cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
2132                cfg.define("NDEBUG", None);
2133            }
2134            if self.target.is_windows() {
2135                cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");
2136            }
2137        }
2138
2139        cc_cfg.compiler(builder.cc(self.target));
2140        if let Ok(cxx) = builder.cxx(self.target) {
2141            cpp_cfg.compiler(cxx);
2142        } else {
2143            cc_cfg.compiler(builder.cc(self.target));
2144        }
2145
2146        // Don't set this for clang
2147        // By default, Clang builds C code in GNU C17 mode.
2148        // By default, Clang builds C++ code according to the C++98 standard,
2149        // with many C++11 features accepted as extensions.
2150        if cc_cfg.get_compiler().is_like_gnu() {
2151            cc_cfg.flag("-std=c99");
2152        }
2153        if cpp_cfg.get_compiler().is_like_gnu() {
2154            cpp_cfg.flag("-std=c++11");
2155        }
2156
2157        if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
2158            // use the same GCC C compiler command to compile C++ code so we do not need to setup the
2159            // C++ compiler env variables on the builders.
2160            // Don't set this for clang++, as clang++ is able to compile this without libc++.
2161            if cpp_cfg.get_compiler().is_like_gnu() {
2162                cpp_cfg.cpp(false);
2163                cpp_cfg.compiler(builder.cc(self.target));
2164            }
2165        }
2166
2167        let mut c_sources = vec![
2168            "Unwind-sjlj.c",
2169            "UnwindLevel1-gcc-ext.c",
2170            "UnwindLevel1.c",
2171            "UnwindRegistersRestore.S",
2172            "UnwindRegistersSave.S",
2173        ];
2174
2175        let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
2176        let cpp_len = cpp_sources.len();
2177
2178        if self.target.contains("x86_64-fortanix-unknown-sgx") {
2179            c_sources.push("UnwindRustSgx.c");
2180        }
2181
2182        for src in c_sources {
2183            cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
2184        }
2185
2186        for src in &cpp_sources {
2187            cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
2188        }
2189
2190        cpp_cfg.compile("unwind-cpp");
2191
2192        // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
2193        let mut count = 0;
2194        let mut files = fs::read_dir(&out_dir)
2195            .unwrap()
2196            .map(|entry| entry.unwrap().path().canonicalize().unwrap())
2197            .collect::<Vec<_>>();
2198        files.sort();
2199        for file in files {
2200            if file.is_file() && file.extension() == Some(OsStr::new("o")) {
2201                // Object file name without the hash prefix is "Unwind-EHABI", "Unwind-seh" or "libunwind".
2202                let base_name = unhashed_basename(&file);
2203                if cpp_sources.iter().any(|f| *base_name == f[..f.len() - 4]) {
2204                    cc_cfg.object(&file);
2205                    count += 1;
2206                }
2207            }
2208        }
2209        assert_eq!(cpp_len, count, "Can't get object files from {out_dir:?}");
2210
2211        cc_cfg.compile("unwind");
2212        out_dir
2213    }
2214}
2215
2216/// Returns the path to `FileCheck` LLVM binary for the specified target.
2217#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2218pub struct FileCheck {
2219    pub target: TargetSelection,
2220}
2221
2222impl Step for FileCheck {
2223    type Output = PathBuf;
2224
2225    fn run(self, builder: &Builder<'_>) -> Self::Output {
2226        let target_config = builder.config.target_config.get(&self.target);
2227
2228        // The target configured filecheck, prefer it
2229        if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
2230            return s.clone();
2231        };
2232
2233        // There is a LLVM config set, take filecheck from it
2234        if let Some(llvm_config) = target_config.and_then(|c| c.llvm_config.as_ref()) {
2235            // We can only execute llvm-config if we're on the same host target
2236            return if builder.is_host_target(self.target) {
2237                let llvm_bindir =
2238                    command(llvm_config).arg("--bindir").run_capture_stdout(builder).stdout();
2239                let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", self.target));
2240
2241                if filecheck.exists() {
2242                    filecheck
2243                } else {
2244                    // On Fedora the system LLVM installs FileCheck in the
2245                    // llvm subdirectory of the libdir.
2246                    let llvm_libdir =
2247                        command(llvm_config).arg("--libdir").run_capture_stdout(builder).stdout();
2248                    let lib_filecheck = Path::new(llvm_libdir.trim())
2249                        .join("llvm")
2250                        .join(exe("FileCheck", self.target));
2251                    if lib_filecheck.exists() {
2252                        lib_filecheck
2253                    } else {
2254                        // Return the most normal file name, even though
2255                        // it doesn't exist, so that any error message
2256                        // refers to that.
2257                        filecheck
2258                    }
2259                }
2260            } else {
2261                // In other cases, just guess that Filecheck is available in the same directory
2262                // as the llvm-config
2263                llvm_config.parent().unwrap().join(exe("FileCheck", self.target))
2264            };
2265        }
2266        // Here we take the filecheck from LLVM directly
2267        let llvm_output = builder.ensure(Llvm { target: self.target });
2268        llvm_output.root_dir().join("bin").join(exe("FileCheck", self.target))
2269    }
2270}