Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_ssa/src/back/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1226,7 +1226,7 @@ fn start_executing_work<B: WriteBackendMethods>(
// 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,
};
Expand Down
49 changes: 25 additions & 24 deletions compiler/rustc_codegen_ssa/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
11 changes: 9 additions & 2 deletions compiler/rustc_interface/src/interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -380,12 +380,19 @@ pub fn run_compiler<R: Send>(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()
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_interface/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,8 @@ pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce(CurrentGcx) -> 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 {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_metadata/src/rmeta/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/dep_graph/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_query_impl/src/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
76 changes: 65 additions & 11 deletions compiler/rustc_session/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}
Expand Down Expand Up @@ -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<NonZero<usize>>);

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<NonZero<usize>> {

@petrochenkov petrochenkov Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So much boilerplate and we still convert the "newtypes" back to an option in most places.
This is exactly what I wanted to avoid originally.

View changes since the review

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The actual representation is an Option<NonZero<usize>>, but I think that there is benefit to wrapping it, so that we make it easier to understand how exactly it behaves.

What about a compromise:

struct FrontendJobs(Option<NonZero<usize>>);

This allows us to document the behavior + add methods to the type to reduce confusion of how it behaves, vs just using is_none().

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<NonZero<usize>>);

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<NonZero<usize>> {
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<NonZero<usize>>,
pub backend: Option<NonZero<usize>>,
pub frontend: FrontendJobs,
pub backend: BackendJobs,
pub linker: LinkerJobs,
}

Expand Down Expand Up @@ -1748,17 +1802,17 @@ 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) => {
let opt_name = "-Zthreads";
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") {
Expand All @@ -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) => {
Expand Down
Loading