diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index 04be7956e8278..a411905f7d2e7 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -1226,7 +1226,7 @@ fn start_executing_work( // Note that using `jobserver::Proxy` is not necessary here, the code below always acquires // tokens before releasing them, so we can never accidentally release the last token // permanently held by rustc process. - let parallel = match sess.opts.jobs.backend { + let parallel = match sess.opts.jobs.backend.parallel_thread_count() { Some(n) if backend.supports_parallel() => Some(n), _ => None, }; diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index f9dfd04faf2ac..b4e03236dcd85 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -820,32 +820,33 @@ pub fn codegen_crate< // This likely is a temporary measure. Once we don't have to support the // non-parallel compiler anymore, we can compile CGUs end-to-end in // parallel and get rid of the complicated scheduling logic. - let mut pre_compiled_cgus = if let Some(threads) = tcx.sess.opts.jobs.frontend { - tcx.sess.time("compile_first_CGU_batch", || { - // Try to find one CGU to compile per thread. - let cgus: Vec<_> = cgu_reuse - .iter() - .enumerate() - .filter(|&(_, reuse)| reuse == &CguReuse::No) - .take(threads.get()) - .collect(); - - // Compile the found CGUs in parallel. - let start_time = Instant::now(); - - let pre_compiled_cgus = par_map(cgus, |(i, _)| { - let module = - backend.compile_codegen_unit(tcx, codegen_units[i].name(), bitcode_needed); - (i, IntoDynSyncSend(module)) - }); + let mut pre_compiled_cgus = + if let Some(threads) = tcx.sess.opts.jobs.frontend.parallel_thread_count() { + tcx.sess.time("compile_first_CGU_batch", || { + // Try to find one CGU to compile per thread. + let cgus: Vec<_> = cgu_reuse + .iter() + .enumerate() + .filter(|&(_, reuse)| reuse == &CguReuse::No) + .take(threads.get()) + .collect(); + + // Compile the found CGUs in parallel. + let start_time = Instant::now(); + + let pre_compiled_cgus = par_map(cgus, |(i, _)| { + let module = + backend.compile_codegen_unit(tcx, codegen_units[i].name(), bitcode_needed); + (i, IntoDynSyncSend(module)) + }); - total_codegen_time += start_time.elapsed(); + total_codegen_time += start_time.elapsed(); - pre_compiled_cgus - }) - } else { - FxHashMap::default() - }; + pre_compiled_cgus + }) + } else { + FxHashMap::default() + }; for (i, cgu) in codegen_units.iter().enumerate() { ongoing_codegen.wait_for_signal_to_codegen_item(); diff --git a/compiler/rustc_interface/src/interface.rs b/compiler/rustc_interface/src/interface.rs index 7a6a49f37278a..dda0cebca1d5a 100644 --- a/compiler/rustc_interface/src/interface.rs +++ b/compiler/rustc_interface/src/interface.rs @@ -380,12 +380,19 @@ pub fn run_compiler(config: Config, f: impl FnOnce(&Compiler) -> R + Se trace!("run_compiler"); // Set parallel mode before thread pool creation, which will create `Lock`s. - rustc_data_structures::sync::set_dyn_thread_safe_mode(config.opts.jobs.frontend.is_some()); + rustc_data_structures::sync::set_dyn_thread_safe_mode( + config.opts.jobs.frontend.is_synchronized(), + ); // Initialize jobserver as early as possible. let early_dcx = EarlyDiagCtxt::new(config.opts.error_format); let jobs = config.opts.jobs; - if let Some(limit) = jobs.frontend.max(jobs.backend).max(jobs.linker.limit()) { + if let Some(limit) = jobs + .frontend + .parallel_thread_count() + .max(jobs.backend.parallel_thread_count()) + .max(jobs.linker.limit()) + { jobserver::initialize(limit.get(), |err| { let note = "the build environment is likely misconfigured"; early_dcx.early_struct_warn(err).with_note(note).emit() diff --git a/compiler/rustc_interface/src/util.rs b/compiler/rustc_interface/src/util.rs index d58b7bfddfc6d..3c1c6026f7e76 100644 --- a/compiler/rustc_interface/src/util.rs +++ b/compiler/rustc_interface/src/util.rs @@ -227,7 +227,8 @@ pub(crate) fn run_in_thread_pool_with_globals R + Send, let thread_stack_size = init_stack_size(thread_builder_diag); - let jobs_frontend = jobs.frontend.or(NonZero::new(1)).unwrap(); + let jobs_frontend = + jobs.frontend.parallel_thread_count().unwrap_or_else(|| NonZero::new(1).unwrap()); let registry = sync::Registry::new(jobs_frontend); let Some(proof) = sync::check_dyn_thread_safe() else { diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 03493d0e1b6a9..40a744591b6bb 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -2579,7 +2579,7 @@ pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path, ref_path: Option<&Path>) { return; }; - if tcx.sess.opts.jobs.frontend.is_some() { + if tcx.sess.opts.jobs.frontend.is_synchronized() { // Prefetch some queries used by metadata encoding. // This is not necessary for correctness, but is only done for performance reasons. // It can be removed if it turns out to cause trouble or be detrimental to performance. diff --git a/compiler/rustc_middle/src/dep_graph/graph.rs b/compiler/rustc_middle/src/dep_graph/graph.rs index dcb5775f20595..004652f4a05f3 100644 --- a/compiler/rustc_middle/src/dep_graph/graph.rs +++ b/compiler/rustc_middle/src/dep_graph/graph.rs @@ -676,7 +676,7 @@ impl DepGraphData { let ok = match color { DepNodeColor::Unknown => true, DepNodeColor::Red => false, - DepNodeColor::Green(..) => sess.opts.jobs.frontend.is_some(), // Other threads may mark this green + DepNodeColor::Green(..) => sess.opts.jobs.frontend.is_synchronized(), // Other threads may mark this green }; if !ok { panic!("{}", msg()) diff --git a/compiler/rustc_query_impl/src/execution.rs b/compiler/rustc_query_impl/src/execution.rs index ca60614ba97db..af0eff4500d34 100644 --- a/compiler/rustc_query_impl/src/execution.rs +++ b/compiler/rustc_query_impl/src/execution.rs @@ -292,7 +292,7 @@ fn try_execute_query<'tcx, C: QueryCache, const INCR: bool>( // re-executing the query since `try_start` only checks that the query is not currently // executing, but another thread may have already completed the query and stores it result // in the query cache. - if tcx.sess.opts.jobs.frontend.is_some() { + if tcx.sess.opts.jobs.frontend.is_synchronized() { if let Some((value, index)) = query.cache.lookup(&key) { tcx.prof.query_cache_hit(index.into()); return (value, Some(index)); diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 64cfdfd5f85a7..7881cbe19196a 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -1518,7 +1518,11 @@ impl Default for Options { verbose: false, target_modifiers: BTreeMap::default(), mitigation_coverage_map: Default::default(), - jobs: Jobs { frontend: None, backend: None, linker: LinkerJobs::Default }, + jobs: Jobs { + frontend: FrontendJobs::sequential(), + backend: BackendJobs::sequential(), + linker: LinkerJobs::Default, + }, recommended_stack_size: DEFAULT_STACK_SIZE, } } @@ -1709,12 +1713,62 @@ impl LinkerJobs { } } -/// `None` for frontend and backend means everything is single-threaded -/// and synchronization can be disabled. +/// When the value is `None`, the frontend will be executed on a single thread, without using +/// parallel synchronization (i.e. locks) unnecessarily. +/// +/// When the value is `Some`, the frontend will be executed potentially on multiple threads, +/// using parallel synchronization. +/// If the number of threads is 1, the synchronization will still be applied, but it will be +/// pure overhead (this can be used e.g. to measure the basis of that overhead). +/// This case with one thread corresponds to `--jobs-frontend=sync`. +#[derive(Clone, Copy)] +pub struct FrontendJobs(Option>); + +impl FrontendJobs { + /// Run with one frontend thread, without synchronization. + fn sequential() -> Self { + Self(None) + } + + /// Should the frontend use synchronization primitives? + pub fn is_synchronized(&self) -> bool { + self.0.is_some() + } + + /// Return the number of threads that we are using for the parallel frontend. + /// Returns `None` if synchronization is not required. + pub fn parallel_thread_count(&self) -> Option> { + self.0 + } +} + +/// When the value is `None`, the backend will be executed on a single thread, without spinning +/// up unnecessary coordination/jobserver threads. +/// +/// When the value is `Some`, the backend will be executed potentially on multiple threads, with +/// jobserver synchronization. +#[derive(Clone, Copy)] +pub struct BackendJobs(Option>); + +impl BackendJobs { + /// Run with one backend thread, without synchronization. + fn sequential() -> Self { + Self(None) + } + + /// Return the number of threads that we are using for the backend. + /// Returns `None` if synchronization is not required. + pub fn parallel_thread_count(&self) -> Option> { + self.0 + } +} + +/// Setting `Sequential` for frontend and backend and `Default` for linker backend +/// means everything is single-threaded and the jobserver doesn't have to be initialized. #[derive(Clone, Copy)] pub struct Jobs { - pub frontend: Option>, - pub backend: Option>, + pub frontend: FrontendJobs, + pub backend: BackendJobs, pub linker: LinkerJobs, } @@ -1748,7 +1802,7 @@ fn parse_jobs_all( if zthreads.is_some() { early_dcx.early_fatal("cannot use both `--jobs-frontend` and `-Zthreads`"); } - frontend + FrontendJobs(frontend) } None => match zthreads { Some(zthreads) => { @@ -1756,9 +1810,9 @@ fn parse_jobs_all( let frontend = parse_jobs_one(early_dcx, opt_name, zthreads, unstable, &mut available); check_upper_limit(frontend, opt_name); - frontend + FrontendJobs(frontend) } - None => None, // default to 1 thread irrespectively of `jobs` for now + None => FrontendJobs::sequential(), // default to 1 thread irrespectively of `jobs` for now }, }; let backend = match matches.opt_str("jobs-backend") { @@ -1767,13 +1821,13 @@ fn parse_jobs_all( let backend = parse_jobs_one(early_dcx, opt_name, &jobs_backend, unstable, &mut available); check_upper_limit(backend, opt_name); - backend + BackendJobs(backend) } - None => match jobs { + None => BackendJobs(match jobs { Some(n) => n, // Use all available parallelism as the default. None => parse_jobs_one(early_dcx, "", "0", unstable, &mut available), - }, + }), }; let linker = match matches.opt_str("jobs-linker") { Some(jobs_linker) => {