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