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