-
-
Notifications
You must be signed in to change notification settings - Fork 15.4k
Expand file tree
/
Copy pathllvm.rs
More file actions
1535 lines (1335 loc) · 58.5 KB
/
Copy pathllvm.rs
File metadata and controls
1535 lines (1335 loc) · 58.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Compilation of native dependencies like LLVM.
//!
//! Native projects like LLVM unfortunately aren't suited just yet for
//! compilation in build scripts that Cargo has. This is because the
//! compilation takes a *very* long time but also because we don't want to
//! compile LLVM 3 times as part of a normal bootstrap (we want it cached).
//!
//! LLVM and compiler-rt are essentially just wired up to everything else to
//! ensure that they're always in place if needed.
use std::env::consts::EXE_EXTENSION;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::{env, fs};
use build_helper::git::PathFreshness;
#[cfg(feature = "tracing")]
use tracing::instrument;
use crate::core::builder::{Builder, RunConfig, ShouldRun, Step};
use crate::core::config::{Config, TargetSelection};
use crate::utils::build_stamp::{BuildStamp, generate_smart_stamp_hash};
use crate::utils::exec::command;
use crate::utils::helpers::{
self, exe, get_clang_cl_resource_dir, t, unhashed_basename, up_to_date,
};
use crate::{CLang, GitRepo, Kind, trace};
#[derive(Clone)]
pub struct LlvmResult {
/// Path to llvm-config binary.
/// NB: This is always the host llvm-config!
pub llvm_config: PathBuf,
/// Path to LLVM cmake directory for the target.
pub llvm_cmake_dir: PathBuf,
}
pub struct Meta {
stamp: BuildStamp,
res: LlvmResult,
out_dir: PathBuf,
root: String,
}
pub enum LlvmBuildStatus {
AlreadyBuilt(LlvmResult),
ShouldBuild(Meta),
}
impl LlvmBuildStatus {
pub fn should_build(&self) -> bool {
match self {
LlvmBuildStatus::AlreadyBuilt(_) => false,
LlvmBuildStatus::ShouldBuild(_) => true,
}
}
#[cfg(test)]
pub fn llvm_result(&self) -> &LlvmResult {
match self {
LlvmBuildStatus::AlreadyBuilt(res) => res,
LlvmBuildStatus::ShouldBuild(meta) => &meta.res,
}
}
}
/// Linker flags to pass to LLVM's CMake invocation.
#[derive(Debug, Clone, Default)]
struct LdFlags {
/// CMAKE_EXE_LINKER_FLAGS
exe: OsString,
/// CMAKE_SHARED_LINKER_FLAGS
shared: OsString,
/// CMAKE_MODULE_LINKER_FLAGS
module: OsString,
}
impl LdFlags {
fn push_all(&mut self, s: impl AsRef<OsStr>) {
let s = s.as_ref();
self.exe.push(" ");
self.exe.push(s);
self.shared.push(" ");
self.shared.push(s);
self.module.push(" ");
self.module.push(s);
}
}
/// This returns whether we've already previously built LLVM.
///
/// It's used to avoid busting caches during x.py check -- if we've already built
/// LLVM, it's fine for us to not try to avoid doing so.
///
/// This will return the llvm-config if it can get it (but it will not build it
/// if not).
pub fn prebuilt_llvm_config(
builder: &Builder<'_>,
target: TargetSelection,
// Certain commands (like `x test mir-opt --bless`) may call this function with different targets,
// which could bypass the CI LLVM early-return even if `builder.config.llvm_from_ci` is true.
// This flag should be `true` only if the caller needs the LLVM sources (e.g., if it will build LLVM).
handle_submodule_when_needed: bool,
) -> LlvmBuildStatus {
builder.config.maybe_download_ci_llvm();
// If we're using a custom LLVM bail out here, but we can only use a
// custom LLVM for the build triple.
if let Some(config) = builder.config.target_config.get(&target) {
if let Some(ref s) = config.llvm_config {
check_llvm_version(builder, s);
let llvm_config = s.to_path_buf();
let mut llvm_cmake_dir = llvm_config.clone();
llvm_cmake_dir.pop();
llvm_cmake_dir.pop();
llvm_cmake_dir.push("lib");
llvm_cmake_dir.push("cmake");
llvm_cmake_dir.push("llvm");
return LlvmBuildStatus::AlreadyBuilt(LlvmResult { llvm_config, llvm_cmake_dir });
}
}
if handle_submodule_when_needed {
// If submodules are disabled, this does nothing.
builder.config.update_submodule("src/llvm-project");
}
let root = "src/llvm-project/llvm";
let out_dir = builder.llvm_out(target);
let build_llvm_config = if let Some(build_llvm_config) = builder
.config
.target_config
.get(&builder.config.build)
.and_then(|config| config.llvm_config.clone())
{
build_llvm_config
} else {
let mut llvm_config_ret_dir = builder.llvm_out(builder.config.build);
llvm_config_ret_dir.push("bin");
llvm_config_ret_dir.join(exe("llvm-config", builder.config.build))
};
let llvm_cmake_dir = out_dir.join("lib/cmake/llvm");
let res = LlvmResult { llvm_config: build_llvm_config, llvm_cmake_dir };
static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
generate_smart_stamp_hash(
builder,
&builder.config.src.join("src/llvm-project"),
builder.in_tree_llvm_info.sha().unwrap_or_default(),
)
});
let stamp = BuildStamp::new(&out_dir).with_prefix("llvm").add_stamp(smart_stamp_hash);
if stamp.is_up_to_date() {
if stamp.stamp().is_empty() {
builder.info(
"Could not determine the LLVM submodule commit hash. \
Assuming that an LLVM rebuild is not necessary.",
);
builder.info(&format!(
"To force LLVM to rebuild, remove the file `{}`",
stamp.path().display()
));
}
return LlvmBuildStatus::AlreadyBuilt(res);
}
LlvmBuildStatus::ShouldBuild(Meta { stamp, res, out_dir, root: root.into() })
}
/// Paths whose changes invalidate LLVM downloads.
pub const LLVM_INVALIDATION_PATHS: &[&str] = &[
"src/llvm-project",
"src/bootstrap/download-ci-llvm-stamp",
// the LLVM shared object file is named `LLVM-<LLVM-version>-rust-{version}-nightly`
"src/version",
];
/// Detect whether LLVM sources have been modified locally or not.
pub(crate) fn detect_llvm_freshness(config: &Config, is_git: bool) -> PathFreshness {
if is_git {
config.check_path_modifications(LLVM_INVALIDATION_PATHS)
} else if let Some(info) = crate::utils::channel::read_commit_info_file(&config.src) {
PathFreshness::LastModifiedUpstream { upstream: info.sha.trim().to_owned() }
} else {
PathFreshness::MissingUpstream
}
}
/// Returns whether the CI-found LLVM is currently usable.
///
/// This checks the build triple platform to confirm we're usable at all, and if LLVM
/// with/without assertions is available.
pub(crate) fn is_ci_llvm_available_for_target(config: &Config, asserts: bool) -> bool {
// This is currently all tier 1 targets and tier 2 targets with host tools
// (since others may not have CI artifacts)
// https://doc.rust-lang.org/rustc/platform-support.html#tier-1
let supported_platforms = [
// tier 1
("aarch64-unknown-linux-gnu", false),
("aarch64-apple-darwin", false),
("i686-pc-windows-gnu", false),
("i686-pc-windows-msvc", false),
("i686-unknown-linux-gnu", false),
("x86_64-unknown-linux-gnu", true),
("x86_64-apple-darwin", true),
("x86_64-pc-windows-gnu", true),
("x86_64-pc-windows-msvc", true),
// tier 2 with host tools
("aarch64-pc-windows-msvc", false),
("aarch64-unknown-linux-musl", false),
("arm-unknown-linux-gnueabi", false),
("arm-unknown-linux-gnueabihf", false),
("armv7-unknown-linux-gnueabihf", false),
("loongarch64-unknown-linux-gnu", false),
("loongarch64-unknown-linux-musl", false),
("mips-unknown-linux-gnu", false),
("mips64-unknown-linux-gnuabi64", false),
("mips64el-unknown-linux-gnuabi64", false),
("mipsel-unknown-linux-gnu", false),
("powerpc-unknown-linux-gnu", false),
("powerpc64-unknown-linux-gnu", false),
("powerpc64le-unknown-linux-gnu", false),
("powerpc64le-unknown-linux-musl", false),
("riscv64gc-unknown-linux-gnu", false),
("s390x-unknown-linux-gnu", false),
("x86_64-unknown-freebsd", false),
("x86_64-unknown-illumos", false),
("x86_64-unknown-linux-musl", false),
("x86_64-unknown-netbsd", false),
];
if !supported_platforms.contains(&(&*config.build.triple, asserts))
&& (asserts || !supported_platforms.contains(&(&*config.build.triple, true)))
{
return false;
}
true
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Llvm {
pub target: TargetSelection,
}
impl Step for Llvm {
type Output = LlvmResult;
const ONLY_HOSTS: bool = true;
fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
run.path("src/llvm-project").path("src/llvm-project/llvm")
}
fn make_run(run: RunConfig<'_>) {
run.builder.ensure(Llvm { target: run.target });
}
/// Compile LLVM for `target`.
fn run(self, builder: &Builder<'_>) -> LlvmResult {
let target = self.target;
let target_native = if self.target.starts_with("riscv") {
// RISC-V target triples in Rust is not named the same as C compiler target triples.
// This converts Rust RISC-V target triples to C compiler triples.
let idx = target.triple.find('-').unwrap();
format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
} else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
// FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
// Set the version suffix to 13.0 so the correct target details are used.
format!("{}{}", self.target, "13.0")
} else {
target.to_string()
};
// If LLVM has already been built or been downloaded through download-ci-llvm, we avoid building it again.
let Meta { stamp, res, out_dir, root } = match prebuilt_llvm_config(builder, target, true) {
LlvmBuildStatus::AlreadyBuilt(p) => return p,
LlvmBuildStatus::ShouldBuild(m) => m,
};
if builder.llvm_link_shared() && target.is_windows() && !target.ends_with("windows-gnullvm")
{
panic!("shared linking to LLVM is not currently supported on {}", target.triple);
}
let _guard = builder.msg_unstaged(Kind::Build, "LLVM", target);
t!(stamp.remove());
let _time = helpers::timeit(builder);
t!(fs::create_dir_all(&out_dir));
// https://llvm.org/docs/CMake.html
let mut cfg = cmake::Config::new(builder.src.join(root));
let mut ldflags = LdFlags::default();
let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
(false, _) => "Debug",
(true, false) => "Release",
(true, true) => "RelWithDebInfo",
};
// NOTE: remember to also update `bootstrap.example.toml` when changing the
// defaults!
let llvm_targets = match &builder.config.llvm_targets {
Some(s) => s,
None => {
"AArch64;AMDGPU;ARM;BPF;Hexagon;LoongArch;MSP430;Mips;NVPTX;PowerPC;RISCV;\
Sparc;SystemZ;WebAssembly;X86"
}
};
let llvm_exp_targets = match builder.config.llvm_experimental_targets {
Some(ref s) => s,
None => "AVR;M68k;CSKY;Xtensa",
};
let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
let enable_warnings = if builder.config.llvm_enable_warnings { "ON" } else { "OFF" };
cfg.out_dir(&out_dir)
.profile(profile)
.define("LLVM_ENABLE_ASSERTIONS", assertions)
.define("LLVM_UNREACHABLE_OPTIMIZE", "OFF")
.define("LLVM_ENABLE_PLUGINS", plugins)
.define("LLVM_TARGETS_TO_BUILD", llvm_targets)
.define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
.define("LLVM_INCLUDE_EXAMPLES", "OFF")
.define("LLVM_INCLUDE_DOCS", "OFF")
.define("LLVM_INCLUDE_BENCHMARKS", "OFF")
.define("LLVM_INCLUDE_TESTS", enable_tests)
.define("LLVM_ENABLE_LIBEDIT", "OFF")
.define("LLVM_ENABLE_BINDINGS", "OFF")
.define("LLVM_ENABLE_Z3_SOLVER", "OFF")
.define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
.define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
.define("LLVM_DEFAULT_TARGET_TRIPLE", target_native)
.define("LLVM_ENABLE_WARNINGS", enable_warnings);
// Parts of our test suite rely on the `FileCheck` tool, which is built by default in
// `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
// This flag makes sure `FileCheck` is copied in the final binaries directory.
cfg.define("LLVM_INSTALL_UTILS", "ON");
if builder.config.llvm_profile_generate {
cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
if let Ok(llvm_profile_dir) = std::env::var("LLVM_PROFILE_DIR") {
cfg.define("LLVM_PROFILE_DATA_DIR", llvm_profile_dir);
}
cfg.define("LLVM_BUILD_RUNTIME", "No");
}
if let Some(path) = builder.config.llvm_profile_use.as_ref() {
cfg.define("LLVM_PROFDATA_FILE", path);
}
// Libraries for ELF section compression and profraw files merging.
if !target.is_msvc() {
cfg.define("LLVM_ENABLE_ZLIB", "ON");
} else {
cfg.define("LLVM_ENABLE_ZLIB", "OFF");
}
// Are we compiling for iOS/tvOS/watchOS/visionOS?
if target.contains("apple-ios")
|| target.contains("apple-tvos")
|| target.contains("apple-watchos")
|| target.contains("apple-visionos")
{
// Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
// Zlib fails to link properly, leading to a compiler error.
cfg.define("LLVM_ENABLE_ZLIB", "OFF");
}
// This setting makes the LLVM tools link to the dynamic LLVM library,
// which saves both memory during parallel links and overall disk space
// for the tools. We don't do this on every platform as it doesn't work
// equally well everywhere.
if builder.llvm_link_shared() {
cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
}
if (target.starts_with("csky")
|| target.starts_with("riscv")
|| target.starts_with("sparc-"))
&& !target.contains("freebsd")
&& !target.contains("openbsd")
&& !target.contains("netbsd")
{
// CSKY and RISC-V GCC erroneously requires linking against
// `libatomic` when using 1-byte and 2-byte C++
// atomics but the LLVM build system check cannot
// detect this. Therefore it is set manually here.
// Some BSD uses Clang as its system compiler and
// provides no libatomic in its base system so does
// not want this. 32-bit SPARC requires linking against
// libatomic as well.
ldflags.exe.push(" -latomic");
ldflags.shared.push(" -latomic");
}
if target.starts_with("mips") && target.contains("netbsd") {
// LLVM wants 64-bit atomics, while mipsel is 32-bit only, so needs -latomic
ldflags.exe.push(" -latomic");
ldflags.shared.push(" -latomic");
}
if target.is_msvc() {
cfg.define("CMAKE_MSVC_RUNTIME_LIBRARY", "MultiThreaded");
cfg.static_crt(true);
}
if target.starts_with("i686") {
cfg.define("LLVM_BUILD_32_BITS", "ON");
}
if target.starts_with("x86_64") && target.contains("ohos") {
cfg.define("LLVM_TOOL_LLVM_RTDYLD_BUILD", "OFF");
}
let mut enabled_llvm_projects = Vec::new();
if helpers::forcing_clang_based_tests() {
enabled_llvm_projects.push("clang");
}
if builder.config.llvm_polly {
enabled_llvm_projects.push("polly");
}
if builder.config.llvm_clang {
enabled_llvm_projects.push("clang");
}
// We want libxml to be disabled.
// See https://github.com/rust-lang/rust/pull/50104
cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
if !enabled_llvm_projects.is_empty() {
enabled_llvm_projects.sort();
enabled_llvm_projects.dedup();
cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
}
let mut enabled_llvm_runtimes = Vec::new();
if helpers::forcing_clang_based_tests() {
enabled_llvm_runtimes.push("compiler-rt");
}
if builder.config.llvm_offload {
enabled_llvm_runtimes.push("offload");
//FIXME(ZuseZ4): LLVM intends to drop the offload dependency on openmp.
//Remove this line once they achieved it.
enabled_llvm_runtimes.push("openmp");
}
if !enabled_llvm_runtimes.is_empty() {
enabled_llvm_runtimes.sort();
enabled_llvm_runtimes.dedup();
cfg.define("LLVM_ENABLE_RUNTIMES", enabled_llvm_runtimes.join(";"));
}
if let Some(num_linkers) = builder.config.llvm_link_jobs {
if num_linkers > 0 {
cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
}
}
// https://llvm.org/docs/HowToCrossCompileLLVM.html
if !builder.config.is_host_target(target) {
let LlvmResult { llvm_config, .. } =
builder.ensure(Llvm { target: builder.config.build });
if !builder.config.dry_run() {
let llvm_bindir =
command(&llvm_config).arg("--bindir").run_capture_stdout(builder).stdout();
let host_bin = Path::new(llvm_bindir.trim());
cfg.define(
"LLVM_TABLEGEN",
host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION),
);
// LLVM_NM is required for cross compiling using MSVC
cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
}
cfg.define("LLVM_CONFIG_PATH", llvm_config);
if builder.config.llvm_clang {
let build_bin = builder.llvm_out(builder.config.build).join("build").join("bin");
let clang_tblgen = build_bin.join("clang-tblgen").with_extension(EXE_EXTENSION);
if !builder.config.dry_run() && !clang_tblgen.exists() {
panic!("unable to find {}", clang_tblgen.display());
}
cfg.define("CLANG_TABLEGEN", clang_tblgen);
}
}
let llvm_version_suffix = if let Some(ref suffix) = builder.config.llvm_version_suffix {
// Allow version-suffix="" to not define a version suffix at all.
if !suffix.is_empty() { Some(suffix.to_string()) } else { None }
} else if builder.config.channel == "dev" {
// Changes to a version suffix require a complete rebuild of the LLVM.
// To avoid rebuilds during a time of version bump, don't include rustc
// release number on the dev channel.
Some("-rust-dev".to_string())
} else {
Some(format!("-rust-{}-{}", builder.version, builder.config.channel))
};
if let Some(ref suffix) = llvm_version_suffix {
cfg.define("LLVM_VERSION_SUFFIX", suffix);
}
configure_cmake(builder, target, &mut cfg, true, ldflags, &[]);
configure_llvm(builder, target, &mut cfg);
for (key, val) in &builder.config.llvm_build_config {
cfg.define(key, val);
}
if builder.config.dry_run() {
return res;
}
cfg.build();
// Helper to find the name of LLVM's shared library on darwin and linux.
let find_llvm_lib_name = |extension| {
let major = get_llvm_version_major(builder, &res.llvm_config);
match &llvm_version_suffix {
Some(version_suffix) => format!("libLLVM-{major}{version_suffix}.{extension}"),
None => format!("libLLVM-{major}.{extension}"),
}
};
// FIXME(ZuseZ4): Do we need that for Enzyme too?
// When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
// libLLVM.dylib will be built. However, llvm-config will still look
// for a versioned path like libLLVM-14.dylib. Manually create a symbolic
// link to make llvm-config happy.
if builder.llvm_link_shared() && target.contains("apple-darwin") {
let lib_name = find_llvm_lib_name("dylib");
let lib_llvm = out_dir.join("build").join("lib").join(lib_name);
if !lib_llvm.exists() {
t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));
}
}
// When building LLVM as a shared library on linux, it can contain unexpected debuginfo:
// some can come from the C++ standard library. Unless we're explicitly requesting LLVM to
// be built with debuginfo, strip it away after the fact, to make dist artifacts smaller.
if builder.llvm_link_shared()
&& builder.config.llvm_optimize
&& !builder.config.llvm_release_debuginfo
{
// Find the name of the LLVM shared library that we just built.
let lib_name = find_llvm_lib_name("so");
// If the shared library exists in LLVM's `/build/lib/` or `/lib/` folders, strip its
// debuginfo.
crate::core::build_steps::compile::strip_debug(
builder,
target,
&out_dir.join("lib").join(&lib_name),
);
crate::core::build_steps::compile::strip_debug(
builder,
target,
&out_dir.join("build").join("lib").join(&lib_name),
);
}
t!(stamp.write());
res
}
}
pub fn get_llvm_version(builder: &Builder<'_>, llvm_config: &Path) -> String {
command(llvm_config).arg("--version").run_capture_stdout(builder).stdout().trim().to_owned()
}
pub fn get_llvm_version_major(builder: &Builder<'_>, llvm_config: &Path) -> u8 {
let version = get_llvm_version(builder, llvm_config);
let major_str = version.split_once('.').expect("Failed to parse LLVM version").0;
major_str.parse().unwrap()
}
fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
if builder.config.dry_run() {
return;
}
let version = get_llvm_version(builder, llvm_config);
let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
if major >= 19 {
return;
}
}
panic!("\n\nbad LLVM version: {version}, need >=19\n\n")
}
fn configure_cmake(
builder: &Builder<'_>,
target: TargetSelection,
cfg: &mut cmake::Config,
use_compiler_launcher: bool,
mut ldflags: LdFlags,
suppressed_compiler_flag_prefixes: &[&str],
) {
// Do not print installation messages for up-to-date files.
// LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
// Do not allow the user's value of DESTDIR to influence where
// LLVM will install itself. LLVM must always be installed in our
// own build directories.
cfg.env("DESTDIR", "");
if builder.ninja() {
cfg.generator("Ninja");
}
cfg.target(&target.triple).host(&builder.config.build.triple);
if !builder.config.is_host_target(target) {
cfg.define("CMAKE_CROSSCOMPILING", "True");
// NOTE: Ideally, we wouldn't have to do this, and `cmake-rs` would just handle it for us.
// But it currently determines this based on the `CARGO_CFG_TARGET_OS` environment variable,
// which isn't set when compiling outside `build.rs` (like bootstrap is).
//
// So for now, we define `CMAKE_SYSTEM_NAME` ourselves, to panicking in `cmake-rs`.
if target.contains("netbsd") {
cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
} else if target.contains("dragonfly") {
cfg.define("CMAKE_SYSTEM_NAME", "DragonFly");
} else if target.contains("openbsd") {
cfg.define("CMAKE_SYSTEM_NAME", "OpenBSD");
} else if target.contains("freebsd") {
cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
} else if target.is_windows() {
cfg.define("CMAKE_SYSTEM_NAME", "Windows");
} else if target.contains("haiku") {
cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
} else if target.contains("solaris") || target.contains("illumos") {
cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
} else if target.contains("linux") {
cfg.define("CMAKE_SYSTEM_NAME", "Linux");
} else if target.contains("darwin") {
// macOS
cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
} else if target.contains("ios") {
cfg.define("CMAKE_SYSTEM_NAME", "iOS");
} else if target.contains("tvos") {
cfg.define("CMAKE_SYSTEM_NAME", "tvOS");
} else if target.contains("visionos") {
cfg.define("CMAKE_SYSTEM_NAME", "visionOS");
} else if target.contains("watchos") {
cfg.define("CMAKE_SYSTEM_NAME", "watchOS");
} else if target.contains("none") {
// "none" should be the last branch
cfg.define("CMAKE_SYSTEM_NAME", "Generic");
} else {
builder.info(&format!(
"could not determine CMAKE_SYSTEM_NAME from the target `{target}`, build may fail",
));
// Fallback, set `CMAKE_SYSTEM_NAME` anyhow to avoid the logic `cmake-rs` tries, and
// to avoid CMAKE_SYSTEM_NAME being inferred from the host.
cfg.define("CMAKE_SYSTEM_NAME", "Generic");
}
// When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
// that case like CMake we cannot easily determine system version either.
//
// Since, the LLVM itself makes rather limited use of version checks in
// CMakeFiles (and then only in tests), and so far no issues have been
// reported, the system version is currently left unset.
if target.contains("apple") {
if !target.contains("darwin") {
// FIXME(madsmtm): compiler-rt's CMake setup is kinda weird, it seems like they do
// version testing etc. for macOS (i.e. Darwin), even while building for iOS?
//
// So for now we set it to "Darwin" on all Apple platforms.
cfg.define("CMAKE_SYSTEM_NAME", "Darwin");
// These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
cfg.define("CMAKE_OSX_SYSROOT", "/");
cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
}
// Make sure that CMake does not build universal binaries on macOS.
// Explicitly specify the one single target architecture.
if target.starts_with("aarch64") {
// macOS uses a different name for building arm64
cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
} else if target.starts_with("i686") {
// macOS uses a different name for building i386
cfg.define("CMAKE_OSX_ARCHITECTURES", "i386");
} else {
cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
}
}
}
let sanitize_cc = |cc: &Path| {
if target.is_msvc() {
OsString::from(cc.to_str().unwrap().replace('\\', "/"))
} else {
cc.as_os_str().to_owned()
}
};
// MSVC with CMake uses msbuild by default which doesn't respect these
// vars that we'd otherwise configure. In that case we just skip this
// entirely.
if target.is_msvc() && !builder.ninja() {
return;
}
let (cc, cxx) = match builder.config.llvm_clang_cl {
Some(ref cl) => (cl.into(), cl.into()),
None => (builder.cc(target), builder.cxx(target).unwrap()),
};
// If ccache is configured we inform the build a little differently how
// to invoke ccache while also invoking our compilers.
if use_compiler_launcher {
if let Some(ref ccache) = builder.config.ccache {
cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
.define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
}
}
cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
.define("CMAKE_CXX_COMPILER", sanitize_cc(&cxx))
.define("CMAKE_ASM_COMPILER", sanitize_cc(&cc));
cfg.build_arg("-j").build_arg(builder.jobs().to_string());
// FIXME(madsmtm): Allow `cmake-rs` to select flags by itself by passing
// our flags via `.cflag`/`.cxxflag` instead.
//
// Needs `suppressed_compiler_flag_prefixes` to be gone, and hence
// https://github.com/llvm/llvm-project/issues/88780 to be fixed.
let mut cflags: OsString = builder
.cc_handled_clags(target, CLang::C)
.into_iter()
.chain(builder.cc_unhandled_cflags(target, GitRepo::Llvm, CLang::C))
.filter(|flag| {
!suppressed_compiler_flag_prefixes
.iter()
.any(|suppressed_prefix| flag.starts_with(suppressed_prefix))
})
.collect::<Vec<String>>()
.join(" ")
.into();
if let Some(ref s) = builder.config.llvm_cflags {
cflags.push(" ");
cflags.push(s);
}
if target.contains("ohos") {
cflags.push(" -D_LINUX_SYSINFO_H");
}
if builder.config.llvm_clang_cl.is_some() {
cflags.push(format!(" --target={target}"));
}
cfg.define("CMAKE_C_FLAGS", cflags);
let mut cxxflags: OsString = builder
.cc_handled_clags(target, CLang::Cxx)
.into_iter()
.chain(builder.cc_unhandled_cflags(target, GitRepo::Llvm, CLang::Cxx))
.filter(|flag| {
!suppressed_compiler_flag_prefixes
.iter()
.any(|suppressed_prefix| flag.starts_with(suppressed_prefix))
})
.collect::<Vec<String>>()
.join(" ")
.into();
if let Some(ref s) = builder.config.llvm_cxxflags {
cxxflags.push(" ");
cxxflags.push(s);
}
if target.contains("ohos") {
cxxflags.push(" -D_LINUX_SYSINFO_H");
}
if builder.config.llvm_clang_cl.is_some() {
cxxflags.push(format!(" --target={target}"));
}
cfg.define("CMAKE_CXX_FLAGS", cxxflags);
if let Some(ar) = builder.ar(target) {
if ar.is_absolute() {
// LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
// tries to resolve this path in the LLVM build directory.
cfg.define("CMAKE_AR", sanitize_cc(&ar));
}
}
if let Some(ranlib) = builder.ranlib(target) {
if ranlib.is_absolute() {
// LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
// tries to resolve this path in the LLVM build directory.
cfg.define("CMAKE_RANLIB", sanitize_cc(&ranlib));
}
}
if let Some(ref flags) = builder.config.llvm_ldflags {
ldflags.push_all(flags);
}
if let Some(flags) = get_var("LDFLAGS", &builder.config.build.triple, &target.triple) {
ldflags.push_all(&flags);
}
// For distribution we want the LLVM tools to be *statically* linked to libstdc++.
// We also do this if the user explicitly requested static libstdc++.
if builder.config.llvm_static_stdcpp
&& !target.is_msvc()
&& !target.contains("netbsd")
&& !target.contains("solaris")
{
if target.contains("apple") || target.is_windows() {
ldflags.push_all("-static-libstdc++");
} else {
ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
}
}
cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
if env::var_os("SCCACHE_ERROR_LOG").is_some() {
cfg.env("RUSTC_LOG", "sccache=warn");
}
}
fn configure_llvm(builder: &Builder<'_>, target: TargetSelection, cfg: &mut cmake::Config) {
// ThinLTO is only available when building with LLVM, enabling LLD is required.
// Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
if builder.config.llvm_thin_lto {
cfg.define("LLVM_ENABLE_LTO", "Thin");
if !target.contains("apple") {
cfg.define("LLVM_ENABLE_LLD", "ON");
}
}
// Libraries for ELF section compression.
if builder.config.llvm_libzstd {
cfg.define("LLVM_ENABLE_ZSTD", "FORCE_ON");
cfg.define("LLVM_USE_STATIC_ZSTD", "TRUE");
} else {
cfg.define("LLVM_ENABLE_ZSTD", "OFF");
}
if let Some(ref linker) = builder.config.llvm_use_linker {
cfg.define("LLVM_USE_LINKER", linker);
}
if builder.config.llvm_allow_old_toolchain {
cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
}
}
// Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
let kind = if host == target { "HOST" } else { "TARGET" };
let target_u = target.replace('-', "_");
env::var_os(format!("{var_base}_{target}"))
.or_else(|| env::var_os(format!("{var_base}_{target_u}")))
.or_else(|| env::var_os(format!("{kind}_{var_base}")))
.or_else(|| env::var_os(var_base))
}
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct Enzyme {
pub target: TargetSelection,
}
impl Step for Enzyme {
type Output = PathBuf;
const ONLY_HOSTS: bool = true;
fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
run.path("src/tools/enzyme/enzyme")
}
fn make_run(run: RunConfig<'_>) {
run.builder.ensure(Enzyme { target: run.target });
}
/// Compile Enzyme for `target`.
#[cfg_attr(
feature = "tracing",
instrument(
level = "debug",
name = "Enzyme::run",
skip_all,
fields(target = ?self.target),
),
)]
fn run(self, builder: &Builder<'_>) -> PathBuf {
builder.require_submodule(
"src/tools/enzyme",
Some("The Enzyme sources are required for autodiff."),
);
if builder.config.dry_run() {
let out_dir = builder.enzyme_out(self.target);
return out_dir;
}
let target = self.target;
let LlvmResult { llvm_config, .. } = builder.ensure(Llvm { target: self.target });
static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
generate_smart_stamp_hash(
builder,
&builder.config.src.join("src/tools/enzyme"),
builder.enzyme_info.sha().unwrap_or_default(),
)
});
let out_dir = builder.enzyme_out(target);
let stamp = BuildStamp::new(&out_dir).with_prefix("enzyme").add_stamp(smart_stamp_hash);
trace!("checking build stamp to see if we need to rebuild enzyme artifacts");
if stamp.is_up_to_date() {
trace!(?out_dir, "enzyme build artifacts are up to date");
if stamp.stamp().is_empty() {
builder.info(
"Could not determine the Enzyme submodule commit hash. \
Assuming that an Enzyme rebuild is not necessary.",
);
builder.info(&format!(
"To force Enzyme to rebuild, remove the file `{}`",
stamp.path().display()
));
}
return out_dir;
}
trace!(?target, "(re)building enzyme artifacts");
builder.info(&format!("Building Enzyme for {target}"));
t!(stamp.remove());
let _time = helpers::timeit(builder);
t!(fs::create_dir_all(&out_dir));
builder
.config
.update_submodule(Path::new("src").join("tools").join("enzyme").to_str().unwrap());
let mut cfg = cmake::Config::new(builder.src.join("src/tools/enzyme/enzyme/"));
configure_cmake(builder, target, &mut cfg, true, LdFlags::default(), &[]);
// Re-use the same flags as llvm to control the level of debug information
// generated by Enzyme.
// FIXME(ZuseZ4): Find a nicer way to use Enzyme Debug builds.
let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
(false, _) => "Debug",
(true, false) => "Release",
(true, true) => "RelWithDebInfo",
};
trace!(?profile);
cfg.out_dir(&out_dir)
.profile(profile)
.env("LLVM_CONFIG_REAL", &llvm_config)
.define("LLVM_ENABLE_ASSERTIONS", "ON")
.define("ENZYME_EXTERNAL_SHARED_LIB", "ON")
.define("LLVM_DIR", builder.llvm_out(target));
cfg.build();
t!(stamp.write());
out_dir
}
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Lld {
pub target: TargetSelection,
}
impl Step for Lld {
type Output = PathBuf;
const ONLY_HOSTS: bool = true;
fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
run.path("src/llvm-project/lld")
}
fn make_run(run: RunConfig<'_>) {
run.builder.ensure(Lld { target: run.target });
}
/// Compile LLD for `target`.