]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_llvm/build.rs
Auto merge of #104572 - pkubaj:patch-1, r=cuviper
[rust.git] / compiler / rustc_llvm / build.rs
1 use std::env;
2 use std::ffi::{OsStr, OsString};
3 use std::fmt::Display;
4 use std::path::{Path, PathBuf};
5 use std::process::{Command, Stdio};
6
7 const OPTIONAL_COMPONENTS: &[&str] = &[
8     "x86",
9     "arm",
10     "aarch64",
11     "amdgpu",
12     "avr",
13     "m68k",
14     "mips",
15     "powerpc",
16     "systemz",
17     "jsbackend",
18     "webassembly",
19     "msp430",
20     "sparc",
21     "nvptx",
22     "hexagon",
23     "riscv",
24     "bpf",
25 ];
26
27 const REQUIRED_COMPONENTS: &[&str] =
28     &["ipo", "bitreader", "bitwriter", "linker", "asmparser", "lto", "coverage", "instrumentation"];
29
30 fn detect_llvm_link() -> (&'static str, &'static str) {
31     // Force the link mode we want, preferring static by default, but
32     // possibly overridden by `configure --enable-llvm-link-shared`.
33     if tracked_env_var_os("LLVM_LINK_SHARED").is_some() {
34         ("dylib", "--link-shared")
35     } else {
36         ("static", "--link-static")
37     }
38 }
39
40 // Because Cargo adds the compiler's dylib path to our library search path, llvm-config may
41 // break: the dylib path for the compiler, as of this writing, contains a copy of the LLVM
42 // shared library, which means that when our freshly built llvm-config goes to load it's
43 // associated LLVM, it actually loads the compiler's LLVM. In particular when building the first
44 // compiler (i.e., in stage 0) that's a problem, as the compiler's LLVM is likely different from
45 // the one we want to use. As such, we restore the environment to what bootstrap saw. This isn't
46 // perfect -- we might actually want to see something from Cargo's added library paths -- but
47 // for now it works.
48 fn restore_library_path() {
49     let key = tracked_env_var_os("REAL_LIBRARY_PATH_VAR").expect("REAL_LIBRARY_PATH_VAR");
50     if let Some(env) = tracked_env_var_os("REAL_LIBRARY_PATH") {
51         env::set_var(&key, &env);
52     } else {
53         env::remove_var(&key);
54     }
55 }
56
57 /// Reads an environment variable and adds it to dependencies.
58 /// Supposed to be used for all variables except those set for build scripts by cargo
59 /// <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts>
60 fn tracked_env_var_os<K: AsRef<OsStr> + Display>(key: K) -> Option<OsString> {
61     println!("cargo:rerun-if-env-changed={}", key);
62     env::var_os(key)
63 }
64
65 fn rerun_if_changed_anything_in_dir(dir: &Path) {
66     let mut stack = dir
67         .read_dir()
68         .unwrap()
69         .map(|e| e.unwrap())
70         .filter(|e| &*e.file_name() != ".git")
71         .collect::<Vec<_>>();
72     while let Some(entry) = stack.pop() {
73         let path = entry.path();
74         if entry.file_type().unwrap().is_dir() {
75             stack.extend(path.read_dir().unwrap().map(|e| e.unwrap()));
76         } else {
77             println!("cargo:rerun-if-changed={}", path.display());
78         }
79     }
80 }
81
82 #[track_caller]
83 fn output(cmd: &mut Command) -> String {
84     let output = match cmd.stderr(Stdio::inherit()).output() {
85         Ok(status) => status,
86         Err(e) => {
87             println!("\n\nfailed to execute command: {:?}\nerror: {}\n\n", cmd, e);
88             std::process::exit(1);
89         }
90     };
91     if !output.status.success() {
92         panic!(
93             "command did not execute successfully: {:?}\n\
94              expected success, got: {}",
95             cmd, output.status
96         );
97     }
98     String::from_utf8(output.stdout).unwrap()
99 }
100
101 fn main() {
102     for component in REQUIRED_COMPONENTS.iter().chain(OPTIONAL_COMPONENTS.iter()) {
103         println!("cargo:rustc-check-cfg=values(llvm_component,\"{}\")", component);
104     }
105
106     if tracked_env_var_os("RUST_CHECK").is_some() {
107         // If we're just running `check`, there's no need for LLVM to be built.
108         return;
109     }
110
111     restore_library_path();
112
113     let target = env::var("TARGET").expect("TARGET was not set");
114     let llvm_config =
115         tracked_env_var_os("LLVM_CONFIG").map(|x| Some(PathBuf::from(x))).unwrap_or_else(|| {
116             if let Some(dir) = tracked_env_var_os("CARGO_TARGET_DIR").map(PathBuf::from) {
117                 let to_test = dir
118                     .parent()
119                     .unwrap()
120                     .parent()
121                     .unwrap()
122                     .join(&target)
123                     .join("llvm/bin/llvm-config");
124                 if Command::new(&to_test).output().is_ok() {
125                     return Some(to_test);
126                 }
127             }
128             None
129         });
130
131     if let Some(llvm_config) = &llvm_config {
132         println!("cargo:rerun-if-changed={}", llvm_config.display());
133     }
134     let llvm_config = llvm_config.unwrap_or_else(|| PathBuf::from("llvm-config"));
135
136     // Test whether we're cross-compiling LLVM. This is a pretty rare case
137     // currently where we're producing an LLVM for a different platform than
138     // what this build script is currently running on.
139     //
140     // In that case, there's no guarantee that we can actually run the target,
141     // so the build system works around this by giving us the LLVM_CONFIG for
142     // the host platform. This only really works if the host LLVM and target
143     // LLVM are compiled the same way, but for us that's typically the case.
144     //
145     // We *want* detect this cross compiling situation by asking llvm-config
146     // what its host-target is. If that's not the TARGET, then we're cross
147     // compiling. Unfortunately `llvm-config` seems either be buggy, or we're
148     // misconfiguring it, because the `i686-pc-windows-gnu` build of LLVM will
149     // report itself with a `--host-target` of `x86_64-pc-windows-gnu`. This
150     // tricks us into thinking we're doing a cross build when we aren't, so
151     // havoc ensues.
152     //
153     // In any case, if we're cross compiling, this generally just means that we
154     // can't trust all the output of llvm-config because it might be targeted
155     // for the host rather than the target. As a result a bunch of blocks below
156     // are gated on `if !is_crossed`
157     let target = env::var("TARGET").expect("TARGET was not set");
158     let host = env::var("HOST").expect("HOST was not set");
159     let is_crossed = target != host;
160
161     let components = output(Command::new(&llvm_config).arg("--components"));
162     let mut components = components.split_whitespace().collect::<Vec<_>>();
163     components.retain(|c| OPTIONAL_COMPONENTS.contains(c) || REQUIRED_COMPONENTS.contains(c));
164
165     for component in REQUIRED_COMPONENTS {
166         if !components.contains(component) {
167             panic!("require llvm component {} but wasn't found", component);
168         }
169     }
170
171     for component in components.iter() {
172         println!("cargo:rustc-cfg=llvm_component=\"{}\"", component);
173     }
174
175     // Link in our own LLVM shims, compiled with the same flags as LLVM
176     let mut cmd = Command::new(&llvm_config);
177     cmd.arg("--cxxflags");
178     let cxxflags = output(&mut cmd);
179     let mut cfg = cc::Build::new();
180     cfg.warnings(false);
181     for flag in cxxflags.split_whitespace() {
182         // Ignore flags like `-m64` when we're doing a cross build
183         if is_crossed && flag.starts_with("-m") {
184             continue;
185         }
186
187         if flag.starts_with("-flto") {
188             continue;
189         }
190
191         // -Wdate-time is not supported by the netbsd cross compiler
192         if is_crossed && target.contains("netbsd") && flag.contains("date-time") {
193             continue;
194         }
195
196         // Include path contains host directory, replace it with target
197         if is_crossed && flag.starts_with("-I") {
198             cfg.flag(&flag.replace(&host, &target));
199             continue;
200         }
201
202         cfg.flag(flag);
203     }
204
205     for component in &components {
206         let mut flag = String::from("LLVM_COMPONENT_");
207         flag.push_str(&component.to_uppercase());
208         cfg.define(&flag, None);
209     }
210
211     if tracked_env_var_os("LLVM_RUSTLLVM").is_some() {
212         cfg.define("LLVM_RUSTLLVM", None);
213     }
214
215     if tracked_env_var_os("LLVM_NDEBUG").is_some() {
216         cfg.define("NDEBUG", None);
217         cfg.debug(false);
218     }
219
220     rerun_if_changed_anything_in_dir(Path::new("llvm-wrapper"));
221     cfg.file("llvm-wrapper/PassWrapper.cpp")
222         .file("llvm-wrapper/RustWrapper.cpp")
223         .file("llvm-wrapper/ArchiveWrapper.cpp")
224         .file("llvm-wrapper/CoverageMappingWrapper.cpp")
225         .file("llvm-wrapper/SymbolWrapper.cpp")
226         .file("llvm-wrapper/Linker.cpp")
227         .cpp(true)
228         .cpp_link_stdlib(None) // we handle this below
229         .compile("llvm-wrapper");
230
231     let (llvm_kind, llvm_link_arg) = detect_llvm_link();
232
233     // Link in all LLVM libraries, if we're using the "wrong" llvm-config then
234     // we don't pick up system libs because unfortunately they're for the host
235     // of llvm-config, not the target that we're attempting to link.
236     let mut cmd = Command::new(&llvm_config);
237     cmd.arg(llvm_link_arg).arg("--libs");
238
239     if !is_crossed {
240         cmd.arg("--system-libs");
241     }
242
243     if (target.starts_with("arm") && !target.contains("freebsd"))
244         || target.starts_with("mips-")
245         || target.starts_with("mipsel-")
246         || target.starts_with("powerpc-")
247     {
248         // 32-bit targets need to link libatomic.
249         println!("cargo:rustc-link-lib=atomic");
250     } else if target.contains("windows-gnu") {
251         println!("cargo:rustc-link-lib=shell32");
252         println!("cargo:rustc-link-lib=uuid");
253     } else if target.contains("netbsd") || target.contains("haiku") || target.contains("darwin") {
254         println!("cargo:rustc-link-lib=z");
255     }
256     cmd.args(&components);
257
258     for lib in output(&mut cmd).split_whitespace() {
259         let name = if let Some(stripped) = lib.strip_prefix("-l") {
260             stripped
261         } else if let Some(stripped) = lib.strip_prefix('-') {
262             stripped
263         } else if Path::new(lib).exists() {
264             // On MSVC llvm-config will print the full name to libraries, but
265             // we're only interested in the name part
266             let name = Path::new(lib).file_name().unwrap().to_str().unwrap();
267             name.trim_end_matches(".lib")
268         } else if lib.ends_with(".lib") {
269             // Some MSVC libraries just come up with `.lib` tacked on, so chop
270             // that off
271             lib.trim_end_matches(".lib")
272         } else {
273             continue;
274         };
275
276         // Don't need or want this library, but LLVM's CMake build system
277         // doesn't provide a way to disable it, so filter it here even though we
278         // may or may not have built it. We don't reference anything from this
279         // library and it otherwise may just pull in extra dependencies on
280         // libedit which we don't want
281         if name == "LLVMLineEditor" {
282             continue;
283         }
284
285         let kind = if name.starts_with("LLVM") { llvm_kind } else { "dylib" };
286         println!("cargo:rustc-link-lib={}={}", kind, name);
287     }
288
289     // LLVM ldflags
290     //
291     // If we're a cross-compile of LLVM then unfortunately we can't trust these
292     // ldflags (largely where all the LLVM libs are located). Currently just
293     // hack around this by replacing the host triple with the target and pray
294     // that those -L directories are the same!
295     let mut cmd = Command::new(&llvm_config);
296     cmd.arg(llvm_link_arg).arg("--ldflags");
297     for lib in output(&mut cmd).split_whitespace() {
298         if is_crossed {
299             if let Some(stripped) = lib.strip_prefix("-LIBPATH:") {
300                 println!("cargo:rustc-link-search=native={}", stripped.replace(&host, &target));
301             } else if let Some(stripped) = lib.strip_prefix("-L") {
302                 println!("cargo:rustc-link-search=native={}", stripped.replace(&host, &target));
303             }
304         } else if let Some(stripped) = lib.strip_prefix("-LIBPATH:") {
305             println!("cargo:rustc-link-search=native={}", stripped);
306         } else if let Some(stripped) = lib.strip_prefix("-l") {
307             println!("cargo:rustc-link-lib={}", stripped);
308         } else if let Some(stripped) = lib.strip_prefix("-L") {
309             println!("cargo:rustc-link-search=native={}", stripped);
310         }
311     }
312
313     // Some LLVM linker flags (-L and -l) may be needed even when linking
314     // rustc_llvm, for example when using static libc++, we may need to
315     // manually specify the library search path and -ldl -lpthread as link
316     // dependencies.
317     let llvm_linker_flags = tracked_env_var_os("LLVM_LINKER_FLAGS");
318     if let Some(s) = llvm_linker_flags {
319         for lib in s.into_string().unwrap().split_whitespace() {
320             if let Some(stripped) = lib.strip_prefix("-l") {
321                 println!("cargo:rustc-link-lib={}", stripped);
322             } else if let Some(stripped) = lib.strip_prefix("-L") {
323                 println!("cargo:rustc-link-search=native={}", stripped);
324             }
325         }
326     }
327
328     let llvm_static_stdcpp = tracked_env_var_os("LLVM_STATIC_STDCPP");
329     let llvm_use_libcxx = tracked_env_var_os("LLVM_USE_LIBCXX");
330
331     let stdcppname = if target.contains("openbsd") {
332         if target.contains("sparc64") { "estdc++" } else { "c++" }
333     } else if target.contains("darwin")
334         || target.contains("freebsd")
335         || target.contains("windows-gnullvm")
336     {
337         "c++"
338     } else if target.contains("netbsd") && llvm_static_stdcpp.is_some() {
339         // NetBSD uses a separate library when relocation is required
340         "stdc++_p"
341     } else if llvm_use_libcxx.is_some() {
342         "c++"
343     } else {
344         "stdc++"
345     };
346
347     // RISC-V GCC erroneously requires libatomic for sub-word
348     // atomic operations. Some BSD uses Clang as its system
349     // compiler and provides no libatomic in its base system so
350     // does not want this.
351     if target.starts_with("riscv") && !target.contains("freebsd") && !target.contains("openbsd") {
352         println!("cargo:rustc-link-lib=atomic");
353     }
354
355     // C++ runtime library
356     if !target.contains("msvc") {
357         if let Some(s) = llvm_static_stdcpp {
358             assert!(!cxxflags.contains("stdlib=libc++"));
359             let path = PathBuf::from(s);
360             println!("cargo:rustc-link-search=native={}", path.parent().unwrap().display());
361             if target.contains("windows") {
362                 println!("cargo:rustc-link-lib=static:-bundle={}", stdcppname);
363             } else {
364                 println!("cargo:rustc-link-lib=static={}", stdcppname);
365             }
366         } else if cxxflags.contains("stdlib=libc++") {
367             println!("cargo:rustc-link-lib=c++");
368         } else {
369             println!("cargo:rustc-link-lib={}", stdcppname);
370         }
371     }
372
373     // Libstdc++ depends on pthread which Rust doesn't link on MinGW
374     // since nothing else requires it.
375     if target.ends_with("windows-gnu") {
376         println!("cargo:rustc-link-lib=static:-bundle=pthread");
377     }
378 }