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