]>
Commit | Line | Data |
---|---|---|
74b04a01 XL |
1 | use rustc_ast::mut_visit::{visit_clobber, MutVisitor, *}; |
2 | use rustc_ast::ptr::P; | |
3dfed10e | 3 | use rustc_ast::{self as ast, AttrVec, BlockCheckMode}; |
ba9703b0 | 4 | use rustc_codegen_ssa::traits::CodegenBackend; |
dfeec247 XL |
5 | use rustc_data_structures::fingerprint::Fingerprint; |
6 | use rustc_data_structures::fx::{FxHashMap, FxHashSet}; | |
532ac7d7 XL |
7 | #[cfg(parallel_compiler)] |
8 | use rustc_data_structures::jobserver; | |
532ac7d7 | 9 | use rustc_data_structures::stable_hasher::StableHasher; |
3dfed10e | 10 | use rustc_data_structures::sync::Lrc; |
532ac7d7 | 11 | use rustc_errors::registry::Registry; |
532ac7d7 | 12 | use rustc_metadata::dynamic_lib::DynamicLibrary; |
6a06907d XL |
13 | #[cfg(parallel_compiler)] |
14 | use rustc_middle::ty::tls; | |
60c5eb7d | 15 | use rustc_resolve::{self, Resolver}; |
dfeec247 | 16 | use rustc_session as session; |
f9f354fc | 17 | use rustc_session::config::{self, CrateType}; |
dfeec247 | 18 | use rustc_session::config::{ErrorOutputType, Input, OutputFilenames}; |
ba9703b0 | 19 | use rustc_session::lint::{self, BuiltinLintDiagnostics, LintBuffer}; |
74b04a01 | 20 | use rustc_session::parse::CrateConfig; |
dfeec247 | 21 | use rustc_session::CrateDisambiguator; |
f9f354fc | 22 | use rustc_session::{early_error, filesearch, output, DiagnosticOutput, Session}; |
dfeec247 | 23 | use rustc_span::edition::Edition; |
fc512014 | 24 | use rustc_span::lev_distance::find_best_match_for_name; |
f9f354fc | 25 | use rustc_span::source_map::FileLoader; |
dfeec247 XL |
26 | use rustc_span::symbol::{sym, Symbol}; |
27 | use smallvec::SmallVec; | |
532ac7d7 | 28 | use std::env; |
29967ef6 | 29 | use std::env::consts::{DLL_PREFIX, DLL_SUFFIX}; |
fc512014 | 30 | use std::io; |
1b1a35ee | 31 | use std::lazy::SyncOnceCell; |
532ac7d7 | 32 | use std::mem; |
dfeec247 | 33 | use std::ops::DerefMut; |
6a06907d XL |
34 | #[cfg(not(parallel_compiler))] |
35 | use std::panic; | |
532ac7d7 | 36 | use std::path::{Path, PathBuf}; |
29967ef6 | 37 | use std::sync::atomic::{AtomicBool, Ordering}; |
532ac7d7 | 38 | use std::sync::{Arc, Mutex, Once}; |
6a06907d | 39 | use std::thread; |
3dfed10e | 40 | use tracing::info; |
532ac7d7 | 41 | |
532ac7d7 XL |
42 | /// Adds `target_feature = "..."` cfgs for a variety of platform |
43 | /// specific features (SSE, NEON etc.). | |
44 | /// | |
f035d41b XL |
45 | /// This is performed by checking whether a set of permitted features |
46 | /// is available on the target machine, by querying LLVM. | |
532ac7d7 | 47 | pub fn add_configuration( |
74b04a01 | 48 | cfg: &mut CrateConfig, |
f9f354fc | 49 | sess: &mut Session, |
532ac7d7 XL |
50 | codegen_backend: &dyn CodegenBackend, |
51 | ) { | |
dc9dc135 | 52 | let tf = sym::target_feature; |
532ac7d7 | 53 | |
f9f354fc XL |
54 | let target_features = codegen_backend.target_features(sess); |
55 | sess.target_features.extend(target_features.iter().cloned()); | |
56 | ||
57 | cfg.extend(target_features.into_iter().map(|feat| (tf, Some(feat)))); | |
532ac7d7 | 58 | |
f9f354fc | 59 | if sess.crt_static(None) { |
3dfed10e | 60 | cfg.insert((tf, Some(sym::crt_dash_static))); |
532ac7d7 XL |
61 | } |
62 | } | |
63 | ||
64 | pub fn create_session( | |
65 | sopts: config::Options, | |
66 | cfg: FxHashSet<(String, Option<String>)>, | |
67 | diagnostic_output: DiagnosticOutput, | |
68 | file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>, | |
69 | input_path: Option<PathBuf>, | |
70 | lint_caps: FxHashMap<lint::LintId, lint::Level>, | |
1b1a35ee XL |
71 | make_codegen_backend: Option< |
72 | Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>, | |
73 | >, | |
60c5eb7d | 74 | descriptions: Registry, |
f9f354fc | 75 | ) -> (Lrc<Session>, Lrc<Box<dyn CodegenBackend>>) { |
1b1a35ee XL |
76 | let codegen_backend = if let Some(make_codegen_backend) = make_codegen_backend { |
77 | make_codegen_backend(&sopts) | |
78 | } else { | |
79 | get_codegen_backend(&sopts) | |
80 | }; | |
81 | ||
82 | // target_override is documented to be called before init(), so this is okay | |
83 | let target_override = codegen_backend.target_override(&sopts); | |
84 | ||
f9f354fc | 85 | let mut sess = session::build_session( |
532ac7d7 XL |
86 | sopts, |
87 | input_path, | |
88 | descriptions, | |
532ac7d7 XL |
89 | diagnostic_output, |
90 | lint_caps, | |
ba9703b0 | 91 | file_loader, |
1b1a35ee | 92 | target_override, |
532ac7d7 XL |
93 | ); |
94 | ||
1b1a35ee | 95 | codegen_backend.init(&sess); |
532ac7d7 | 96 | |
532ac7d7 | 97 | let mut cfg = config::build_configuration(&sess, config::to_crate_config(cfg)); |
f9f354fc | 98 | add_configuration(&mut cfg, &mut sess, &*codegen_backend); |
532ac7d7 XL |
99 | sess.parse_sess.config = cfg; |
100 | ||
f9f354fc | 101 | (Lrc::new(sess), Lrc::new(codegen_backend)) |
532ac7d7 XL |
102 | } |
103 | ||
f9f354fc | 104 | const STACK_SIZE: usize = 8 * 1024 * 1024; |
532ac7d7 XL |
105 | |
106 | fn get_stack_size() -> Option<usize> { | |
107 | // FIXME: Hacks on hacks. If the env is trying to override the stack size | |
108 | // then *don't* set it explicitly. | |
60c5eb7d | 109 | env::var_os("RUST_MIN_STACK").is_none().then_some(STACK_SIZE) |
532ac7d7 XL |
110 | } |
111 | ||
f035d41b XL |
112 | /// Like a `thread::Builder::spawn` followed by a `join()`, but avoids the need |
113 | /// for `'static` bounds. | |
532ac7d7 XL |
114 | #[cfg(not(parallel_compiler))] |
115 | pub fn scoped_thread<F: FnOnce() -> R + Send, R: Send>(cfg: thread::Builder, f: F) -> R { | |
116 | struct Ptr(*mut ()); | |
117 | unsafe impl Send for Ptr {} | |
118 | unsafe impl Sync for Ptr {} | |
119 | ||
120 | let mut f = Some(f); | |
121 | let run = Ptr(&mut f as *mut _ as *mut ()); | |
122 | let mut result = None; | |
123 | let result_ptr = Ptr(&mut result as *mut _ as *mut ()); | |
124 | ||
125 | let thread = cfg.spawn(move || { | |
126 | let run = unsafe { (*(run.0 as *mut Option<F>)).take().unwrap() }; | |
127 | let result = unsafe { &mut *(result_ptr.0 as *mut Option<R>) }; | |
128 | *result = Some(run()); | |
129 | }); | |
130 | ||
131 | match thread.unwrap().join() { | |
132 | Ok(()) => result.unwrap(), | |
133 | Err(p) => panic::resume_unwind(p), | |
134 | } | |
135 | } | |
136 | ||
137 | #[cfg(not(parallel_compiler))] | |
f035d41b | 138 | pub fn setup_callbacks_and_run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>( |
dc9dc135 | 139 | edition: Edition, |
e74abb32 | 140 | _threads: usize, |
532ac7d7 XL |
141 | stderr: &Option<Arc<Mutex<Vec<u8>>>>, |
142 | f: F, | |
143 | ) -> R { | |
144 | let mut cfg = thread::Builder::new().name("rustc".to_string()); | |
145 | ||
146 | if let Some(size) = get_stack_size() { | |
147 | cfg = cfg.stack_size(size); | |
148 | } | |
149 | ||
dfeec247 XL |
150 | crate::callbacks::setup_callbacks(); |
151 | ||
f035d41b | 152 | let main_handler = move || { |
3dfed10e | 153 | rustc_span::with_session_globals(edition, || { |
fc512014 | 154 | io::set_output_capture(stderr.clone()); |
3dfed10e | 155 | f() |
532ac7d7 | 156 | }) |
f035d41b XL |
157 | }; |
158 | ||
159 | scoped_thread(cfg, main_handler) | |
532ac7d7 XL |
160 | } |
161 | ||
6a06907d XL |
162 | /// Creates a new thread and forwards information in thread locals to it. |
163 | /// The new thread runs the deadlock handler. | |
164 | /// Must only be called when a deadlock is about to happen. | |
165 | #[cfg(parallel_compiler)] | |
166 | unsafe fn handle_deadlock() { | |
167 | let registry = rustc_rayon_core::Registry::current(); | |
168 | ||
169 | let context = tls::get_tlv(); | |
170 | assert!(context != 0); | |
171 | rustc_data_structures::sync::assert_sync::<tls::ImplicitCtxt<'_, '_>>(); | |
172 | let icx: &tls::ImplicitCtxt<'_, '_> = &*(context as *const tls::ImplicitCtxt<'_, '_>); | |
173 | ||
174 | let session_globals = rustc_span::SESSION_GLOBALS.with(|sg| sg as *const _); | |
175 | let session_globals = &*session_globals; | |
176 | thread::spawn(move || { | |
177 | tls::enter_context(icx, |_| { | |
178 | rustc_span::SESSION_GLOBALS | |
179 | .set(session_globals, || tls::with(|tcx| tcx.queries.deadlock(tcx, ®istry))) | |
180 | }); | |
181 | }); | |
182 | } | |
183 | ||
532ac7d7 | 184 | #[cfg(parallel_compiler)] |
f035d41b | 185 | pub fn setup_callbacks_and_run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>( |
dc9dc135 | 186 | edition: Edition, |
e74abb32 | 187 | threads: usize, |
532ac7d7 XL |
188 | stderr: &Option<Arc<Mutex<Vec<u8>>>>, |
189 | f: F, | |
190 | ) -> R { | |
dfeec247 | 191 | crate::callbacks::setup_callbacks(); |
532ac7d7 | 192 | |
f035d41b | 193 | let mut config = rayon::ThreadPoolBuilder::new() |
e74abb32 | 194 | .thread_name(|_| "rustc".to_string()) |
532ac7d7 XL |
195 | .acquire_thread_handler(jobserver::acquire_thread) |
196 | .release_thread_handler(jobserver::release_thread) | |
e74abb32 | 197 | .num_threads(threads) |
6a06907d | 198 | .deadlock_handler(|| unsafe { handle_deadlock() }); |
532ac7d7 XL |
199 | |
200 | if let Some(size) = get_stack_size() { | |
201 | config = config.stack_size(size); | |
202 | } | |
203 | ||
29967ef6 | 204 | let with_pool = move |pool: &rayon::ThreadPool| pool.install(f); |
f035d41b | 205 | |
3dfed10e XL |
206 | rustc_span::with_session_globals(edition, || { |
207 | rustc_span::SESSION_GLOBALS.with(|session_globals| { | |
208 | // The main handler runs for each Rayon worker thread and sets up | |
209 | // the thread local rustc uses. `session_globals` is captured and set | |
210 | // on the new threads. | |
211 | let main_handler = move |thread: rayon::ThreadBuilder| { | |
212 | rustc_span::SESSION_GLOBALS.set(session_globals, || { | |
fc512014 | 213 | io::set_output_capture(stderr.clone()); |
3dfed10e XL |
214 | thread.run() |
215 | }) | |
216 | }; | |
217 | ||
218 | config.build_scoped(main_handler, with_pool).unwrap() | |
532ac7d7 XL |
219 | }) |
220 | }) | |
221 | } | |
222 | ||
223 | fn load_backend_from_dylib(path: &Path) -> fn() -> Box<dyn CodegenBackend> { | |
f9f354fc | 224 | let lib = DynamicLibrary::open(path).unwrap_or_else(|err| { |
532ac7d7 XL |
225 | let err = format!("couldn't load codegen backend {:?}: {:?}", path, err); |
226 | early_error(ErrorOutputType::default(), &err); | |
227 | }); | |
228 | unsafe { | |
229 | match lib.symbol("__rustc_codegen_backend") { | |
230 | Ok(f) => { | |
231 | mem::forget(lib); | |
232 | mem::transmute::<*mut u8, _>(f) | |
233 | } | |
234 | Err(e) => { | |
dfeec247 XL |
235 | let err = format!( |
236 | "couldn't load codegen backend as it \ | |
532ac7d7 | 237 | doesn't export the `__rustc_codegen_backend` \ |
dfeec247 XL |
238 | symbol: {:?}", |
239 | e | |
240 | ); | |
532ac7d7 XL |
241 | early_error(ErrorOutputType::default(), &err); |
242 | } | |
243 | } | |
244 | } | |
245 | } | |
246 | ||
1b1a35ee | 247 | pub fn get_codegen_backend(sopts: &config::Options) -> Box<dyn CodegenBackend> { |
532ac7d7 XL |
248 | static INIT: Once = Once::new(); |
249 | ||
250 | static mut LOAD: fn() -> Box<dyn CodegenBackend> = || unreachable!(); | |
251 | ||
252 | INIT.call_once(|| { | |
29967ef6 XL |
253 | #[cfg(feature = "llvm")] |
254 | const DEFAULT_CODEGEN_BACKEND: &str = "llvm"; | |
255 | ||
256 | #[cfg(not(feature = "llvm"))] | |
257 | const DEFAULT_CODEGEN_BACKEND: &str = "cranelift"; | |
258 | ||
259 | let codegen_name = sopts | |
260 | .debugging_opts | |
261 | .codegen_backend | |
262 | .as_ref() | |
263 | .map(|name| &name[..]) | |
264 | .unwrap_or(DEFAULT_CODEGEN_BACKEND); | |
265 | ||
3dfed10e | 266 | let backend = match codegen_name { |
74b04a01 | 267 | filename if filename.contains('.') => load_backend_from_dylib(filename.as_ref()), |
60c5eb7d | 268 | codegen_name => get_builtin_codegen_backend(codegen_name), |
532ac7d7 XL |
269 | }; |
270 | ||
271 | unsafe { | |
272 | LOAD = backend; | |
273 | } | |
274 | }); | |
1b1a35ee | 275 | unsafe { LOAD() } |
532ac7d7 XL |
276 | } |
277 | ||
e1599b0c XL |
278 | // This is used for rustdoc, but it uses similar machinery to codegen backend |
279 | // loading, so we leave the code here. It is potentially useful for other tools | |
280 | // that want to invoke the rustc binary while linking to rustc as well. | |
281 | pub fn rustc_path<'a>() -> Option<&'a Path> { | |
1b1a35ee | 282 | static RUSTC_PATH: SyncOnceCell<Option<PathBuf>> = SyncOnceCell::new(); |
e1599b0c XL |
283 | |
284 | const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR"); | |
532ac7d7 | 285 | |
e1599b0c XL |
286 | RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v) |
287 | } | |
288 | ||
289 | fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> { | |
f9f354fc XL |
290 | sysroot_candidates().iter().find_map(|sysroot| { |
291 | let candidate = sysroot.join(bin_path).join(if cfg!(target_os = "windows") { | |
292 | "rustc.exe" | |
293 | } else { | |
294 | "rustc" | |
295 | }); | |
296 | candidate.exists().then_some(candidate) | |
297 | }) | |
e1599b0c XL |
298 | } |
299 | ||
300 | fn sysroot_candidates() -> Vec<PathBuf> { | |
532ac7d7 XL |
301 | let target = session::config::host_triple(); |
302 | let mut sysroot_candidates = vec![filesearch::get_or_default_sysroot()]; | |
e1599b0c | 303 | let path = current_dll_path().and_then(|s| s.canonicalize().ok()); |
532ac7d7 XL |
304 | if let Some(dll) = path { |
305 | // use `parent` twice to chop off the file name and then also the | |
306 | // directory containing the dll which should be either `lib` or `bin`. | |
307 | if let Some(path) = dll.parent().and_then(|p| p.parent()) { | |
308 | // The original `path` pointed at the `rustc_driver` crate's dll. | |
309 | // Now that dll should only be in one of two locations. The first is | |
310 | // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The | |
311 | // other is the target's libdir, for example | |
312 | // `$sysroot/lib/rustlib/$target/lib/*.dll`. | |
313 | // | |
314 | // We don't know which, so let's assume that if our `path` above | |
315 | // ends in `$target` we *could* be in the target libdir, and always | |
316 | // assume that we may be in the main libdir. | |
317 | sysroot_candidates.push(path.to_owned()); | |
318 | ||
319 | if path.ends_with(target) { | |
dfeec247 XL |
320 | sysroot_candidates.extend( |
321 | path.parent() // chop off `$target` | |
322 | .and_then(|p| p.parent()) // chop off `rustlib` | |
323 | .and_then(|p| p.parent()) // chop off `lib` | |
324 | .map(|s| s.to_owned()), | |
325 | ); | |
532ac7d7 XL |
326 | } |
327 | } | |
328 | } | |
329 | ||
e1599b0c | 330 | return sysroot_candidates; |
532ac7d7 XL |
331 | |
332 | #[cfg(unix)] | |
333 | fn current_dll_path() -> Option<PathBuf> { | |
dfeec247 | 334 | use std::ffi::{CStr, OsStr}; |
532ac7d7 XL |
335 | use std::os::unix::prelude::*; |
336 | ||
337 | unsafe { | |
338 | let addr = current_dll_path as usize as *mut _; | |
339 | let mut info = mem::zeroed(); | |
340 | if libc::dladdr(addr, &mut info) == 0 { | |
341 | info!("dladdr failed"); | |
dfeec247 | 342 | return None; |
532ac7d7 XL |
343 | } |
344 | if info.dli_fname.is_null() { | |
345 | info!("dladdr returned null pointer"); | |
dfeec247 | 346 | return None; |
532ac7d7 XL |
347 | } |
348 | let bytes = CStr::from_ptr(info.dli_fname).to_bytes(); | |
349 | let os = OsStr::from_bytes(bytes); | |
350 | Some(PathBuf::from(os)) | |
351 | } | |
352 | } | |
353 | ||
354 | #[cfg(windows)] | |
355 | fn current_dll_path() -> Option<PathBuf> { | |
356 | use std::ffi::OsString; | |
357 | use std::os::windows::prelude::*; | |
dfeec247 | 358 | use std::ptr; |
532ac7d7 | 359 | |
dfeec247 XL |
360 | use winapi::um::libloaderapi::{ |
361 | GetModuleFileNameW, GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, | |
362 | }; | |
532ac7d7 XL |
363 | |
364 | unsafe { | |
dfeec247 XL |
365 | let mut module = ptr::null_mut(); |
366 | let r = GetModuleHandleExW( | |
367 | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, | |
368 | current_dll_path as usize as *mut _, | |
369 | &mut module, | |
370 | ); | |
532ac7d7 XL |
371 | if r == 0 { |
372 | info!("GetModuleHandleExW failed: {}", io::Error::last_os_error()); | |
dfeec247 | 373 | return None; |
532ac7d7 XL |
374 | } |
375 | let mut space = Vec::with_capacity(1024); | |
dfeec247 | 376 | let r = GetModuleFileNameW(module, space.as_mut_ptr(), space.capacity() as u32); |
532ac7d7 XL |
377 | if r == 0 { |
378 | info!("GetModuleFileNameW failed: {}", io::Error::last_os_error()); | |
dfeec247 | 379 | return None; |
532ac7d7 XL |
380 | } |
381 | let r = r as usize; | |
382 | if r >= space.capacity() { | |
dfeec247 XL |
383 | info!("our buffer was too small? {}", io::Error::last_os_error()); |
384 | return None; | |
532ac7d7 XL |
385 | } |
386 | space.set_len(r); | |
387 | let os = OsString::from_wide(&space); | |
388 | Some(PathBuf::from(os)) | |
389 | } | |
390 | } | |
391 | } | |
392 | ||
60c5eb7d | 393 | pub fn get_builtin_codegen_backend(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> { |
29967ef6 XL |
394 | match backend_name { |
395 | #[cfg(feature = "llvm")] | |
396 | "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new, | |
397 | _ => get_codegen_sysroot(backend_name), | |
398 | } | |
399 | } | |
400 | ||
401 | pub fn get_codegen_sysroot(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> { | |
402 | // For now we only allow this function to be called once as it'll dlopen a | |
403 | // few things, which seems to work best if we only do that once. In | |
404 | // general this assertion never trips due to the once guard in `get_codegen_backend`, | |
405 | // but there's a few manual calls to this function in this file we protect | |
406 | // against. | |
407 | static LOADED: AtomicBool = AtomicBool::new(false); | |
408 | assert!( | |
409 | !LOADED.fetch_or(true, Ordering::SeqCst), | |
410 | "cannot load the default codegen backend twice" | |
411 | ); | |
412 | ||
413 | let target = session::config::host_triple(); | |
414 | let sysroot_candidates = sysroot_candidates(); | |
415 | ||
416 | let sysroot = sysroot_candidates | |
417 | .iter() | |
418 | .map(|sysroot| { | |
419 | let libdir = filesearch::relative_target_lib_path(&sysroot, &target); | |
420 | sysroot.join(libdir).with_file_name("codegen-backends") | |
421 | }) | |
422 | .find(|f| { | |
423 | info!("codegen backend candidate: {}", f.display()); | |
424 | f.exists() | |
425 | }); | |
426 | let sysroot = sysroot.unwrap_or_else(|| { | |
427 | let candidates = sysroot_candidates | |
428 | .iter() | |
429 | .map(|p| p.display().to_string()) | |
430 | .collect::<Vec<_>>() | |
431 | .join("\n* "); | |
432 | let err = format!( | |
433 | "failed to find a `codegen-backends` folder \ | |
434 | in the sysroot candidates:\n* {}", | |
435 | candidates | |
436 | ); | |
437 | early_error(ErrorOutputType::default(), &err); | |
438 | }); | |
439 | info!("probing {} for a codegen backend", sysroot.display()); | |
440 | ||
441 | let d = sysroot.read_dir().unwrap_or_else(|e| { | |
442 | let err = format!( | |
443 | "failed to load default codegen backend, couldn't \ | |
444 | read `{}`: {}", | |
445 | sysroot.display(), | |
446 | e | |
447 | ); | |
448 | early_error(ErrorOutputType::default(), &err); | |
449 | }); | |
450 | ||
451 | let mut file: Option<PathBuf> = None; | |
452 | ||
453 | let expected_name = | |
454 | format!("rustc_codegen_{}-{}", backend_name, release_str().expect("CFG_RELEASE")); | |
455 | for entry in d.filter_map(|e| e.ok()) { | |
456 | let path = entry.path(); | |
457 | let filename = match path.file_name().and_then(|s| s.to_str()) { | |
458 | Some(s) => s, | |
459 | None => continue, | |
460 | }; | |
461 | if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) { | |
462 | continue; | |
463 | } | |
464 | let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()]; | |
465 | if name != expected_name { | |
466 | continue; | |
e1599b0c | 467 | } |
29967ef6 XL |
468 | if let Some(ref prev) = file { |
469 | let err = format!( | |
470 | "duplicate codegen backends found\n\ | |
471 | first: {}\n\ | |
472 | second: {}\n\ | |
473 | ", | |
474 | prev.display(), | |
475 | path.display() | |
476 | ); | |
477 | early_error(ErrorOutputType::default(), &err); | |
478 | } | |
479 | file = Some(path.clone()); | |
e1599b0c XL |
480 | } |
481 | ||
29967ef6 XL |
482 | match file { |
483 | Some(ref s) => load_backend_from_dylib(s), | |
484 | None => { | |
485 | let err = format!("unsupported builtin codegen backend `{}`", backend_name); | |
486 | early_error(ErrorOutputType::default(), &err); | |
487 | } | |
488 | } | |
e1599b0c XL |
489 | } |
490 | ||
532ac7d7 XL |
491 | pub(crate) fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator { |
492 | use std::hash::Hasher; | |
493 | ||
494 | // The crate_disambiguator is a 128 bit hash. The disambiguator is fed | |
495 | // into various other hashes quite a bit (symbol hashes, incr. comp. hashes, | |
496 | // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits | |
497 | // should still be safe enough to avoid collisions in practice. | |
e74abb32 | 498 | let mut hasher = StableHasher::new(); |
532ac7d7 XL |
499 | |
500 | let mut metadata = session.opts.cg.metadata.clone(); | |
501 | // We don't want the crate_disambiguator to dependent on the order | |
502 | // -C metadata arguments, so sort them: | |
503 | metadata.sort(); | |
504 | // Every distinct -C metadata value is only incorporated once: | |
505 | metadata.dedup(); | |
506 | ||
507 | hasher.write(b"metadata"); | |
508 | for s in &metadata { | |
509 | // Also incorporate the length of a metadata string, so that we generate | |
510 | // different values for `-Cmetadata=ab -Cmetadata=c` and | |
511 | // `-Cmetadata=a -Cmetadata=bc` | |
512 | hasher.write_usize(s.len()); | |
513 | hasher.write(s.as_bytes()); | |
514 | } | |
515 | ||
516 | // Also incorporate crate type, so that we don't get symbol conflicts when | |
517 | // linking against a library of the same name, if this is an executable. | |
f9f354fc | 518 | let is_exe = session.crate_types().contains(&CrateType::Executable); |
532ac7d7 XL |
519 | hasher.write(if is_exe { b"exe" } else { b"lib" }); |
520 | ||
e74abb32 XL |
521 | CrateDisambiguator::from(hasher.finish::<Fingerprint>()) |
522 | } | |
523 | ||
3dfed10e XL |
524 | pub(crate) fn check_attr_crate_type( |
525 | sess: &Session, | |
526 | attrs: &[ast::Attribute], | |
527 | lint_buffer: &mut LintBuffer, | |
528 | ) { | |
e74abb32 XL |
529 | // Unconditionally collect crate types from attributes to make them used |
530 | for a in attrs.iter() { | |
3dfed10e | 531 | if sess.check_name(a, sym::crate_type) { |
e74abb32 | 532 | if let Some(n) = a.value_str() { |
74b04a01 | 533 | if categorize_crate_type(n).is_some() { |
e74abb32 XL |
534 | return; |
535 | } | |
536 | ||
537 | if let ast::MetaItemKind::NameValue(spanned) = a.meta().unwrap().kind { | |
538 | let span = spanned.span; | |
fc512014 XL |
539 | let lev_candidate = find_best_match_for_name( |
540 | &CRATE_TYPES.iter().map(|(k, _)| *k).collect::<Vec<_>>(), | |
541 | n, | |
542 | None, | |
543 | ); | |
e74abb32 XL |
544 | if let Some(candidate) = lev_candidate { |
545 | lint_buffer.buffer_lint_with_diagnostic( | |
546 | lint::builtin::UNKNOWN_CRATE_TYPES, | |
547 | ast::CRATE_NODE_ID, | |
548 | span, | |
549 | "invalid `crate_type` value", | |
dfeec247 XL |
550 | BuiltinLintDiagnostics::UnknownCrateTypes( |
551 | span, | |
552 | "did you mean".to_string(), | |
553 | format!("\"{}\"", candidate), | |
554 | ), | |
e74abb32 XL |
555 | ); |
556 | } else { | |
557 | lint_buffer.buffer_lint( | |
558 | lint::builtin::UNKNOWN_CRATE_TYPES, | |
559 | ast::CRATE_NODE_ID, | |
560 | span, | |
dfeec247 | 561 | "invalid `crate_type` value", |
e74abb32 XL |
562 | ); |
563 | } | |
564 | } | |
565 | } | |
566 | } | |
567 | } | |
568 | } | |
569 | ||
f9f354fc XL |
570 | const CRATE_TYPES: &[(Symbol, CrateType)] = &[ |
571 | (sym::rlib, CrateType::Rlib), | |
572 | (sym::dylib, CrateType::Dylib), | |
573 | (sym::cdylib, CrateType::Cdylib), | |
e74abb32 | 574 | (sym::lib, config::default_lib_output()), |
f9f354fc XL |
575 | (sym::staticlib, CrateType::Staticlib), |
576 | (sym::proc_dash_macro, CrateType::ProcMacro), | |
577 | (sym::bin, CrateType::Executable), | |
e74abb32 XL |
578 | ]; |
579 | ||
f9f354fc | 580 | fn categorize_crate_type(s: Symbol) -> Option<CrateType> { |
e74abb32 | 581 | Some(CRATE_TYPES.iter().find(|(key, _)| *key == s)?.1) |
532ac7d7 XL |
582 | } |
583 | ||
f9f354fc | 584 | pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<CrateType> { |
532ac7d7 | 585 | // Unconditionally collect crate types from attributes to make them used |
f9f354fc | 586 | let attr_types: Vec<CrateType> = attrs |
532ac7d7 XL |
587 | .iter() |
588 | .filter_map(|a| { | |
3dfed10e | 589 | if session.check_name(a, sym::crate_type) { |
532ac7d7 | 590 | match a.value_str() { |
e74abb32 XL |
591 | Some(s) => categorize_crate_type(s), |
592 | _ => None, | |
532ac7d7 XL |
593 | } |
594 | } else { | |
595 | None | |
596 | } | |
597 | }) | |
598 | .collect(); | |
599 | ||
600 | // If we're generating a test executable, then ignore all other output | |
601 | // styles at all other locations | |
602 | if session.opts.test { | |
f9f354fc | 603 | return vec![CrateType::Executable]; |
532ac7d7 XL |
604 | } |
605 | ||
606 | // Only check command line flags if present. If no types are specified by | |
607 | // command line, then reuse the empty `base` Vec to hold the types that | |
608 | // will be found in crate attributes. | |
609 | let mut base = session.opts.crate_types.clone(); | |
610 | if base.is_empty() { | |
611 | base.extend(attr_types); | |
612 | if base.is_empty() { | |
ba9703b0 | 613 | base.push(output::default_output_for_target(session)); |
532ac7d7 XL |
614 | } else { |
615 | base.sort(); | |
616 | base.dedup(); | |
617 | } | |
618 | } | |
619 | ||
620 | base.retain(|crate_type| { | |
ba9703b0 | 621 | let res = !output::invalid_output_for_target(session, *crate_type); |
532ac7d7 XL |
622 | |
623 | if !res { | |
624 | session.warn(&format!( | |
625 | "dropping unsupported crate type `{}` for target `{}`", | |
626 | *crate_type, session.opts.target_triple | |
627 | )); | |
628 | } | |
629 | ||
630 | res | |
631 | }); | |
632 | ||
633 | base | |
634 | } | |
635 | ||
636 | pub fn build_output_filenames( | |
637 | input: &Input, | |
638 | odir: &Option<PathBuf>, | |
639 | ofile: &Option<PathBuf>, | |
640 | attrs: &[ast::Attribute], | |
641 | sess: &Session, | |
642 | ) -> OutputFilenames { | |
643 | match *ofile { | |
644 | None => { | |
645 | // "-" as input file will cause the parser to read from stdin so we | |
646 | // have to make up a name | |
647 | // We want to toss everything after the final '.' | |
648 | let dirpath = (*odir).as_ref().cloned().unwrap_or_default(); | |
649 | ||
650 | // If a crate name is present, we use it as the link name | |
dfeec247 XL |
651 | let stem = sess |
652 | .opts | |
532ac7d7 XL |
653 | .crate_name |
654 | .clone() | |
3dfed10e | 655 | .or_else(|| rustc_attr::find_crate_name(&sess, attrs).map(|n| n.to_string())) |
532ac7d7 XL |
656 | .unwrap_or_else(|| input.filestem().to_owned()); |
657 | ||
dfeec247 XL |
658 | OutputFilenames::new( |
659 | dirpath, | |
660 | stem, | |
661 | None, | |
662 | sess.opts.cg.extra_filename.clone(), | |
663 | sess.opts.output_types.clone(), | |
664 | ) | |
532ac7d7 XL |
665 | } |
666 | ||
667 | Some(ref out_file) => { | |
dfeec247 XL |
668 | let unnamed_output_types = |
669 | sess.opts.output_types.values().filter(|a| a.is_none()).count(); | |
532ac7d7 XL |
670 | let ofile = if unnamed_output_types > 1 { |
671 | sess.warn( | |
672 | "due to multiple output types requested, the explicitly specified \ | |
673 | output file name will be adapted for each output type", | |
674 | ); | |
675 | None | |
676 | } else { | |
416331ca XL |
677 | if !sess.opts.cg.extra_filename.is_empty() { |
678 | sess.warn("ignoring -C extra-filename flag due to -o flag"); | |
679 | } | |
532ac7d7 XL |
680 | Some(out_file.clone()) |
681 | }; | |
682 | if *odir != None { | |
683 | sess.warn("ignoring --out-dir flag due to -o flag"); | |
684 | } | |
532ac7d7 | 685 | |
dfeec247 XL |
686 | OutputFilenames::new( |
687 | out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(), | |
688 | out_file.file_stem().unwrap_or_default().to_str().unwrap().to_string(), | |
689 | ofile, | |
690 | sess.opts.cg.extra_filename.clone(), | |
691 | sess.opts.output_types.clone(), | |
692 | ) | |
532ac7d7 XL |
693 | } |
694 | } | |
695 | } | |
696 | ||
6a06907d XL |
697 | #[cfg(not(target_os = "linux"))] |
698 | pub fn non_durable_rename(src: &Path, dst: &Path) -> std::io::Result<()> { | |
699 | std::fs::rename(src, dst) | |
700 | } | |
701 | ||
702 | /// This function attempts to bypass the auto_da_alloc heuristic implemented by some filesystems | |
703 | /// such as btrfs and ext4. When renaming over a file that already exists then they will "helpfully" | |
704 | /// write back the source file before committing the rename in case a developer forgot some of | |
705 | /// the fsyncs in the open/write/fsync(file)/rename/fsync(dir) dance for atomic file updates. | |
706 | /// | |
707 | /// To avoid triggering this heuristic we delete the destination first, if it exists. | |
708 | /// The cost of an extra syscall is much lower than getting descheduled for the sync IO. | |
709 | #[cfg(target_os = "linux")] | |
710 | pub fn non_durable_rename(src: &Path, dst: &Path) -> std::io::Result<()> { | |
711 | let _ = std::fs::remove_file(dst); | |
712 | std::fs::rename(src, dst) | |
713 | } | |
714 | ||
715 | /// Replaces function bodies with `loop {}` (an infinite loop). This gets rid of | |
716 | /// all semantic errors in the body while still satisfying the return type, | |
717 | /// except in certain cases, see below for more. | |
718 | /// | |
719 | /// This pass is known as `everybody_loops`. Very punny. | |
720 | /// | |
721 | /// As of March 2021, `everybody_loops` is only used for the | |
722 | /// `-Z unpretty=everybody_loops` debugging option. | |
723 | /// | |
724 | /// FIXME: Currently the `everybody_loops` transformation is not applied to: | |
725 | /// * `const fn`; support could be added, but hasn't. Originally `const fn` | |
726 | /// was skipped due to issue #43636 that `loop` was not supported for | |
727 | /// const evaluation. | |
728 | /// * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging. | |
729 | /// Solving this may require `!` to implement every trait, which relies on the an even more | |
730 | /// ambitious form of the closed RFC #1637. See also [#34511]. | |
731 | /// | |
732 | /// [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401 | |
60c5eb7d | 733 | pub struct ReplaceBodyWithLoop<'a, 'b> { |
532ac7d7 XL |
734 | within_static_or_const: bool, |
735 | nested_blocks: Option<Vec<ast::Block>>, | |
60c5eb7d | 736 | resolver: &'a mut Resolver<'b>, |
532ac7d7 XL |
737 | } |
738 | ||
60c5eb7d XL |
739 | impl<'a, 'b> ReplaceBodyWithLoop<'a, 'b> { |
740 | pub fn new(resolver: &'a mut Resolver<'b>) -> ReplaceBodyWithLoop<'a, 'b> { | |
dfeec247 | 741 | ReplaceBodyWithLoop { within_static_or_const: false, nested_blocks: None, resolver } |
532ac7d7 XL |
742 | } |
743 | ||
744 | fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R { | |
745 | let old_const = mem::replace(&mut self.within_static_or_const, is_const); | |
746 | let old_blocks = self.nested_blocks.take(); | |
747 | let ret = action(self); | |
748 | self.within_static_or_const = old_const; | |
749 | self.nested_blocks = old_blocks; | |
750 | ret | |
751 | } | |
752 | ||
74b04a01 XL |
753 | fn should_ignore_fn(ret_ty: &ast::FnRetTy) -> bool { |
754 | if let ast::FnRetTy::Ty(ref ty) = ret_ty { | |
532ac7d7 | 755 | fn involves_impl_trait(ty: &ast::Ty) -> bool { |
e74abb32 | 756 | match ty.kind { |
532ac7d7 | 757 | ast::TyKind::ImplTrait(..) => true, |
dfeec247 XL |
758 | ast::TyKind::Slice(ref subty) |
759 | | ast::TyKind::Array(ref subty, _) | |
760 | | ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. }) | |
761 | | ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. }) | |
762 | | ast::TyKind::Paren(ref subty) => involves_impl_trait(subty), | |
532ac7d7 | 763 | ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()), |
f9f354fc XL |
764 | ast::TyKind::Path(_, ref path) => { |
765 | path.segments.iter().any(|seg| match seg.args.as_deref() { | |
532ac7d7 XL |
766 | None => false, |
767 | Some(&ast::GenericArgs::AngleBracketed(ref data)) => { | |
ba9703b0 XL |
768 | data.args.iter().any(|arg| match arg { |
769 | ast::AngleBracketedArg::Arg(arg) => match arg { | |
770 | ast::GenericArg::Type(ty) => involves_impl_trait(ty), | |
771 | ast::GenericArg::Lifetime(_) | |
772 | | ast::GenericArg::Const(_) => false, | |
773 | }, | |
774 | ast::AngleBracketedArg::Constraint(c) => match c.kind { | |
dc9dc135 | 775 | ast::AssocTyConstraintKind::Bound { .. } => true, |
dfeec247 XL |
776 | ast::AssocTyConstraintKind::Equality { ref ty } => { |
777 | involves_impl_trait(ty) | |
778 | } | |
ba9703b0 XL |
779 | }, |
780 | }) | |
dfeec247 | 781 | } |
532ac7d7 | 782 | Some(&ast::GenericArgs::Parenthesized(ref data)) => { |
dfeec247 XL |
783 | any_involves_impl_trait(data.inputs.iter()) |
784 | || ReplaceBodyWithLoop::should_ignore_fn(&data.output) | |
532ac7d7 | 785 | } |
f9f354fc XL |
786 | }) |
787 | } | |
532ac7d7 XL |
788 | _ => false, |
789 | } | |
790 | } | |
791 | ||
792 | fn any_involves_impl_trait<'a, I: Iterator<Item = &'a P<ast::Ty>>>(mut it: I) -> bool { | |
793 | it.any(|subty| involves_impl_trait(subty)) | |
794 | } | |
795 | ||
796 | involves_impl_trait(ty) | |
797 | } else { | |
798 | false | |
799 | } | |
800 | } | |
60c5eb7d XL |
801 | |
802 | fn is_sig_const(sig: &ast::FnSig) -> bool { | |
74b04a01 | 803 | matches!(sig.header.constness, ast::Const::Yes(_)) |
dfeec247 | 804 | || ReplaceBodyWithLoop::should_ignore_fn(&sig.decl.output) |
60c5eb7d | 805 | } |
532ac7d7 XL |
806 | } |
807 | ||
60c5eb7d | 808 | impl<'a> MutVisitor for ReplaceBodyWithLoop<'a, '_> { |
532ac7d7 XL |
809 | fn visit_item_kind(&mut self, i: &mut ast::ItemKind) { |
810 | let is_const = match i { | |
811 | ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true, | |
5869c6ff | 812 | ast::ItemKind::Fn(box ast::FnKind(_, ref sig, _, _)) => Self::is_sig_const(sig), |
532ac7d7 XL |
813 | _ => false, |
814 | }; | |
815 | self.run(is_const, |s| noop_visit_item_kind(i, s)) | |
816 | } | |
817 | ||
74b04a01 | 818 | fn flat_map_trait_item(&mut self, i: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> { |
e74abb32 | 819 | let is_const = match i.kind { |
dfeec247 | 820 | ast::AssocItemKind::Const(..) => true, |
5869c6ff | 821 | ast::AssocItemKind::Fn(box ast::FnKind(_, ref sig, _, _)) => Self::is_sig_const(sig), |
532ac7d7 XL |
822 | _ => false, |
823 | }; | |
dfeec247 | 824 | self.run(is_const, |s| noop_flat_map_assoc_item(i, s)) |
532ac7d7 XL |
825 | } |
826 | ||
74b04a01 | 827 | fn flat_map_impl_item(&mut self, i: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> { |
dfeec247 | 828 | self.flat_map_trait_item(i) |
532ac7d7 XL |
829 | } |
830 | ||
831 | fn visit_anon_const(&mut self, c: &mut ast::AnonConst) { | |
832 | self.run(true, |s| noop_visit_anon_const(c, s)) | |
833 | } | |
834 | ||
835 | fn visit_block(&mut self, b: &mut P<ast::Block>) { | |
dfeec247 XL |
836 | fn stmt_to_block( |
837 | rules: ast::BlockCheckMode, | |
838 | s: Option<ast::Stmt>, | |
839 | resolver: &mut Resolver<'_>, | |
840 | ) -> ast::Block { | |
532ac7d7 XL |
841 | ast::Block { |
842 | stmts: s.into_iter().collect(), | |
843 | rules, | |
60c5eb7d | 844 | id: resolver.next_node_id(), |
dfeec247 | 845 | span: rustc_span::DUMMY_SP, |
1b1a35ee | 846 | tokens: None, |
532ac7d7 XL |
847 | } |
848 | } | |
849 | ||
60c5eb7d | 850 | fn block_to_stmt(b: ast::Block, resolver: &mut Resolver<'_>) -> ast::Stmt { |
532ac7d7 | 851 | let expr = P(ast::Expr { |
60c5eb7d | 852 | id: resolver.next_node_id(), |
e74abb32 | 853 | kind: ast::ExprKind::Block(P(b), None), |
dfeec247 XL |
854 | span: rustc_span::DUMMY_SP, |
855 | attrs: AttrVec::new(), | |
f9f354fc | 856 | tokens: None, |
532ac7d7 XL |
857 | }); |
858 | ||
859 | ast::Stmt { | |
60c5eb7d | 860 | id: resolver.next_node_id(), |
e74abb32 | 861 | kind: ast::StmtKind::Expr(expr), |
dfeec247 | 862 | span: rustc_span::DUMMY_SP, |
532ac7d7 XL |
863 | } |
864 | } | |
865 | ||
60c5eb7d | 866 | let empty_block = stmt_to_block(BlockCheckMode::Default, None, self.resolver); |
532ac7d7 | 867 | let loop_expr = P(ast::Expr { |
e74abb32 | 868 | kind: ast::ExprKind::Loop(P(empty_block), None), |
60c5eb7d | 869 | id: self.resolver.next_node_id(), |
dfeec247 XL |
870 | span: rustc_span::DUMMY_SP, |
871 | attrs: AttrVec::new(), | |
f9f354fc | 872 | tokens: None, |
532ac7d7 XL |
873 | }); |
874 | ||
875 | let loop_stmt = ast::Stmt { | |
60c5eb7d | 876 | id: self.resolver.next_node_id(), |
dfeec247 | 877 | span: rustc_span::DUMMY_SP, |
e74abb32 | 878 | kind: ast::StmtKind::Expr(loop_expr), |
532ac7d7 XL |
879 | }; |
880 | ||
881 | if self.within_static_or_const { | |
882 | noop_visit_block(b, self) | |
883 | } else { | |
884 | visit_clobber(b.deref_mut(), |b| { | |
885 | let mut stmts = vec![]; | |
886 | for s in b.stmts { | |
887 | let old_blocks = self.nested_blocks.replace(vec![]); | |
888 | ||
889 | stmts.extend(self.flat_map_stmt(s).into_iter().filter(|s| s.is_item())); | |
890 | ||
891 | // we put a Some in there earlier with that replace(), so this is valid | |
892 | let new_blocks = self.nested_blocks.take().unwrap(); | |
893 | self.nested_blocks = old_blocks; | |
60c5eb7d | 894 | stmts.extend(new_blocks.into_iter().map(|b| block_to_stmt(b, self.resolver))); |
532ac7d7 XL |
895 | } |
896 | ||
dfeec247 | 897 | let mut new_block = ast::Block { stmts, ..b }; |
532ac7d7 XL |
898 | |
899 | if let Some(old_blocks) = self.nested_blocks.as_mut() { | |
900 | //push our fresh block onto the cache and yield an empty block with `loop {}` | |
901 | if !new_block.stmts.is_empty() { | |
902 | old_blocks.push(new_block); | |
903 | } | |
904 | ||
60c5eb7d | 905 | stmt_to_block(b.rules, Some(loop_stmt), &mut self.resolver) |
532ac7d7 XL |
906 | } else { |
907 | //push `loop {}` onto the end of our fresh block and yield that | |
908 | new_block.stmts.push(loop_stmt); | |
909 | ||
910 | new_block | |
911 | } | |
912 | }) | |
913 | } | |
914 | } | |
29967ef6 | 915 | } |
532ac7d7 | 916 | |
29967ef6 XL |
917 | /// Returns a version string such as "rustc 1.46.0 (04488afe3 2020-08-24)" |
918 | pub fn version_str() -> Option<&'static str> { | |
919 | option_env!("CFG_VERSION") | |
920 | } | |
921 | ||
922 | /// Returns a version string such as "0.12.0-dev". | |
923 | pub fn release_str() -> Option<&'static str> { | |
924 | option_env!("CFG_RELEASE") | |
925 | } | |
926 | ||
927 | /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built. | |
928 | pub fn commit_hash_str() -> Option<&'static str> { | |
929 | option_env!("CFG_VER_HASH") | |
930 | } | |
931 | ||
932 | /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string. | |
933 | pub fn commit_date_str() -> Option<&'static str> { | |
934 | option_env!("CFG_VER_DATE") | |
532ac7d7 | 935 | } |