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