]> git.lizzy.rs Git - rust.git/blob - src/librustc_llvm/build.rs
Auto merge of #71292 - marmeladema:queries-local-def-id, r=eddyb
[rust.git] / src / librustc_llvm / build.rs
1 use std::env;
2 use std::path::{Path, PathBuf};
3 use std::process::Command;
4
5 use build_helper::output;
6
7 fn detect_llvm_link() -> (&'static str, &'static str) {
8     // Force the link mode we want, preferring static by default, but
9     // possibly overridden by `configure --enable-llvm-link-shared`.
10     if env::var_os("LLVM_LINK_SHARED").is_some() {
11         ("dylib", "--link-shared")
12     } else {
13         ("static", "--link-static")
14     }
15 }
16
17 fn main() {
18     if env::var_os("RUST_CHECK").is_some() {
19         // If we're just running `check`, there's no need for LLVM to be built.
20         println!("cargo:rerun-if-env-changed=RUST_CHECK");
21         return;
22     }
23
24     build_helper::restore_library_path();
25
26     let target = env::var("TARGET").expect("TARGET was not set");
27     let llvm_config =
28         env::var_os("LLVM_CONFIG").map(|x| Some(PathBuf::from(x))).unwrap_or_else(|| {
29             if let Some(dir) = env::var_os("CARGO_TARGET_DIR").map(PathBuf::from) {
30                 let to_test = dir
31                     .parent()
32                     .unwrap()
33                     .parent()
34                     .unwrap()
35                     .join(&target)
36                     .join("llvm/bin/llvm-config");
37                 if Command::new(&to_test).output().is_ok() {
38                     return Some(to_test);
39                 }
40             }
41             None
42         });
43
44     if let Some(llvm_config) = &llvm_config {
45         println!("cargo:rerun-if-changed={}", llvm_config.display());
46     }
47     let llvm_config = llvm_config.unwrap_or_else(|| PathBuf::from("llvm-config"));
48
49     println!("cargo:rerun-if-env-changed=LLVM_CONFIG");
50
51     // Test whether we're cross-compiling LLVM. This is a pretty rare case
52     // currently where we're producing an LLVM for a different platform than
53     // what this build script is currently running on.
54     //
55     // In that case, there's no guarantee that we can actually run the target,
56     // so the build system works around this by giving us the LLVM_CONFIG for
57     // the host platform. This only really works if the host LLVM and target
58     // LLVM are compiled the same way, but for us that's typically the case.
59     //
60     // We *want* detect this cross compiling situation by asking llvm-config
61     // what its host-target is. If that's not the TARGET, then we're cross
62     // compiling. Unfortunately `llvm-config` seems either be buggy, or we're
63     // misconfiguring it, because the `i686-pc-windows-gnu` build of LLVM will
64     // report itself with a `--host-target` of `x86_64-pc-windows-gnu`. This
65     // tricks us into thinking we're doing a cross build when we aren't, so
66     // havoc ensues.
67     //
68     // In any case, if we're cross compiling, this generally just means that we
69     // can't trust all the output of llvm-config because it might be targeted
70     // for the host rather than the target. As a result a bunch of blocks below
71     // are gated on `if !is_crossed`
72     let target = env::var("TARGET").expect("TARGET was not set");
73     let host = env::var("HOST").expect("HOST was not set");
74     let is_crossed = target != host;
75
76     let mut optional_components = vec![
77         "x86",
78         "arm",
79         "aarch64",
80         "amdgpu",
81         "mips",
82         "powerpc",
83         "systemz",
84         "jsbackend",
85         "webassembly",
86         "msp430",
87         "sparc",
88         "nvptx",
89         "hexagon",
90     ];
91
92     let mut version_cmd = Command::new(&llvm_config);
93     version_cmd.arg("--version");
94     let version_output = output(&mut version_cmd);
95     let mut parts = version_output.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
96     let (major, _minor) = if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {
97         (major, minor)
98     } else {
99         (6, 0)
100     };
101
102     if major > 6 {
103         optional_components.push("riscv");
104     }
105
106     let required_components =
107         &["ipo", "bitreader", "bitwriter", "linker", "asmparser", "lto", "instrumentation"];
108
109     let components = output(Command::new(&llvm_config).arg("--components"));
110     let mut components = components.split_whitespace().collect::<Vec<_>>();
111     components.retain(|c| optional_components.contains(c) || required_components.contains(c));
112
113     for component in required_components {
114         if !components.contains(component) {
115             panic!("require llvm component {} but wasn't found", component);
116         }
117     }
118
119     for component in components.iter() {
120         println!("cargo:rustc-cfg=llvm_component=\"{}\"", component);
121     }
122
123     if major >= 9 {
124         println!("cargo:rustc-cfg=llvm_has_msp430_asm_parser");
125     }
126
127     // Link in our own LLVM shims, compiled with the same flags as LLVM
128     let mut cmd = Command::new(&llvm_config);
129     cmd.arg("--cxxflags");
130     let cxxflags = output(&mut cmd);
131     let mut cfg = cc::Build::new();
132     cfg.warnings(false);
133     for flag in cxxflags.split_whitespace() {
134         // Ignore flags like `-m64` when we're doing a cross build
135         if is_crossed && flag.starts_with("-m") {
136             continue;
137         }
138
139         if flag.starts_with("-flto") {
140             continue;
141         }
142
143         // -Wdate-time is not supported by the netbsd cross compiler
144         if is_crossed && target.contains("netbsd") && flag.contains("date-time") {
145             continue;
146         }
147
148         cfg.flag(flag);
149     }
150
151     for component in &components {
152         let mut flag = String::from("LLVM_COMPONENT_");
153         flag.push_str(&component.to_uppercase());
154         cfg.define(&flag, None);
155     }
156
157     println!("cargo:rerun-if-changed-env=LLVM_RUSTLLVM");
158     if env::var_os("LLVM_RUSTLLVM").is_some() {
159         cfg.define("LLVM_RUSTLLVM", None);
160     }
161
162     if env::var_os("LLVM_NDEBUG").is_some() {
163         cfg.define("NDEBUG", None);
164         cfg.debug(false);
165     }
166
167     build_helper::rerun_if_changed_anything_in_dir(Path::new("../rustllvm"));
168     cfg.file("../rustllvm/PassWrapper.cpp")
169         .file("../rustllvm/RustWrapper.cpp")
170         .file("../rustllvm/ArchiveWrapper.cpp")
171         .file("../rustllvm/Linker.cpp")
172         .cpp(true)
173         .cpp_link_stdlib(None) // we handle this below
174         .compile("rustllvm");
175
176     let (llvm_kind, llvm_link_arg) = detect_llvm_link();
177
178     // Link in all LLVM libraries, if we're using the "wrong" llvm-config then
179     // we don't pick up system libs because unfortunately they're for the host
180     // of llvm-config, not the target that we're attempting to link.
181     let mut cmd = Command::new(&llvm_config);
182     cmd.arg(llvm_link_arg).arg("--libs");
183
184     if !is_crossed {
185         cmd.arg("--system-libs");
186     }
187     cmd.args(&components);
188
189     for lib in output(&mut cmd).split_whitespace() {
190         let name = if lib.starts_with("-l") {
191             &lib[2..]
192         } else if lib.starts_with('-') {
193             &lib[1..]
194         } else if Path::new(lib).exists() {
195             // On MSVC llvm-config will print the full name to libraries, but
196             // we're only interested in the name part
197             let name = Path::new(lib).file_name().unwrap().to_str().unwrap();
198             name.trim_end_matches(".lib")
199         } else if lib.ends_with(".lib") {
200             // Some MSVC libraries just come up with `.lib` tacked on, so chop
201             // that off
202             lib.trim_end_matches(".lib")
203         } else {
204             continue;
205         };
206
207         // Don't need or want this library, but LLVM's CMake build system
208         // doesn't provide a way to disable it, so filter it here even though we
209         // may or may not have built it. We don't reference anything from this
210         // library and it otherwise may just pull in extra dependencies on
211         // libedit which we don't want
212         if name == "LLVMLineEditor" {
213             continue;
214         }
215
216         let kind = if name.starts_with("LLVM") { llvm_kind } else { "dylib" };
217         println!("cargo:rustc-link-lib={}={}", kind, name);
218     }
219
220     // LLVM ldflags
221     //
222     // If we're a cross-compile of LLVM then unfortunately we can't trust these
223     // ldflags (largely where all the LLVM libs are located). Currently just
224     // hack around this by replacing the host triple with the target and pray
225     // that those -L directories are the same!
226     let mut cmd = Command::new(&llvm_config);
227     cmd.arg(llvm_link_arg).arg("--ldflags");
228     for lib in output(&mut cmd).split_whitespace() {
229         if is_crossed {
230             if lib.starts_with("-LIBPATH:") {
231                 println!("cargo:rustc-link-search=native={}", lib[9..].replace(&host, &target));
232             } else if lib.starts_with("-L") {
233                 println!("cargo:rustc-link-search=native={}", lib[2..].replace(&host, &target));
234             }
235         } else if lib.starts_with("-LIBPATH:") {
236             println!("cargo:rustc-link-search=native={}", &lib[9..]);
237         } else if lib.starts_with("-l") {
238             println!("cargo:rustc-link-lib={}", &lib[2..]);
239         } else if lib.starts_with("-L") {
240             println!("cargo:rustc-link-search=native={}", &lib[2..]);
241         }
242     }
243
244     // Some LLVM linker flags (-L and -l) may be needed even when linking
245     // librustc_llvm, for example when using static libc++, we may need to
246     // manually specify the library search path and -ldl -lpthread as link
247     // dependencies.
248     let llvm_linker_flags = env::var_os("LLVM_LINKER_FLAGS");
249     if let Some(s) = llvm_linker_flags {
250         for lib in s.into_string().unwrap().split_whitespace() {
251             if lib.starts_with("-l") {
252                 println!("cargo:rustc-link-lib={}", &lib[2..]);
253             } else if lib.starts_with("-L") {
254                 println!("cargo:rustc-link-search=native={}", &lib[2..]);
255             }
256         }
257     }
258
259     let llvm_static_stdcpp = env::var_os("LLVM_STATIC_STDCPP");
260     let llvm_use_libcxx = env::var_os("LLVM_USE_LIBCXX");
261
262     let stdcppname = if target.contains("openbsd") {
263         if target.contains("sparc64") { "estdc++" } else { "c++" }
264     } else if target.contains("freebsd") {
265         "c++"
266     } else if target.contains("darwin") {
267         "c++"
268     } else if target.contains("netbsd") && llvm_static_stdcpp.is_some() {
269         // NetBSD uses a separate library when relocation is required
270         "stdc++_pic"
271     } else if llvm_use_libcxx.is_some() {
272         "c++"
273     } else {
274         "stdc++"
275     };
276
277     // C++ runtime library
278     if !target.contains("msvc") {
279         if let Some(s) = llvm_static_stdcpp {
280             assert!(!cxxflags.contains("stdlib=libc++"));
281             let path = PathBuf::from(s);
282             println!("cargo:rustc-link-search=native={}", path.parent().unwrap().display());
283             if target.contains("windows") {
284                 println!("cargo:rustc-link-lib=static-nobundle={}", stdcppname);
285             } else {
286                 println!("cargo:rustc-link-lib=static={}", stdcppname);
287             }
288         } else if cxxflags.contains("stdlib=libc++") {
289             println!("cargo:rustc-link-lib=c++");
290         } else {
291             println!("cargo:rustc-link-lib={}", stdcppname);
292         }
293     }
294
295     // LLVM requires symbols from this library, but apparently they're not printed
296     // during llvm-config?
297     if target.contains("windows-gnu") {
298         println!("cargo:rustc-link-lib=static-nobundle=gcc_s");
299         println!("cargo:rustc-link-lib=static-nobundle=pthread");
300         println!("cargo:rustc-link-lib=dylib=uuid");
301     }
302 }