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
11 use std::env;
12 use std::env::consts::EXE_EXTENSION;
13 use std::ffi::{OsStr, OsString};
14 use std::fs::{self, File};
15 use std::io;
16 use std::path::{Path, PathBuf};
17 use std::process::Command;
18
19 use build_helper::{output, t};
20
21 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
22 use crate::config::TargetSelection;
23 use crate::util::{self, exe};
24 use crate::GitRepo;
25 use build_helper::up_to_date;
26
27 pub struct Meta {
28 stamp: HashStamp,
29 build_llvm_config: PathBuf,
30 out_dir: PathBuf,
31 root: String,
32 }
33
34 // This returns whether we've already previously built LLVM.
35 //
36 // It's used to avoid busting caches during x.py check -- if we've already built
37 // LLVM, it's fine for us to not try to avoid doing so.
38 //
39 // This will return the llvm-config if it can get it (but it will not build it
40 // if not).
prebuilt_llvm_config( builder: &Builder<'_>, target: TargetSelection, ) -> Result<PathBuf, Meta>41 pub fn prebuilt_llvm_config(
42 builder: &Builder<'_>,
43 target: TargetSelection,
44 ) -> Result<PathBuf, Meta> {
45 // If we're using a custom LLVM bail out here, but we can only use a
46 // custom LLVM for the build triple.
47 if let Some(config) = builder.config.target_config.get(&target) {
48 if let Some(ref s) = config.llvm_config {
49 check_llvm_version(builder, s);
50 return Ok(s.to_path_buf());
51 }
52 }
53
54 let root = "src/llvm-project/llvm";
55 let out_dir = builder.llvm_out(target);
56
57 let mut llvm_config_ret_dir = builder.llvm_out(builder.config.build);
58 if !builder.config.build.contains("msvc") || builder.ninja() {
59 llvm_config_ret_dir.push("build");
60 }
61 llvm_config_ret_dir.push("bin");
62
63 let build_llvm_config = llvm_config_ret_dir.join(exe("llvm-config", builder.config.build));
64
65 let stamp = out_dir.join("llvm-finished-building");
66 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
67
68 if builder.config.llvm_skip_rebuild && stamp.path.exists() {
69 builder.info(
70 "Warning: \
71 Using a potentially stale build of LLVM; \
72 This may not behave well.",
73 );
74 return Ok(build_llvm_config);
75 }
76
77 if stamp.is_done() {
78 if stamp.hash.is_none() {
79 builder.info(
80 "Could not determine the LLVM submodule commit hash. \
81 Assuming that an LLVM rebuild is not necessary.",
82 );
83 builder.info(&format!(
84 "To force LLVM to rebuild, remove the file `{}`",
85 stamp.path.display()
86 ));
87 }
88 return Ok(build_llvm_config);
89 }
90
91 Err(Meta { stamp, build_llvm_config, out_dir, root: root.into() })
92 }
93
94 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
95 pub struct Llvm {
96 pub target: TargetSelection,
97 }
98
99 impl Step for Llvm {
100 type Output = PathBuf; // path to llvm-config
101
102 const ONLY_HOSTS: bool = true;
103
should_run(run: ShouldRun<'_>) -> ShouldRun<'_>104 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
105 run.path("src/llvm-project").path("src/llvm-project/llvm").path("src/llvm")
106 }
107
make_run(run: RunConfig<'_>)108 fn make_run(run: RunConfig<'_>) {
109 run.builder.ensure(Llvm { target: run.target });
110 }
111
112 /// Compile LLVM for `target`.
run(self, builder: &Builder<'_>) -> PathBuf113 fn run(self, builder: &Builder<'_>) -> PathBuf {
114 let target = self.target;
115 let target_native = if self.target.starts_with("riscv") {
116 // RISC-V target triples in Rust is not named the same as C compiler target triples.
117 // This converts Rust RISC-V target triples to C compiler triples.
118 let idx = target.triple.find('-').unwrap();
119
120 format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
121 } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
122 // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
123 // Set the version suffix to 13.0 so the correct target details are used.
124 format!("{}{}", self.target, "13.0")
125 } else {
126 target.to_string()
127 };
128
129 let Meta { stamp, build_llvm_config, out_dir, root } =
130 match prebuilt_llvm_config(builder, target) {
131 Ok(p) => return p,
132 Err(m) => m,
133 };
134
135 builder.update_submodule(&Path::new("src").join("llvm-project"));
136 if builder.config.llvm_link_shared
137 && (target.contains("windows") || target.contains("apple-darwin"))
138 {
139 panic!("shared linking to LLVM is not currently supported on {}", target.triple);
140 }
141
142 builder.info(&format!("Building LLVM for {}", target));
143 t!(stamp.remove());
144 let _time = util::timeit(&builder);
145 t!(fs::create_dir_all(&out_dir));
146
147 // https://llvm.org/docs/CMake.html
148 let mut cfg = cmake::Config::new(builder.src.join(root));
149
150 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
151 (false, _) => "Debug",
152 (true, false) => "Release",
153 (true, true) => "RelWithDebInfo",
154 };
155
156 // NOTE: remember to also update `config.toml.example` when changing the
157 // defaults!
158 let llvm_targets = match &builder.config.llvm_targets {
159 Some(s) => s,
160 None => {
161 "AArch64;ARM;BPF;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
162 Sparc;SystemZ;WebAssembly;X86"
163 }
164 };
165
166 let llvm_exp_targets = match builder.config.llvm_experimental_targets {
167 Some(ref s) => s,
168 None => "AVR;M68k",
169 };
170
171 let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
172 let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
173 let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
174
175 cfg.out_dir(&out_dir)
176 .profile(profile)
177 .define("LLVM_ENABLE_ASSERTIONS", assertions)
178 .define("LLVM_ENABLE_PLUGINS", plugins)
179 .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
180 .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
181 .define("LLVM_INCLUDE_EXAMPLES", "OFF")
182 .define("LLVM_INCLUDE_DOCS", "OFF")
183 .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
184 .define("LLVM_INCLUDE_TESTS", enable_tests)
185 .define("LLVM_ENABLE_TERMINFO", "OFF")
186 .define("LLVM_ENABLE_LIBEDIT", "OFF")
187 .define("LLVM_ENABLE_BINDINGS", "OFF")
188 .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
189 .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
190 .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
191 .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native);
192
193 // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
194 // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
195 // This flag makes sure `FileCheck` is copied in the final binaries directory.
196 cfg.define("LLVM_INSTALL_UTILS", "ON");
197
198 if builder.config.llvm_profile_generate {
199 cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
200 cfg.define("LLVM_BUILD_RUNTIME", "No");
201 }
202 if let Some(path) = builder.config.llvm_profile_use.as_ref() {
203 cfg.define("LLVM_PROFDATA_FILE", &path);
204 }
205
206 if target != "aarch64-apple-darwin" && !target.contains("windows") {
207 cfg.define("LLVM_ENABLE_ZLIB", "ON");
208 } else {
209 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
210 }
211
212 // Are we compiling for iOS/tvOS?
213 if target.contains("apple-ios") || target.contains("apple-tvos") {
214 // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
215 cfg.define("CMAKE_OSX_SYSROOT", "/");
216 cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
217 // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
218 cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
219 // Zlib fails to link properly, leading to a compiler error.
220 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
221 }
222
223 if builder.config.llvm_thin_lto {
224 cfg.define("LLVM_ENABLE_LTO", "Thin");
225 if !target.contains("apple") {
226 cfg.define("LLVM_ENABLE_LLD", "ON");
227 }
228 }
229
230 // This setting makes the LLVM tools link to the dynamic LLVM library,
231 // which saves both memory during parallel links and overall disk space
232 // for the tools. We don't do this on every platform as it doesn't work
233 // equally well everywhere.
234 //
235 // If we're not linking rustc to a dynamic LLVM, though, then don't link
236 // tools to it.
237 if builder.llvm_link_tools_dynamically(target) && builder.config.llvm_link_shared {
238 cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
239 }
240
241 // For distribution we want the LLVM tools to be *statically* linked to libstdc++
242 if builder.config.llvm_tools_enabled {
243 if !target.contains("msvc") {
244 if target.contains("apple") {
245 cfg.define("CMAKE_EXE_LINKER_FLAGS", "-static-libstdc++");
246 } else {
247 cfg.define("CMAKE_EXE_LINKER_FLAGS", "-Wl,-Bsymbolic -static-libstdc++");
248 }
249 }
250 }
251
252 if target.starts_with("riscv") {
253 // In RISC-V, using C++ atomics require linking to `libatomic` but the LLVM build
254 // system check cannot detect this. Therefore it is set manually here.
255 if !builder.config.llvm_tools_enabled {
256 cfg.define("CMAKE_EXE_LINKER_FLAGS", "-latomic");
257 } else {
258 cfg.define("CMAKE_EXE_LINKER_FLAGS", "-latomic -static-libstdc++");
259 }
260 cfg.define("CMAKE_SHARED_LINKER_FLAGS", "-latomic");
261 }
262
263 if target.contains("msvc") {
264 cfg.define("LLVM_USE_CRT_DEBUG", "MT");
265 cfg.define("LLVM_USE_CRT_RELEASE", "MT");
266 cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
267 cfg.static_crt(true);
268 }
269
270 if target.starts_with("i686") {
271 cfg.define("LLVM_BUILD_32_BITS", "ON");
272 }
273
274 let mut enabled_llvm_projects = Vec::new();
275
276 if util::forcing_clang_based_tests() {
277 enabled_llvm_projects.push("clang");
278 enabled_llvm_projects.push("compiler-rt");
279 }
280
281 if builder.config.llvm_polly {
282 enabled_llvm_projects.push("polly");
283 }
284
285 if builder.config.llvm_clang {
286 enabled_llvm_projects.push("clang");
287 }
288
289 // We want libxml to be disabled.
290 // See https://github.com/rust-lang/rust/pull/50104
291 cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
292
293 if !enabled_llvm_projects.is_empty() {
294 enabled_llvm_projects.sort();
295 enabled_llvm_projects.dedup();
296 cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
297 }
298
299 if let Some(num_linkers) = builder.config.llvm_link_jobs {
300 if num_linkers > 0 {
301 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
302 }
303 }
304
305 // Workaround for ppc32 lld limitation
306 if target == "powerpc-unknown-freebsd" {
307 cfg.define("CMAKE_EXE_LINKER_FLAGS", "-fuse-ld=bfd");
308 }
309
310 // https://llvm.org/docs/HowToCrossCompileLLVM.html
311 if target != builder.config.build {
312 builder.ensure(Llvm { target: builder.config.build });
313 // FIXME: if the llvm root for the build triple is overridden then we
314 // should use llvm-tblgen from there, also should verify that it
315 // actually exists most of the time in normal installs of LLVM.
316 let host_bin = builder.llvm_out(builder.config.build).join("bin");
317 cfg.define("CMAKE_CROSSCOMPILING", "True");
318 cfg.define("LLVM_TABLEGEN", host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION));
319 cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
320 cfg.define(
321 "LLVM_CONFIG_PATH",
322 host_bin.join("llvm-config").with_extension(EXE_EXTENSION),
323 );
324 }
325
326 if let Some(ref suffix) = builder.config.llvm_version_suffix {
327 // Allow version-suffix="" to not define a version suffix at all.
328 if !suffix.is_empty() {
329 cfg.define("LLVM_VERSION_SUFFIX", suffix);
330 }
331 } else if builder.config.channel == "dev" {
332 // Changes to a version suffix require a complete rebuild of the LLVM.
333 // To avoid rebuilds during a time of version bump, don't include rustc
334 // release number on the dev channel.
335 cfg.define("LLVM_VERSION_SUFFIX", "-rust-dev");
336 } else {
337 let suffix = format!("-rust-{}-{}", builder.version, builder.config.channel);
338 cfg.define("LLVM_VERSION_SUFFIX", suffix);
339 }
340
341 if let Some(ref linker) = builder.config.llvm_use_linker {
342 cfg.define("LLVM_USE_LINKER", linker);
343 }
344
345 if builder.config.llvm_allow_old_toolchain {
346 cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
347 }
348
349 configure_cmake(builder, target, &mut cfg, true);
350
351 // FIXME: we don't actually need to build all LLVM tools and all LLVM
352 // libraries here, e.g., we just want a few components and a few
353 // tools. Figure out how to filter them down and only build the right
354 // tools and libs on all platforms.
355
356 if builder.config.dry_run {
357 return build_llvm_config;
358 }
359
360 cfg.build();
361
362 t!(stamp.write());
363
364 build_llvm_config
365 }
366 }
367
check_llvm_version(builder: &Builder<'_>, llvm_config: &Path)368 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
369 if !builder.config.llvm_version_check {
370 return;
371 }
372
373 if builder.config.dry_run {
374 return;
375 }
376
377 let mut cmd = Command::new(llvm_config);
378 let version = output(cmd.arg("--version"));
379 let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
380 if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
381 if major >= 12 {
382 return;
383 }
384 }
385 panic!("\n\nbad LLVM version: {}, need >=12.0\n\n", version)
386 }
387
configure_cmake( builder: &Builder<'_>, target: TargetSelection, cfg: &mut cmake::Config, use_compiler_launcher: bool, )388 fn configure_cmake(
389 builder: &Builder<'_>,
390 target: TargetSelection,
391 cfg: &mut cmake::Config,
392 use_compiler_launcher: bool,
393 ) {
394 // Do not print installation messages for up-to-date files.
395 // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
396 cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
397
398 // Do not allow the user's value of DESTDIR to influence where
399 // LLVM will install itself. LLVM must always be installed in our
400 // own build directories.
401 cfg.env("DESTDIR", "");
402
403 if builder.ninja() {
404 cfg.generator("Ninja");
405 }
406 cfg.target(&target.triple).host(&builder.config.build.triple);
407
408 if target != builder.config.build {
409 if target.contains("netbsd") {
410 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
411 } else if target.contains("freebsd") {
412 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
413 } else if target.contains("windows") {
414 cfg.define("CMAKE_SYSTEM_NAME", "Windows");
415 } else if target.contains("haiku") {
416 cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
417 } else if target.contains("solaris") || target.contains("illumos") {
418 cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
419 }
420 // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
421 // that case like CMake we cannot easily determine system version either.
422 //
423 // Since, the LLVM itself makes rather limited use of version checks in
424 // CMakeFiles (and then only in tests), and so far no issues have been
425 // reported, the system version is currently left unset.
426 }
427
428 let sanitize_cc = |cc: &Path| {
429 if target.contains("msvc") {
430 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
431 } else {
432 cc.as_os_str().to_owned()
433 }
434 };
435
436 // MSVC with CMake uses msbuild by default which doesn't respect these
437 // vars that we'd otherwise configure. In that case we just skip this
438 // entirely.
439 if target.contains("msvc") && !builder.ninja() {
440 return;
441 }
442
443 let (cc, cxx) = match builder.config.llvm_clang_cl {
444 Some(ref cl) => (cl.as_ref(), cl.as_ref()),
445 None => (builder.cc(target), builder.cxx(target).unwrap()),
446 };
447
448 // Handle msvc + ninja + ccache specially (this is what the bots use)
449 if target.contains("msvc") && builder.ninja() && builder.config.ccache.is_some() {
450 let mut wrap_cc = env::current_exe().expect("failed to get cwd");
451 wrap_cc.set_file_name("sccache-plus-cl.exe");
452
453 cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
454 .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
455 cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
456 .env("SCCACHE_TARGET", target.triple)
457 .env("SCCACHE_CC", &cc)
458 .env("SCCACHE_CXX", &cxx);
459
460 // Building LLVM on MSVC can be a little ludicrous at times. We're so far
461 // off the beaten path here that I'm not really sure this is even half
462 // supported any more. Here we're trying to:
463 //
464 // * Build LLVM on MSVC
465 // * Build LLVM with `clang-cl` instead of `cl.exe`
466 // * Build a project with `sccache`
467 // * Build for 32-bit as well
468 // * Build with Ninja
469 //
470 // For `cl.exe` there are different binaries to compile 32/64 bit which
471 // we use but for `clang-cl` there's only one which internally
472 // multiplexes via flags. As a result it appears that CMake's detection
473 // of a compiler's architecture and such on MSVC **doesn't** pass any
474 // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
475 // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
476 // definitely causes problems since all the env vars are pointing to
477 // 32-bit libraries.
478 //
479 // To hack around this... again... we pass an argument that's
480 // unconditionally passed in the sccache shim. This'll get CMake to
481 // correctly diagnose it's doing a 32-bit compilation and LLVM will
482 // internally configure itself appropriately.
483 if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
484 cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
485 }
486 } else {
487 // If ccache is configured we inform the build a little differently how
488 // to invoke ccache while also invoking our compilers.
489 if use_compiler_launcher {
490 if let Some(ref ccache) = builder.config.ccache {
491 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
492 .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
493 }
494 }
495 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
496 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx))
497 .define("CMAKE_ASM_COMPILER", sanitize_cc(cc));
498 }
499
500 cfg.build_arg("-j").build_arg(builder.jobs().to_string());
501 let mut cflags = builder.cflags(target, GitRepo::Llvm).join(" ");
502 if let Some(ref s) = builder.config.llvm_cflags {
503 cflags.push_str(&format!(" {}", s));
504 }
505 // Some compiler features used by LLVM (such as thread locals) will not work on a min version below iOS 10.
506 if target.contains("apple-ios") {
507 if target.contains("86-") {
508 cflags.push_str(" -miphonesimulator-version-min=10.0");
509 } else {
510 cflags.push_str(" -miphoneos-version-min=10.0");
511 }
512 }
513 if builder.config.llvm_clang_cl.is_some() {
514 cflags.push_str(&format!(" --target={}", target))
515 }
516 cfg.define("CMAKE_C_FLAGS", cflags);
517 let mut cxxflags = builder.cflags(target, GitRepo::Llvm).join(" ");
518 if builder.config.llvm_static_stdcpp && !target.contains("msvc") && !target.contains("netbsd") {
519 cxxflags.push_str(" -static-libstdc++");
520 }
521 if let Some(ref s) = builder.config.llvm_cxxflags {
522 cxxflags.push_str(&format!(" {}", s));
523 }
524 if builder.config.llvm_clang_cl.is_some() {
525 cxxflags.push_str(&format!(" --target={}", target))
526 }
527 cfg.define("CMAKE_CXX_FLAGS", cxxflags);
528 if let Some(ar) = builder.ar(target) {
529 if ar.is_absolute() {
530 // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
531 // tries to resolve this path in the LLVM build directory.
532 cfg.define("CMAKE_AR", sanitize_cc(ar));
533 }
534 }
535
536 if let Some(ranlib) = builder.ranlib(target) {
537 if ranlib.is_absolute() {
538 // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
539 // tries to resolve this path in the LLVM build directory.
540 cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
541 }
542 }
543
544 if let Some(ref s) = builder.config.llvm_ldflags {
545 cfg.define("CMAKE_SHARED_LINKER_FLAGS", s);
546 cfg.define("CMAKE_MODULE_LINKER_FLAGS", s);
547 cfg.define("CMAKE_EXE_LINKER_FLAGS", s);
548 }
549
550 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
551 cfg.env("RUSTC_LOG", "sccache=warn");
552 }
553 }
554
555 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
556 pub struct Lld {
557 pub target: TargetSelection,
558 }
559
560 impl Step for Lld {
561 type Output = PathBuf;
562 const ONLY_HOSTS: bool = true;
563
564 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
565 run.path("src/llvm-project/lld").path("src/tools/lld")
566 }
567
568 fn make_run(run: RunConfig<'_>) {
569 run.builder.ensure(Lld { target: run.target });
570 }
571
572 /// Compile LLD for `target`.
573 fn run(self, builder: &Builder<'_>) -> PathBuf {
574 if builder.config.dry_run {
575 return PathBuf::from("lld-out-dir-test-gen");
576 }
577 let target = self.target;
578
579 let llvm_config = builder.ensure(Llvm { target: self.target });
580
581 let out_dir = builder.lld_out(target);
582 let done_stamp = out_dir.join("lld-finished-building");
583 if done_stamp.exists() {
584 return out_dir;
585 }
586
587 builder.info(&format!("Building LLD for {}", target));
588 let _time = util::timeit(&builder);
589 t!(fs::create_dir_all(&out_dir));
590
591 let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
592 configure_cmake(builder, target, &mut cfg, true);
593
594 cfg.out_dir(&out_dir)
595 .profile("Release")
596 .define("LLVM_CONFIG_PATH", &llvm_config)
597 .define("LLVM_INCLUDE_TESTS", "OFF");
598
599 // While we're using this horrible workaround to shim the execution of
600 // llvm-config, let's just pile on more. I can't seem to figure out how
601 // to build LLD as a standalone project and also cross-compile it at the
602 // same time. It wants a natively executable `llvm-config` to learn
603 // about LLVM, but then it learns about all the host configuration of
604 // LLVM and tries to link to host LLVM libraries.
605 //
606 // To work around that we tell our shim to replace anything with the
607 // build target with the actual target instead. This'll break parts of
608 // LLD though which try to execute host tools, such as llvm-tblgen, so
609 // we specifically tell it where to find those. This is likely super
610 // brittle and will break over time. If anyone knows better how to
611 // cross-compile LLD it would be much appreciated to fix this!
612 if target != builder.config.build {
613 cfg.env("LLVM_CONFIG_SHIM_REPLACE", &builder.config.build.triple)
614 .env("LLVM_CONFIG_SHIM_REPLACE_WITH", &target.triple)
615 .define(
616 "LLVM_TABLEGEN_EXE",
617 llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
618 );
619 }
620
621 // Explicitly set C++ standard, because upstream doesn't do so
622 // for standalone builds.
623 cfg.define("CMAKE_CXX_STANDARD", "14");
624
625 cfg.build();
626
627 t!(File::create(&done_stamp));
628 out_dir
629 }
630 }
631
632 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
633 pub struct TestHelpers {
634 pub target: TargetSelection,
635 }
636
637 impl Step for TestHelpers {
638 type Output = ();
639
640 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
641 run.path("src/test/auxiliary/rust_test_helpers.c")
642 }
643
644 fn make_run(run: RunConfig<'_>) {
645 run.builder.ensure(TestHelpers { target: run.target })
646 }
647
648 /// Compiles the `rust_test_helpers.c` library which we used in various
649 /// `run-pass` tests for ABI testing.
650 fn run(self, builder: &Builder<'_>) {
651 if builder.config.dry_run {
652 return;
653 }
654 // The x86_64-fortanix-unknown-sgx target doesn't have a working C
655 // toolchain. However, some x86_64 ELF objects can be linked
656 // without issues. Use this hack to compile the test helpers.
657 let target = if self.target == "x86_64-fortanix-unknown-sgx" {
658 TargetSelection::from_user("x86_64-unknown-linux-gnu")
659 } else {
660 self.target
661 };
662 let dst = builder.test_helpers_out(target);
663 let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
664 if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
665 return;
666 }
667
668 builder.info("Building test helpers");
669 t!(fs::create_dir_all(&dst));
670 let mut cfg = cc::Build::new();
671 // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
672 if target.contains("emscripten") {
673 cfg.pic(false);
674 }
675
676 // We may have found various cross-compilers a little differently due to our
677 // extra configuration, so inform cc of these compilers. Note, though, that
678 // on MSVC we still need cc's detection of env vars (ugh).
679 if !target.contains("msvc") {
680 if let Some(ar) = builder.ar(target) {
681 cfg.archiver(ar);
682 }
683 cfg.compiler(builder.cc(target));
684 }
685 cfg.cargo_metadata(false)
686 .out_dir(&dst)
687 .target(&target.triple)
688 .host(&builder.config.build.triple)
689 .opt_level(0)
690 .warnings(false)
691 .debug(false)
692 .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
693 .compile("rust_test_helpers");
694 }
695 }
696
697 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
698 pub struct Sanitizers {
699 pub target: TargetSelection,
700 }
701
702 impl Step for Sanitizers {
703 type Output = Vec<SanitizerRuntime>;
704
705 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
706 run.path("src/llvm-project/compiler-rt").path("src/sanitizers")
707 }
708
709 fn make_run(run: RunConfig<'_>) {
710 run.builder.ensure(Sanitizers { target: run.target });
711 }
712
713 /// Builds sanitizer runtime libraries.
714 fn run(self, builder: &Builder<'_>) -> Self::Output {
715 let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
716 if !compiler_rt_dir.exists() {
717 return Vec::new();
718 }
719
720 let out_dir = builder.native_dir(self.target).join("sanitizers");
721 let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
722 if runtimes.is_empty() {
723 return runtimes;
724 }
725
726 let llvm_config = builder.ensure(Llvm { target: builder.config.build });
727 if builder.config.dry_run {
728 return runtimes;
729 }
730
731 let stamp = out_dir.join("sanitizers-finished-building");
732 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
733
734 if stamp.is_done() {
735 if stamp.hash.is_none() {
736 builder.info(&format!(
737 "Rebuild sanitizers by removing the file `{}`",
738 stamp.path.display()
739 ));
740 }
741 return runtimes;
742 }
743
744 builder.info(&format!("Building sanitizers for {}", self.target));
745 t!(stamp.remove());
746 let _time = util::timeit(&builder);
747
748 let mut cfg = cmake::Config::new(&compiler_rt_dir);
749 cfg.profile("Release");
750 cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
751 cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
752 cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
753 cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
754 cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
755 cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
756 cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
757 cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
758 cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
759 cfg.define("LLVM_CONFIG_PATH", &llvm_config);
760
761 // On Darwin targets the sanitizer runtimes are build as universal binaries.
762 // Unfortunately sccache currently lacks support to build them successfully.
763 // Disable compiler launcher on Darwin targets to avoid potential issues.
764 let use_compiler_launcher = !self.target.contains("apple-darwin");
765 configure_cmake(builder, self.target, &mut cfg, use_compiler_launcher);
766
767 t!(fs::create_dir_all(&out_dir));
768 cfg.out_dir(out_dir);
769
770 for runtime in &runtimes {
771 cfg.build_target(&runtime.cmake_target);
772 cfg.build();
773 }
774 t!(stamp.write());
775
776 runtimes
777 }
778 }
779
780 #[derive(Clone, Debug)]
781 pub struct SanitizerRuntime {
782 /// CMake target used to build the runtime.
783 pub cmake_target: String,
784 /// Path to the built runtime library.
785 pub path: PathBuf,
786 /// Library filename that will be used rustc.
787 pub name: String,
788 }
789
790 /// Returns sanitizers available on a given target.
791 fn supported_sanitizers(
792 out_dir: &Path,
793 target: TargetSelection,
794 channel: &str,
795 ) -> Vec<SanitizerRuntime> {
796 let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
797 components
798 .iter()
799 .map(move |c| SanitizerRuntime {
800 cmake_target: format!("clang_rt.{}_{}_dynamic", c, os),
801 path: out_dir
802 .join(&format!("build/lib/darwin/libclang_rt.{}_{}_dynamic.dylib", c, os)),
803 name: format!("librustc-{}_rt.{}.dylib", channel, c),
804 })
805 .collect()
806 };
807
808 let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
809 components
810 .iter()
811 .map(move |c| SanitizerRuntime {
812 cmake_target: format!("clang_rt.{}-{}", c, arch),
813 path: out_dir.join(&format!("build/lib/{}/libclang_rt.{}-{}.a", os, c, arch)),
814 name: format!("librustc-{}_rt.{}.a", channel, c),
815 })
816 .collect()
817 };
818
819 match &*target.triple {
820 "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
821 "aarch64-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
822 "aarch64-unknown-linux-gnu" => {
823 common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
824 }
825 "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
826 "x86_64-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
827 "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
828 "x86_64-unknown-netbsd" => {
829 common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
830 }
831 "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
832 "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
833 "x86_64-unknown-linux-gnu" => {
834 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
835 }
836 "x86_64-unknown-linux-musl" => {
837 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
838 }
839 _ => Vec::new(),
840 }
841 }
842
843 struct HashStamp {
844 path: PathBuf,
845 hash: Option<Vec<u8>>,
846 }
847
848 impl HashStamp {
849 fn new(path: PathBuf, hash: Option<&str>) -> Self {
850 HashStamp { path, hash: hash.map(|s| s.as_bytes().to_owned()) }
851 }
852
853 fn is_done(&self) -> bool {
854 match fs::read(&self.path) {
855 Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(),
856 Err(e) if e.kind() == io::ErrorKind::NotFound => false,
857 Err(e) => {
858 panic!("failed to read stamp file `{}`: {}", self.path.display(), e);
859 }
860 }
861 }
862
863 fn remove(&self) -> io::Result<()> {
864 match fs::remove_file(&self.path) {
865 Ok(()) => Ok(()),
866 Err(e) => {
867 if e.kind() == io::ErrorKind::NotFound {
868 Ok(())
869 } else {
870 Err(e)
871 }
872 }
873 }
874 }
875
876 fn write(&self) -> io::Result<()> {
877 fs::write(&self.path, self.hash.as_deref().unwrap_or(b""))
878 }
879 }
880
881 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
882 pub struct CrtBeginEnd {
883 pub target: TargetSelection,
884 }
885
886 impl Step for CrtBeginEnd {
887 type Output = PathBuf;
888
889 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
890 run.path("src/llvm-project/compiler-rt/lib/crt")
891 }
892
893 fn make_run(run: RunConfig<'_>) {
894 run.builder.ensure(CrtBeginEnd { target: run.target });
895 }
896
897 /// Build crtbegin.o/crtend.o for musl target.
898 fn run(self, builder: &Builder<'_>) -> Self::Output {
899 let out_dir = builder.native_dir(self.target).join("crt");
900
901 if builder.config.dry_run {
902 return out_dir;
903 }
904
905 let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtbegin.c");
906 let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtend.c");
907 if up_to_date(&crtbegin_src, &out_dir.join("crtbegin.o"))
908 && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
909 {
910 return out_dir;
911 }
912
913 builder.info("Building crtbegin.o and crtend.o");
914 t!(fs::create_dir_all(&out_dir));
915
916 let mut cfg = cc::Build::new();
917
918 if let Some(ar) = builder.ar(self.target) {
919 cfg.archiver(ar);
920 }
921 cfg.compiler(builder.cc(self.target));
922 cfg.cargo_metadata(false)
923 .out_dir(&out_dir)
924 .target(&self.target.triple)
925 .host(&builder.config.build.triple)
926 .warnings(false)
927 .debug(false)
928 .opt_level(3)
929 .file(crtbegin_src)
930 .file(crtend_src);
931
932 // Those flags are defined in src/llvm-project/compiler-rt/lib/crt/CMakeLists.txt
933 // Currently only consumer of those objects is musl, which use .init_array/.fini_array
934 // instead of .ctors/.dtors
935 cfg.flag("-std=c11")
936 .define("CRT_HAS_INITFINI_ARRAY", None)
937 .define("EH_USE_FRAME_REGISTRY", None);
938
939 cfg.compile("crt");
940
941 t!(fs::copy(out_dir.join("crtbegin.o"), out_dir.join("crtbeginS.o")));
942 t!(fs::copy(out_dir.join("crtend.o"), out_dir.join("crtendS.o")));
943 out_dir
944 }
945 }
946
947 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
948 pub struct Libunwind {
949 pub target: TargetSelection,
950 }
951
952 impl Step for Libunwind {
953 type Output = PathBuf;
954
955 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
956 run.path("src/llvm-project/libunwind")
957 }
958
959 fn make_run(run: RunConfig<'_>) {
960 run.builder.ensure(Libunwind { target: run.target });
961 }
962
963 /// Build linunwind.a
964 fn run(self, builder: &Builder<'_>) -> Self::Output {
965 if builder.config.dry_run {
966 return PathBuf::new();
967 }
968
969 let out_dir = builder.native_dir(self.target).join("libunwind");
970 let root = builder.src.join("src/llvm-project/libunwind");
971
972 if up_to_date(&root, &out_dir.join("libunwind.a")) {
973 return out_dir;
974 }
975
976 builder.info(&format!("Building libunwind.a for {}", self.target.triple));
977 t!(fs::create_dir_all(&out_dir));
978
979 let mut cc_cfg = cc::Build::new();
980 let mut cpp_cfg = cc::Build::new();
981
982 cpp_cfg.cpp(true);
983 cpp_cfg.cpp_set_stdlib(None);
984 cpp_cfg.flag("-nostdinc++");
985 cpp_cfg.flag("-fno-exceptions");
986 cpp_cfg.flag("-fno-rtti");
987 cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
988
989 for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
990 if let Some(ar) = builder.ar(self.target) {
991 cfg.archiver(ar);
992 }
993 cfg.target(&self.target.triple);
994 cfg.host(&builder.config.build.triple);
995 cfg.warnings(false);
996 cfg.debug(false);
997 // get_compiler() need set opt_level first.
998 cfg.opt_level(3);
999 cfg.flag("-fstrict-aliasing");
1000 cfg.flag("-funwind-tables");
1001 cfg.flag("-fvisibility=hidden");
1002 cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1003 cfg.include(root.join("include"));
1004 cfg.cargo_metadata(false);
1005 cfg.out_dir(&out_dir);
1006
1007 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1008 cfg.static_flag(true);
1009 cfg.flag("-fno-stack-protector");
1010 cfg.flag("-ffreestanding");
1011 cfg.flag("-fexceptions");
1012
1013 // easiest way to undefine since no API available in cc::Build to undefine
1014 cfg.flag("-U_FORTIFY_SOURCE");
1015 cfg.define("_FORTIFY_SOURCE", "0");
1016 cfg.define("RUST_SGX", "1");
1017 cfg.define("__NO_STRING_INLINES", None);
1018 cfg.define("__NO_MATH_INLINES", None);
1019 cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1020 cfg.define("__LIBUNWIND_IS_NATIVE_ONLY", None);
1021 cfg.define("NDEBUG", None);
1022 }
1023 }
1024
1025 cc_cfg.compiler(builder.cc(self.target));
1026 if let Ok(cxx) = builder.cxx(self.target) {
1027 cpp_cfg.compiler(cxx);
1028 } else {
1029 cc_cfg.compiler(builder.cc(self.target));
1030 }
1031
1032 // Don't set this for clang
1033 // By default, Clang builds C code in GNU C17 mode.
1034 // By default, Clang builds C++ code according to the C++98 standard,
1035 // with many C++11 features accepted as extensions.
1036 if cc_cfg.get_compiler().is_like_gnu() {
1037 cc_cfg.flag("-std=c99");
1038 }
1039 if cpp_cfg.get_compiler().is_like_gnu() {
1040 cpp_cfg.flag("-std=c++11");
1041 }
1042
1043 if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1044 // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1045 // C++ compiler env variables on the builders.
1046 // Don't set this for clang++, as clang++ is able to compile this without libc++.
1047 if cpp_cfg.get_compiler().is_like_gnu() {
1048 cpp_cfg.cpp(false);
1049 cpp_cfg.compiler(builder.cc(self.target));
1050 }
1051 }
1052
1053 let mut c_sources = vec![
1054 "Unwind-sjlj.c",
1055 "UnwindLevel1-gcc-ext.c",
1056 "UnwindLevel1.c",
1057 "UnwindRegistersRestore.S",
1058 "UnwindRegistersSave.S",
1059 ];
1060
1061 let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1062 let cpp_len = cpp_sources.len();
1063
1064 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1065 c_sources.push("UnwindRustSgx.c");
1066 }
1067
1068 for src in c_sources {
1069 cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1070 }
1071
1072 for src in &cpp_sources {
1073 cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1074 }
1075
1076 cpp_cfg.compile("unwind-cpp");
1077
1078 // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1079 let mut count = 0;
1080 for entry in fs::read_dir(&out_dir).unwrap() {
1081 let file = entry.unwrap().path().canonicalize().unwrap();
1082 if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1083 // file name starts with "Unwind-EHABI", "Unwind-seh" or "libunwind"
1084 let file_name = file.file_name().unwrap().to_str().expect("UTF-8 file name");
1085 if cpp_sources.iter().any(|f| file_name.starts_with(&f[..f.len() - 4])) {
1086 cc_cfg.object(&file);
1087 count += 1;
1088 }
1089 }
1090 }
1091 assert_eq!(cpp_len, count, "Can't get object files from {:?}", &out_dir);
1092
1093 cc_cfg.compile("unwind");
1094 out_dir
1095 }
1096 }
1097