]> git.lizzy.rs Git - rust.git/blob - src/librustc_llvm/build.rs
Auto merge of #39438 - clarcharr:box_from, r=alexcrichton
[rust.git] / src / librustc_llvm / build.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 extern crate gcc;
12 extern crate build_helper;
13
14 use std::process::Command;
15 use std::env;
16 use std::path::{PathBuf, Path};
17
18 use build_helper::output;
19
20 fn detect_llvm_link(llvm_config: &Path) -> (&'static str, Option<&'static str>) {
21     let mut version_cmd = Command::new(llvm_config);
22     version_cmd.arg("--version");
23     let version_output = output(&mut version_cmd);
24     let mut parts = version_output.split('.').take(2)
25         .filter_map(|s| s.parse::<u32>().ok());
26     if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {
27         if major > 3 || (major == 3 && minor >= 9) {
28             // Force the link mode we want, preferring static by default, but
29             // possibly overridden by `configure --enable-llvm-link-shared`.
30             if env::var_os("LLVM_LINK_SHARED").is_some() {
31                 return ("dylib", Some("--link-shared"));
32             } else {
33                 return ("static", Some("--link-static"));
34             }
35         } else if major == 3 && minor == 8 {
36             // Find out LLVM's default linking mode.
37             let mut mode_cmd = Command::new(llvm_config);
38             mode_cmd.arg("--shared-mode");
39             if output(&mut mode_cmd).trim() == "shared" {
40                 return ("dylib", None);
41             } else {
42                 return ("static", None);
43             }
44         }
45     }
46     ("static", None)
47 }
48
49 fn main() {
50     let target = env::var("TARGET").expect("TARGET was not set");
51     let llvm_config = env::var_os("LLVM_CONFIG")
52         .map(PathBuf::from)
53         .unwrap_or_else(|| {
54             if let Some(dir) = env::var_os("CARGO_TARGET_DIR").map(PathBuf::from) {
55                 let to_test = dir.parent()
56                     .unwrap()
57                     .parent()
58                     .unwrap()
59                     .join(&target)
60                     .join("llvm/bin/llvm-config");
61                 if Command::new(&to_test).output().is_ok() {
62                     return to_test;
63                 }
64             }
65             PathBuf::from("llvm-config")
66         });
67
68     println!("cargo:rerun-if-changed={}", llvm_config.display());
69
70     // Test whether we're cross-compiling LLVM. This is a pretty rare case
71     // currently where we're producing an LLVM for a different platform than
72     // what this build script is currently running on.
73     //
74     // In that case, there's no guarantee that we can actually run the target,
75     // so the build system works around this by giving us the LLVM_CONFIG for
76     // the host platform. This only really works if the host LLVM and target
77     // LLVM are compiled the same way, but for us that's typically the case.
78     //
79     // We *want* detect this cross compiling situation by asking llvm-config
80     // what it's host-target is. If that's not the TARGET, then we're cross
81     // compiling. Unfortunately `llvm-config` seems either be buggy, or we're
82     // misconfiguring it, because the `i686-pc-windows-gnu` build of LLVM will
83     // report itself with a `--host-target` of `x86_64-pc-windows-gnu`. This
84     // tricks us into thinking we're doing a cross build when we aren't, so
85     // havoc ensues.
86     //
87     // In any case, if we're cross compiling, this generally just means that we
88     // can't trust all the output of llvm-config becaues it might be targeted
89     // for the host rather than the target. As a result a bunch of blocks below
90     // are gated on `if !is_crossed`
91     let target = env::var("TARGET").expect("TARGET was not set");
92     let host = env::var("HOST").expect("HOST was not set");
93     let is_crossed = target != host;
94
95     let optional_components =
96         ["x86", "arm", "aarch64", "mips", "powerpc", "pnacl", "systemz", "jsbackend", "msp430",
97          "sparc", "nvptx"];
98
99     // FIXME: surely we don't need all these components, right? Stuff like mcjit
100     //        or interpreter the compiler itself never uses.
101     let required_components = &["ipo",
102                                 "bitreader",
103                                 "bitwriter",
104                                 "linker",
105                                 "asmparser",
106                                 "mcjit",
107                                 "interpreter",
108                                 "instrumentation"];
109
110     let components = output(Command::new(&llvm_config).arg("--components"));
111     let mut components = components.split_whitespace().collect::<Vec<_>>();
112     components.retain(|c| optional_components.contains(c) || required_components.contains(c));
113
114     for component in required_components {
115         if !components.contains(component) {
116             panic!("require llvm component {} but wasn't found", component);
117         }
118     }
119
120     for component in components.iter() {
121         println!("cargo:rustc-cfg=llvm_component=\"{}\"", component);
122     }
123
124     // Link in our own LLVM shims, compiled with the same flags as LLVM
125     let mut cmd = Command::new(&llvm_config);
126     cmd.arg("--cxxflags");
127     let cxxflags = output(&mut cmd);
128     let mut cfg = gcc::Config::new();
129     for flag in cxxflags.split_whitespace() {
130         // Ignore flags like `-m64` when we're doing a cross build
131         if is_crossed && flag.starts_with("-m") {
132             continue;
133         }
134         cfg.flag(flag);
135     }
136
137     for component in &components[..] {
138         let mut flag = String::from("-DLLVM_COMPONENT_");
139         flag.push_str(&component.to_uppercase());
140         cfg.flag(&flag);
141     }
142
143     if env::var_os("LLVM_RUSTLLVM").is_some() {
144         cfg.flag("-DLLVM_RUSTLLVM");
145     }
146
147     println!("cargo:rerun-if-changed=../rustllvm/PassWrapper.cpp");
148     println!("cargo:rerun-if-changed=../rustllvm/RustWrapper.cpp");
149     println!("cargo:rerun-if-changed=../rustllvm/ArchiveWrapper.cpp");
150     cfg.file("../rustllvm/PassWrapper.cpp")
151        .file("../rustllvm/RustWrapper.cpp")
152        .file("../rustllvm/ArchiveWrapper.cpp")
153        .cpp(true)
154        .cpp_link_stdlib(None) // we handle this below
155        .compile("librustllvm.a");
156
157     let (llvm_kind, llvm_link_arg) = detect_llvm_link(&llvm_config);
158
159     // Link in all LLVM libraries, if we're uwring the "wrong" llvm-config then
160     // we don't pick up system libs because unfortunately they're for the host
161     // of llvm-config, not the target that we're attempting to link.
162     let mut cmd = Command::new(&llvm_config);
163     cmd.arg("--libs");
164
165     if let Some(link_arg) = llvm_link_arg {
166         cmd.arg(link_arg);
167     }
168
169     if !is_crossed {
170         cmd.arg("--system-libs");
171     }
172     cmd.args(&components[..]);
173
174     for lib in output(&mut cmd).split_whitespace() {
175         let name = if lib.starts_with("-l") {
176             &lib[2..]
177         } else if lib.starts_with("-") {
178             &lib[1..]
179         } else if Path::new(lib).exists() {
180             // On MSVC llvm-config will print the full name to libraries, but
181             // we're only interested in the name part
182             let name = Path::new(lib).file_name().unwrap().to_str().unwrap();
183             name.trim_right_matches(".lib")
184         } else if lib.ends_with(".lib") {
185             // Some MSVC libraries just come up with `.lib` tacked on, so chop
186             // that off
187             lib.trim_right_matches(".lib")
188         } else {
189             continue;
190         };
191
192         // Don't need or want this library, but LLVM's CMake build system
193         // doesn't provide a way to disable it, so filter it here even though we
194         // may or may not have built it. We don't reference anything from this
195         // library and it otherwise may just pull in extra dependencies on
196         // libedit which we don't want
197         if name == "LLVMLineEditor" {
198             continue;
199         }
200
201         let kind = if name.starts_with("LLVM") {
202             llvm_kind
203         } else {
204             "dylib"
205         };
206         println!("cargo:rustc-link-lib={}={}", kind, name);
207     }
208
209     // LLVM ldflags
210     //
211     // If we're a cross-compile of LLVM then unfortunately we can't trust these
212     // ldflags (largely where all the LLVM libs are located). Currently just
213     // hack around this by replacing the host triple with the target and pray
214     // that those -L directories are the same!
215     let mut cmd = Command::new(&llvm_config);
216     cmd.arg("--ldflags");
217     for lib in output(&mut cmd).split_whitespace() {
218         if lib.starts_with("-LIBPATH:") {
219             println!("cargo:rustc-link-search=native={}", &lib[9..]);
220         } else if is_crossed {
221             if lib.starts_with("-L") {
222                 println!("cargo:rustc-link-search=native={}",
223                          lib[2..].replace(&host, &target));
224             }
225         } else if lib.starts_with("-l") {
226             println!("cargo:rustc-link-lib={}", &lib[2..]);
227         } else if lib.starts_with("-L") {
228             println!("cargo:rustc-link-search=native={}", &lib[2..]);
229         }
230     }
231
232     // OpenBSD has a particular C++ runtime library name
233     let stdcppname = if target.contains("openbsd") {
234         "estdc++"
235     } else {
236         "stdc++"
237     };
238
239     // C++ runtime library
240     if !target.contains("msvc") {
241         if let Some(s) = env::var_os("LLVM_STATIC_STDCPP") {
242             assert!(!cxxflags.contains("stdlib=libc++"));
243             let path = PathBuf::from(s);
244             println!("cargo:rustc-link-search=native={}",
245                      path.parent().unwrap().display());
246             println!("cargo:rustc-link-lib=static={}", stdcppname);
247         } else if cxxflags.contains("stdlib=libc++") {
248             println!("cargo:rustc-link-lib=c++");
249         } else {
250             println!("cargo:rustc-link-lib={}", stdcppname);
251         }
252     }
253 }