1 use super::link::{self, ensure_removed};
2 use super::lto::{self, SerializedModule};
3 use super::symbol_export::symbol_name_for_instance_in_crate;
8 CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
10 use jobserver::{Acquired, Client};
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_data_structures::memmap::Mmap;
13 use rustc_data_structures::profiling::SelfProfilerRef;
14 use rustc_data_structures::profiling::TimingGuard;
15 use rustc_data_structures::profiling::VerboseTimingGuard;
16 use rustc_data_structures::sync::Lrc;
17 use rustc_errors::emitter::Emitter;
19 translation::{to_fluent_args, Translate},
20 DiagnosticId, FatalError, Handler, Level,
22 use rustc_fs_util::link_or_copy;
23 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
24 use rustc_incremental::{
25 copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
27 use rustc_metadata::EncodedMetadata;
28 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
29 use rustc_middle::middle::exported_symbols::SymbolExportInfo;
30 use rustc_middle::ty::TyCtxt;
31 use rustc_session::cgu_reuse_tracker::CguReuseTracker;
32 use rustc_session::config::{self, CrateType, Lto, OutputFilenames, OutputType};
33 use rustc_session::config::{Passes, SwitchWithOptPath};
34 use rustc_session::Session;
35 use rustc_span::source_map::SourceMap;
36 use rustc_span::symbol::sym;
37 use rustc_span::{BytePos, FileName, InnerSpan, Pos, Span};
38 use rustc_target::spec::{MergeFunctions, SanitizerSet};
43 use std::marker::PhantomData;
45 use std::path::{Path, PathBuf};
47 use std::sync::mpsc::{channel, Receiver, Sender};
51 const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
53 /// What kind of object file to emit.
54 #[derive(Clone, Copy, PartialEq)]
59 // Just uncompressed llvm bitcode. Provides easy compatibility with
60 // emscripten's ecc compiler, when used as the linker.
63 // Object code, possibly augmented with a bitcode section.
64 ObjectCode(BitcodeSection),
67 /// What kind of llvm bitcode section to embed in an object file.
68 #[derive(Clone, Copy, PartialEq)]
69 pub enum BitcodeSection {
70 // No bitcode section.
73 // A full, uncompressed bitcode section.
77 /// Module-specific configuration for `optimize_and_codegen`.
78 pub struct ModuleConfig {
79 /// Names of additional optimization passes to run.
80 pub passes: Vec<String>,
81 /// Some(level) to optimize at a certain level, or None to run
82 /// absolutely no optimizations (used for the metadata module).
83 pub opt_level: Option<config::OptLevel>,
85 /// Some(level) to optimize binary size, or None to not affect program size.
86 pub opt_size: Option<config::OptLevel>,
88 pub pgo_gen: SwitchWithOptPath,
89 pub pgo_use: Option<PathBuf>,
90 pub pgo_sample_use: Option<PathBuf>,
91 pub debug_info_for_profiling: bool,
92 pub instrument_coverage: bool,
93 pub instrument_gcov: bool,
95 pub sanitizer: SanitizerSet,
96 pub sanitizer_recover: SanitizerSet,
97 pub sanitizer_memory_track_origins: usize,
99 // Flags indicating which outputs to produce.
100 pub emit_pre_lto_bc: bool,
101 pub emit_no_opt_bc: bool,
105 pub emit_obj: EmitObj,
106 pub emit_thin_lto: bool,
107 pub bc_cmdline: String,
109 // Miscellaneous flags. These are mostly copied from command-line
111 pub verify_llvm_ir: bool,
112 pub no_prepopulate_passes: bool,
113 pub no_builtins: bool,
114 pub time_module: bool,
115 pub vectorize_loop: bool,
116 pub vectorize_slp: bool,
117 pub merge_functions: bool,
118 pub inline_threshold: Option<u32>,
119 pub emit_lifetime_markers: bool,
120 pub llvm_plugins: Vec<String>,
128 is_compiler_builtins: bool,
130 // If it's a regular module, use `$regular`, otherwise use `$other`.
131 // `$regular` and `$other` are evaluated lazily.
132 macro_rules! if_regular {
133 ($regular: expr, $other: expr) => {
134 if let ModuleKind::Regular = kind { $regular } else { $other }
138 let opt_level_and_size = if_regular!(Some(sess.opts.optimize), None);
140 let save_temps = sess.opts.cg.save_temps;
142 let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
144 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
145 ModuleKind::Allocator => false,
146 ModuleKind::Metadata => sess.opts.output_types.contains_key(&OutputType::Metadata),
149 let emit_obj = if !should_emit_obj {
151 } else if sess.target.obj_is_bitcode
152 || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
154 // This case is selected if the target uses objects as bitcode, or
155 // if linker plugin LTO is enabled. In the linker plugin LTO case
156 // the assumption is that the final link-step will read the bitcode
157 // and convert it to object code. This may be done by either the
158 // native linker or rustc itself.
160 // Note, however, that the linker-plugin-lto requested here is
161 // explicitly ignored for `#![no_builtins]` crates. These crates are
162 // specifically ignored by rustc's LTO passes and wouldn't work if
163 // loaded into the linker. These crates define symbols that LLVM
164 // lowers intrinsics to, and these symbol dependencies aren't known
165 // until after codegen. As a result any crate marked
166 // `#![no_builtins]` is assumed to not participate in LTO and
167 // instead goes on to generate object code.
169 } else if need_bitcode_in_object(sess) {
170 EmitObj::ObjectCode(BitcodeSection::Full)
172 EmitObj::ObjectCode(BitcodeSection::None)
176 passes: if_regular!(sess.opts.cg.passes.clone(), vec![]),
178 opt_level: opt_level_and_size,
179 opt_size: opt_level_and_size,
181 pgo_gen: if_regular!(
182 sess.opts.cg.profile_generate.clone(),
183 SwitchWithOptPath::Disabled
185 pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
186 pgo_sample_use: if_regular!(sess.opts.unstable_opts.profile_sample_use.clone(), None),
187 debug_info_for_profiling: sess.opts.unstable_opts.debug_info_for_profiling,
188 instrument_coverage: if_regular!(sess.instrument_coverage(), false),
189 instrument_gcov: if_regular!(
190 // compiler_builtins overrides the codegen-units settings,
191 // which is incompatible with -Zprofile which requires that
192 // only a single codegen unit is used per crate.
193 sess.opts.unstable_opts.profile && !is_compiler_builtins,
197 sanitizer: if_regular!(sess.opts.unstable_opts.sanitizer, SanitizerSet::empty()),
198 sanitizer_recover: if_regular!(
199 sess.opts.unstable_opts.sanitizer_recover,
200 SanitizerSet::empty()
202 sanitizer_memory_track_origins: if_regular!(
203 sess.opts.unstable_opts.sanitizer_memory_track_origins,
207 emit_pre_lto_bc: if_regular!(
208 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
211 emit_no_opt_bc: if_regular!(save_temps, false),
212 emit_bc: if_regular!(
213 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
216 emit_ir: if_regular!(
217 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
220 emit_asm: if_regular!(
221 sess.opts.output_types.contains_key(&OutputType::Assembly),
225 emit_thin_lto: sess.opts.unstable_opts.emit_thin_lto,
226 bc_cmdline: sess.target.bitcode_llvm_cmdline.to_string(),
228 verify_llvm_ir: sess.verify_llvm_ir(),
229 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
230 no_builtins: no_builtins || sess.target.no_builtins,
232 // Exclude metadata and allocator modules from time_passes output,
233 // since they throw off the "LLVM passes" measurement.
234 time_module: if_regular!(true, false),
236 // Copy what clang does by turning on loop vectorization at O2 and
237 // slp vectorization at O3.
238 vectorize_loop: !sess.opts.cg.no_vectorize_loops
239 && (sess.opts.optimize == config::OptLevel::Default
240 || sess.opts.optimize == config::OptLevel::Aggressive),
241 vectorize_slp: !sess.opts.cg.no_vectorize_slp
242 && sess.opts.optimize == config::OptLevel::Aggressive,
244 // Some targets (namely, NVPTX) interact badly with the
245 // MergeFunctions pass. This is because MergeFunctions can generate
246 // new function calls which may interfere with the target calling
247 // convention; e.g. for the NVPTX target, PTX kernels should not
248 // call other PTX kernels. MergeFunctions can also be configured to
249 // generate aliases instead, but aliases are not supported by some
250 // backends (again, NVPTX). Therefore, allow targets to opt out of
251 // the MergeFunctions pass, but otherwise keep the pass enabled (at
252 // O2 and O3) since it can be useful for reducing code size.
253 merge_functions: match sess
257 .unwrap_or(sess.target.merge_functions)
259 MergeFunctions::Disabled => false,
260 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
261 use config::OptLevel::*;
262 match sess.opts.optimize {
263 Aggressive | Default | SizeMin | Size => true,
269 inline_threshold: sess.opts.cg.inline_threshold,
270 emit_lifetime_markers: sess.emit_lifetime_markers(),
271 llvm_plugins: if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
275 pub fn bitcode_needed(&self) -> bool {
277 || self.emit_obj == EmitObj::Bitcode
278 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
282 /// Configuration passed to the function returned by the `target_machine_factory`.
283 pub struct TargetMachineFactoryConfig {
284 /// Split DWARF is enabled in LLVM by checking that `TM.MCOptions.SplitDwarfFile` isn't empty,
285 /// so the path to the dwarf object has to be provided when we create the target machine.
286 /// This can be ignored by backends which do not need it for their Split DWARF support.
287 pub split_dwarf_file: Option<PathBuf>,
290 impl TargetMachineFactoryConfig {
292 cgcx: &CodegenContext<impl WriteBackendMethods>,
294 ) -> TargetMachineFactoryConfig {
295 let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
296 cgcx.output_filenames.split_dwarf_path(
297 cgcx.split_debuginfo,
298 cgcx.split_dwarf_kind,
304 TargetMachineFactoryConfig { split_dwarf_file }
308 pub type TargetMachineFactoryFn<B> = Arc<
309 dyn Fn(TargetMachineFactoryConfig) -> Result<<B as WriteBackendMethods>::TargetMachine, String>
314 pub type ExportedSymbols = FxHashMap<CrateNum, Arc<Vec<(String, SymbolExportInfo)>>>;
316 /// Additional resources used by optimize_and_codegen (not module specific)
318 pub struct CodegenContext<B: WriteBackendMethods> {
319 // Resources needed when running LTO
321 pub prof: SelfProfilerRef,
323 pub save_temps: bool,
324 pub fewer_names: bool,
325 pub time_trace: bool,
326 pub exported_symbols: Option<Arc<ExportedSymbols>>,
327 pub opts: Arc<config::Options>,
328 pub crate_types: Vec<CrateType>,
329 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
330 pub output_filenames: Arc<OutputFilenames>,
331 pub regular_module_config: Arc<ModuleConfig>,
332 pub metadata_module_config: Arc<ModuleConfig>,
333 pub allocator_module_config: Arc<ModuleConfig>,
334 pub tm_factory: TargetMachineFactoryFn<B>,
335 pub msvc_imps_needed: bool,
336 pub is_pe_coff: bool,
337 pub target_can_use_split_dwarf: bool,
338 pub target_pointer_width: u32,
339 pub target_arch: String,
340 pub debuginfo: config::DebugInfo,
341 pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
342 pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
344 // Number of cgus excluding the allocator/metadata modules
345 pub total_cgus: usize,
346 // Handler to use for diagnostics produced during codegen.
347 pub diag_emitter: SharedEmitter,
348 // LLVM optimizations for which we want to print remarks.
350 // Worker thread number
352 // The incremental compilation session directory, or None if we are not
353 // compiling incrementally
354 pub incr_comp_session_dir: Option<PathBuf>,
355 // Used to update CGU re-use information during the thinlto phase.
356 pub cgu_reuse_tracker: CguReuseTracker,
357 // Channel back to the main control thread to send messages to
358 pub coordinator_send: Sender<Box<dyn Any + Send>>,
361 impl<B: WriteBackendMethods> CodegenContext<B> {
362 pub fn create_diag_handler(&self) -> Handler {
363 Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
366 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
368 ModuleKind::Regular => &self.regular_module_config,
369 ModuleKind::Metadata => &self.metadata_module_config,
370 ModuleKind::Allocator => &self.allocator_module_config,
375 fn generate_lto_work<B: ExtraBackendMethods>(
376 cgcx: &CodegenContext<B>,
377 needs_fat_lto: Vec<FatLTOInput<B>>,
378 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
379 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
380 ) -> Vec<(WorkItem<B>, u64)> {
381 let _prof_timer = cgcx.prof.generic_activity("codegen_generate_lto_work");
383 let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
384 assert!(needs_thin_lto.is_empty());
386 B::run_fat_lto(cgcx, needs_fat_lto, import_only_modules).unwrap_or_else(|e| e.raise());
387 (vec![lto_module], vec![])
389 assert!(needs_fat_lto.is_empty());
390 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules).unwrap_or_else(|e| e.raise())
396 let cost = module.cost();
397 (WorkItem::LTO(module), cost)
399 .chain(copy_jobs.into_iter().map(|wp| {
401 WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
402 name: wp.cgu_name.clone(),
411 pub struct CompiledModules {
412 pub modules: Vec<CompiledModule>,
413 pub allocator_module: Option<CompiledModule>,
416 fn need_bitcode_in_object(sess: &Session) -> bool {
417 let requested_for_rlib = sess.opts.cg.embed_bitcode
418 && sess.crate_types().contains(&CrateType::Rlib)
419 && sess.opts.output_types.contains_key(&OutputType::Exe);
420 let forced_by_target = sess.target.forces_embed_bitcode;
421 requested_for_rlib || forced_by_target
424 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
425 if sess.opts.incremental.is_none() {
431 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
435 pub fn start_async_codegen<B: ExtraBackendMethods>(
439 metadata: EncodedMetadata,
440 metadata_module: Option<CompiledModule>,
442 ) -> OngoingCodegen<B> {
443 let (coordinator_send, coordinator_receive) = channel();
446 let crate_attrs = tcx.hir().attrs(rustc_hir::CRATE_HIR_ID);
447 let no_builtins = tcx.sess.contains_name(crate_attrs, sym::no_builtins);
448 let is_compiler_builtins = tcx.sess.contains_name(crate_attrs, sym::compiler_builtins);
450 let crate_info = CrateInfo::new(tcx, target_cpu);
453 ModuleConfig::new(ModuleKind::Regular, sess, no_builtins, is_compiler_builtins);
454 let metadata_config =
455 ModuleConfig::new(ModuleKind::Metadata, sess, no_builtins, is_compiler_builtins);
456 let allocator_config =
457 ModuleConfig::new(ModuleKind::Allocator, sess, no_builtins, is_compiler_builtins);
459 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
460 let (codegen_worker_send, codegen_worker_receive) = channel();
462 let coordinator_thread = start_executing_work(
470 sess.jobserver.clone(),
471 Arc::new(regular_config),
472 Arc::new(metadata_config),
473 Arc::new(allocator_config),
474 coordinator_send.clone(),
483 codegen_worker_receive,
485 coordinator: Coordinator {
486 sender: coordinator_send,
487 future: Some(coordinator_thread),
488 phantom: PhantomData,
490 output_filenames: tcx.output_filenames(()).clone(),
494 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
496 compiled_modules: &CompiledModules,
497 ) -> FxHashMap<WorkProductId, WorkProduct> {
498 let mut work_products = FxHashMap::default();
500 if sess.opts.incremental.is_none() {
501 return work_products;
504 let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
506 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
507 let mut files = Vec::new();
508 if let Some(object_file_path) = &module.object {
509 files.push(("o", object_file_path.as_path()));
511 if let Some(dwarf_object_file_path) = &module.dwarf_object {
512 files.push(("dwo", dwarf_object_file_path.as_path()));
515 if let Some((id, product)) =
516 copy_cgu_workproduct_to_incr_comp_cache_dir(sess, &module.name, files.as_slice())
518 work_products.insert(id, product);
525 fn produce_final_output_artifacts(
527 compiled_modules: &CompiledModules,
528 crate_output: &OutputFilenames,
530 let mut user_wants_bitcode = false;
531 let mut user_wants_objects = false;
533 // Produce final compile outputs.
534 let copy_gracefully = |from: &Path, to: &Path| {
535 if let Err(e) = fs::copy(from, to) {
536 sess.emit_err(errors::CopyPath::new(from, to, e));
540 let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
541 if compiled_modules.modules.len() == 1 {
542 // 1) Only one codegen unit. In this case it's no difficulty
543 // to copy `foo.0.x` to `foo.x`.
544 let module_name = Some(&compiled_modules.modules[0].name[..]);
545 let path = crate_output.temp_path(output_type, module_name);
546 copy_gracefully(&path, &crate_output.path(output_type));
547 if !sess.opts.cg.save_temps && !keep_numbered {
548 // The user just wants `foo.x`, not `foo.#module-name#.x`.
549 ensure_removed(sess.diagnostic(), &path);
552 let extension = crate_output
553 .temp_path(output_type, None)
560 if crate_output.outputs.contains_key(&output_type) {
561 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
562 // no good solution for this case, so warn the user.
563 sess.emit_warning(errors::IgnoringEmitPath { extension });
564 } else if crate_output.single_output_file.is_some() {
565 // 3) Multiple codegen units, with `-o some_name`. We have
566 // no good solution for this case, so warn the user.
567 sess.emit_warning(errors::IgnoringOutput { extension });
569 // 4) Multiple codegen units, but no explicit name. We
570 // just leave the `foo.0.x` files in place.
571 // (We don't have to do any work in this case.)
576 // Flag to indicate whether the user explicitly requested bitcode.
577 // Otherwise, we produced it only as a temporary output, and will need
579 for output_type in crate_output.outputs.keys() {
581 OutputType::Bitcode => {
582 user_wants_bitcode = true;
583 // Copy to .bc, but always keep the .0.bc. There is a later
584 // check to figure out if we should delete .0.bc files, or keep
585 // them for making an rlib.
586 copy_if_one_unit(OutputType::Bitcode, true);
588 OutputType::LlvmAssembly => {
589 copy_if_one_unit(OutputType::LlvmAssembly, false);
591 OutputType::Assembly => {
592 copy_if_one_unit(OutputType::Assembly, false);
594 OutputType::Object => {
595 user_wants_objects = true;
596 copy_if_one_unit(OutputType::Object, true);
598 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
602 // Clean up unwanted temporary files.
604 // We create the following files by default:
605 // - #crate#.#module-name#.bc
606 // - #crate#.#module-name#.o
607 // - #crate#.crate.metadata.bc
608 // - #crate#.crate.metadata.o
609 // - #crate#.o (linked from crate.##.o)
610 // - #crate#.bc (copied from crate.##.bc)
611 // We may create additional files if requested by the user (through
612 // `-C save-temps` or `--emit=` flags).
614 if !sess.opts.cg.save_temps {
615 // Remove the temporary .#module-name#.o objects. If the user didn't
616 // explicitly request bitcode (with --emit=bc), and the bitcode is not
617 // needed for building an rlib, then we must remove .#module-name#.bc as
620 // Specific rules for keeping .#module-name#.bc:
621 // - If the user requested bitcode (`user_wants_bitcode`), and
622 // codegen_units > 1, then keep it.
623 // - If the user requested bitcode but codegen_units == 1, then we
624 // can toss .#module-name#.bc because we copied it to .bc earlier.
625 // - If we're not building an rlib and the user didn't request
626 // bitcode, then delete .#module-name#.bc.
627 // If you change how this works, also update back::link::link_rlib,
628 // where .#module-name#.bc files are (maybe) deleted after making an
630 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
632 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
634 let keep_numbered_objects =
635 needs_crate_object || (user_wants_objects && sess.codegen_units() > 1);
637 for module in compiled_modules.modules.iter() {
638 if let Some(ref path) = module.object {
639 if !keep_numbered_objects {
640 ensure_removed(sess.diagnostic(), path);
644 if let Some(ref path) = module.dwarf_object {
645 if !keep_numbered_objects {
646 ensure_removed(sess.diagnostic(), path);
650 if let Some(ref path) = module.bytecode {
651 if !keep_numbered_bitcode {
652 ensure_removed(sess.diagnostic(), path);
657 if !user_wants_bitcode {
658 if let Some(ref allocator_module) = compiled_modules.allocator_module {
659 if let Some(ref path) = allocator_module.bytecode {
660 ensure_removed(sess.diagnostic(), path);
666 // We leave the following files around by default:
668 // - #crate#.crate.metadata.o
670 // These are used in linking steps and will be cleaned up afterward.
673 pub enum WorkItem<B: WriteBackendMethods> {
674 /// Optimize a newly codegened, totally unoptimized module.
675 Optimize(ModuleCodegen<B::Module>),
676 /// Copy the post-LTO artifacts from the incremental cache to the output
678 CopyPostLtoArtifacts(CachedModuleCodegen),
679 /// Performs (Thin)LTO on the given module.
680 LTO(lto::LtoModuleCodegen<B>),
683 impl<B: WriteBackendMethods> WorkItem<B> {
684 pub fn module_kind(&self) -> ModuleKind {
686 WorkItem::Optimize(ref m) => m.kind,
687 WorkItem::CopyPostLtoArtifacts(_) | WorkItem::LTO(_) => ModuleKind::Regular,
691 fn start_profiling<'a>(&self, cgcx: &'a CodegenContext<B>) -> TimingGuard<'a> {
693 WorkItem::Optimize(ref m) => {
694 cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &*m.name)
696 WorkItem::CopyPostLtoArtifacts(ref m) => cgcx
698 .generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &*m.name),
699 WorkItem::LTO(ref m) => {
700 cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name())
705 /// Generate a short description of this work item suitable for use as a thread name.
706 fn short_description(&self) -> String {
707 // `pthread_setname()` on *nix is limited to 15 characters and longer names are ignored.
708 // Use very short descriptions in this case to maximize the space available for the module name.
709 // Windows does not have that limitation so use slightly more descriptive names there.
711 WorkItem::Optimize(m) => {
713 return format!("optimize module {}", m.name);
715 return format!("opt {}", m.name);
717 WorkItem::CopyPostLtoArtifacts(m) => {
719 return format!("copy LTO artifacts for {}", m.name);
721 return format!("copy {}", m.name);
723 WorkItem::LTO(m) => {
725 return format!("LTO module {}", m.name());
727 return format!("LTO {}", m.name());
733 enum WorkItemResult<B: WriteBackendMethods> {
734 Compiled(CompiledModule),
735 NeedsLink(ModuleCodegen<B::Module>),
736 NeedsFatLTO(FatLTOInput<B>),
737 NeedsThinLTO(String, B::ThinBuffer),
740 pub enum FatLTOInput<B: WriteBackendMethods> {
741 Serialized { name: String, buffer: B::ModuleBuffer },
742 InMemory(ModuleCodegen<B::Module>),
745 fn execute_work_item<B: ExtraBackendMethods>(
746 cgcx: &CodegenContext<B>,
747 work_item: WorkItem<B>,
748 ) -> Result<WorkItemResult<B>, FatalError> {
749 let module_config = cgcx.config(work_item.module_kind());
752 WorkItem::Optimize(module) => execute_optimize_work_item(cgcx, module, module_config),
753 WorkItem::CopyPostLtoArtifacts(module) => {
754 Ok(execute_copy_from_cache_work_item(cgcx, module, module_config))
756 WorkItem::LTO(module) => execute_lto_work_item(cgcx, module, module_config),
760 // Actual LTO type we end up choosing based on multiple factors.
761 pub enum ComputedLtoType {
767 pub fn compute_per_cgu_lto_type(
769 opts: &config::Options,
770 sess_crate_types: &[CrateType],
771 module_kind: ModuleKind,
772 ) -> ComputedLtoType {
773 // Metadata modules never participate in LTO regardless of the lto
775 if module_kind == ModuleKind::Metadata {
776 return ComputedLtoType::No;
779 // If the linker does LTO, we don't have to do it. Note that we
780 // keep doing full LTO, if it is requested, as not to break the
781 // assumption that the output will be a single module.
782 let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
784 // When we're automatically doing ThinLTO for multi-codegen-unit
785 // builds we don't actually want to LTO the allocator modules if
786 // it shows up. This is due to various linker shenanigans that
787 // we'll encounter later.
788 let is_allocator = module_kind == ModuleKind::Allocator;
790 // We ignore a request for full crate graph LTO if the crate type
791 // is only an rlib, as there is no full crate graph to process,
792 // that'll happen later.
794 // This use case currently comes up primarily for targets that
795 // require LTO so the request for LTO is always unconditionally
796 // passed down to the backend, but we don't actually want to do
797 // anything about it yet until we've got a final product.
798 let is_rlib = sess_crate_types.len() == 1 && sess_crate_types[0] == CrateType::Rlib;
801 Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
802 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
803 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
804 _ => ComputedLtoType::No,
808 fn execute_optimize_work_item<B: ExtraBackendMethods>(
809 cgcx: &CodegenContext<B>,
810 module: ModuleCodegen<B::Module>,
811 module_config: &ModuleConfig,
812 ) -> Result<WorkItemResult<B>, FatalError> {
813 let diag_handler = cgcx.create_diag_handler();
816 B::optimize(cgcx, &diag_handler, &module, module_config)?;
819 // After we've done the initial round of optimizations we need to
820 // decide whether to synchronously codegen this module or ship it
821 // back to the coordinator thread for further LTO processing (which
822 // has to wait for all the initial modules to be optimized).
824 let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
826 // If we're doing some form of incremental LTO then we need to be sure to
827 // save our module to disk first.
828 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
829 let filename = pre_lto_bitcode_filename(&module.name);
830 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
836 ComputedLtoType::No => finish_intra_module_work(cgcx, module, module_config),
837 ComputedLtoType::Thin => {
838 let (name, thin_buffer) = B::prepare_thin(module);
839 if let Some(path) = bitcode {
840 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
841 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
844 Ok(WorkItemResult::NeedsThinLTO(name, thin_buffer))
846 ComputedLtoType::Fat => match bitcode {
848 let (name, buffer) = B::serialize_module(module);
849 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
850 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
852 Ok(WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer }))
854 None => Ok(WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module))),
859 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
860 cgcx: &CodegenContext<B>,
861 module: CachedModuleCodegen,
862 module_config: &ModuleConfig,
863 ) -> WorkItemResult<B> {
864 assert!(module_config.emit_obj != EmitObj::None);
866 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
868 let load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
869 let source_file = in_incr_comp_dir(&incr_comp_session_dir, saved_path);
871 "copying pre-existing module `{}` from {:?} to {}",
874 output_path.display()
876 match link_or_copy(&source_file, &output_path) {
877 Ok(_) => Some(output_path),
879 cgcx.create_diag_handler().emit_err(errors::CopyPathBuf {
889 let object = load_from_incr_comp_dir(
890 cgcx.output_filenames.temp_path(OutputType::Object, Some(&module.name)),
891 &module.source.saved_files.get("o").expect("no saved object file in work product"),
894 module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
895 let dwarf_obj_out = cgcx
897 .split_dwarf_path(cgcx.split_debuginfo, cgcx.split_dwarf_kind, Some(&module.name))
899 "saved dwarf object in work product but `split_dwarf_path` returned `None`",
901 load_from_incr_comp_dir(dwarf_obj_out, &saved_dwarf_object_file)
904 WorkItemResult::Compiled(CompiledModule {
906 kind: ModuleKind::Regular,
913 fn execute_lto_work_item<B: ExtraBackendMethods>(
914 cgcx: &CodegenContext<B>,
915 module: lto::LtoModuleCodegen<B>,
916 module_config: &ModuleConfig,
917 ) -> Result<WorkItemResult<B>, FatalError> {
918 let module = unsafe { module.optimize(cgcx)? };
919 finish_intra_module_work(cgcx, module, module_config)
922 fn finish_intra_module_work<B: ExtraBackendMethods>(
923 cgcx: &CodegenContext<B>,
924 module: ModuleCodegen<B::Module>,
925 module_config: &ModuleConfig,
926 ) -> Result<WorkItemResult<B>, FatalError> {
927 let diag_handler = cgcx.create_diag_handler();
929 if !cgcx.opts.unstable_opts.combine_cgu
930 || module.kind == ModuleKind::Metadata
931 || module.kind == ModuleKind::Allocator
933 let module = unsafe { B::codegen(cgcx, &diag_handler, module, module_config)? };
934 Ok(WorkItemResult::Compiled(module))
936 Ok(WorkItemResult::NeedsLink(module))
940 pub enum Message<B: WriteBackendMethods> {
941 Token(io::Result<Acquired>),
943 result: FatLTOInput<B>,
948 thin_buffer: B::ThinBuffer,
952 module: ModuleCodegen<B::Module>,
956 result: Result<CompiledModule, Option<WorkerFatalError>>,
960 llvm_work_item: WorkItem<B>,
963 AddImportOnlyModule {
964 module_data: SerializedModule<B::ModuleBuffer>,
965 work_product: WorkProduct,
974 code: Option<DiagnosticId>,
978 #[derive(PartialEq, Clone, Copy, Debug)]
979 enum MainThreadWorkerState {
985 fn start_executing_work<B: ExtraBackendMethods>(
988 crate_info: &CrateInfo,
989 shared_emitter: SharedEmitter,
990 codegen_worker_send: Sender<Message<B>>,
991 coordinator_receive: Receiver<Box<dyn Any + Send>>,
994 regular_config: Arc<ModuleConfig>,
995 metadata_config: Arc<ModuleConfig>,
996 allocator_config: Arc<ModuleConfig>,
997 tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
998 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
999 let coordinator_send = tx_to_llvm_workers;
1000 let sess = tcx.sess;
1002 let mut each_linked_rlib_for_lto = Vec::new();
1003 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1004 if link::ignored_for_lto(sess, crate_info, cnum) {
1007 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1010 // Compute the set of symbols we need to retain when doing LTO (if we need to)
1011 let exported_symbols = {
1012 let mut exported_symbols = FxHashMap::default();
1014 let copy_symbols = |cnum| {
1016 .exported_symbols(cnum)
1018 .map(|&(s, lvl)| (symbol_name_for_instance_in_crate(tcx, s, cnum), lvl))
1026 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1027 Some(Arc::new(exported_symbols))
1029 Lto::Fat | Lto::Thin => {
1030 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1031 for &(cnum, ref _path) in &each_linked_rlib_for_lto {
1032 exported_symbols.insert(cnum, copy_symbols(cnum));
1034 Some(Arc::new(exported_symbols))
1039 // First up, convert our jobserver into a helper thread so we can use normal
1040 // mpsc channels to manage our messages and such.
1041 // After we've requested tokens then we'll, when we can,
1042 // get tokens on `coordinator_receive` which will
1043 // get managed in the main loop below.
1044 let coordinator_send2 = coordinator_send.clone();
1045 let helper = jobserver
1046 .into_helper_thread(move |token| {
1047 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
1049 .expect("failed to spawn helper thread");
1052 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
1053 // If we know that we won’t be doing codegen, create target machines without optimisation.
1054 config::OptLevel::No
1056 tcx.backend_optimization_level(())
1058 let backend_features = tcx.global_backend_features(());
1059 let cgcx = CodegenContext::<B> {
1060 backend: backend.clone(),
1061 crate_types: sess.crate_types().to_vec(),
1062 each_linked_rlib_for_lto,
1064 fewer_names: sess.fewer_names(),
1065 save_temps: sess.opts.cg.save_temps,
1066 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1067 opts: Arc::new(sess.opts.clone()),
1068 prof: sess.prof.clone(),
1070 remark: sess.opts.cg.remark.clone(),
1072 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1073 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1075 diag_emitter: shared_emitter.clone(),
1076 output_filenames: tcx.output_filenames(()).clone(),
1077 regular_module_config: regular_config,
1078 metadata_module_config: metadata_config,
1079 allocator_module_config: allocator_config,
1080 tm_factory: backend.target_machine_factory(tcx.sess, ol, backend_features),
1082 msvc_imps_needed: msvc_imps_needed(tcx),
1083 is_pe_coff: tcx.sess.target.is_like_windows,
1084 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1085 target_pointer_width: tcx.sess.target.pointer_width,
1086 target_arch: tcx.sess.target.arch.to_string(),
1087 debuginfo: tcx.sess.opts.debuginfo,
1088 split_debuginfo: tcx.sess.split_debuginfo(),
1089 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1092 // This is the "main loop" of parallel work happening for parallel codegen.
1093 // It's here that we manage parallelism, schedule work, and work with
1094 // messages coming from clients.
1096 // There are a few environmental pre-conditions that shape how the system
1099 // - Error reporting only can happen on the main thread because that's the
1100 // only place where we have access to the compiler `Session`.
1101 // - LLVM work can be done on any thread.
1102 // - Codegen can only happen on the main thread.
1103 // - Each thread doing substantial work must be in possession of a `Token`
1104 // from the `Jobserver`.
1105 // - The compiler process always holds one `Token`. Any additional `Tokens`
1106 // have to be requested from the `Jobserver`.
1110 // The error reporting restriction is handled separately from the rest: We
1111 // set up a `SharedEmitter` the holds an open channel to the main thread.
1112 // When an error occurs on any thread, the shared emitter will send the
1113 // error message to the receiver main thread (`SharedEmitterMain`). The
1114 // main thread will periodically query this error message queue and emit
1115 // any error messages it has received. It might even abort compilation if
1116 // has received a fatal error. In this case we rely on all other threads
1117 // being torn down automatically with the main thread.
1118 // Since the main thread will often be busy doing codegen work, error
1119 // reporting will be somewhat delayed, since the message queue can only be
1120 // checked in between to work packages.
1122 // Work Processing Infrastructure
1123 // ==============================
1124 // The work processing infrastructure knows three major actors:
1126 // - the coordinator thread,
1127 // - the main thread, and
1128 // - LLVM worker threads
1130 // The coordinator thread is running a message loop. It instructs the main
1131 // thread about what work to do when, and it will spawn off LLVM worker
1132 // threads as open LLVM WorkItems become available.
1134 // The job of the main thread is to codegen CGUs into LLVM work package
1135 // (since the main thread is the only thread that can do this). The main
1136 // thread will block until it receives a message from the coordinator, upon
1137 // which it will codegen one CGU, send it to the coordinator and block
1138 // again. This way the coordinator can control what the main thread is
1141 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1142 // available, it will spawn off a new LLVM worker thread and let it process
1143 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1144 // it will just shut down, which also frees all resources associated with
1145 // the given LLVM module, and sends a message to the coordinator that the
1146 // has been completed.
1150 // The scheduler's goal is to minimize the time it takes to complete all
1151 // work there is, however, we also want to keep memory consumption low
1152 // if possible. These two goals are at odds with each other: If memory
1153 // consumption were not an issue, we could just let the main thread produce
1154 // LLVM WorkItems at full speed, assuring maximal utilization of
1155 // Tokens/LLVM worker threads. However, since codegen is usually faster
1156 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1157 // WorkItem potentially holds on to a substantial amount of memory.
1159 // So the actual goal is to always produce just enough LLVM WorkItems as
1160 // not to starve our LLVM worker threads. That means, once we have enough
1161 // WorkItems in our queue, we can block the main thread, so it does not
1162 // produce more until we need them.
1164 // Doing LLVM Work on the Main Thread
1165 // ----------------------------------
1166 // Since the main thread owns the compiler processes implicit `Token`, it is
1167 // wasteful to keep it blocked without doing any work. Therefore, what we do
1168 // in this case is: We spawn off an additional LLVM worker thread that helps
1169 // reduce the queue. The work it is doing corresponds to the implicit
1170 // `Token`. The coordinator will mark the main thread as being busy with
1171 // LLVM work. (The actual work happens on another OS thread but we just care
1172 // about `Tokens`, not actual threads).
1174 // When any LLVM worker thread finishes while the main thread is marked as
1175 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1176 // of the just finished thread to the LLVM worker thread that is working on
1177 // behalf of the main thread's implicit Token, thus freeing up the main
1178 // thread again. The coordinator can then again decide what the main thread
1179 // should do. This allows the coordinator to make decisions at more points
1182 // Striking a Balance between Throughput and Memory Consumption
1183 // ------------------------------------------------------------
1184 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1185 // memory consumption as low as possible, are in conflict with each other,
1186 // we have to find a trade off between them. Right now, the goal is to keep
1187 // all workers busy, which means that no worker should find the queue empty
1188 // when it is ready to start.
1189 // How do we do achieve this? Good question :) We actually never know how
1190 // many `Tokens` are potentially available so it's hard to say how much to
1191 // fill up the queue before switching the main thread to LLVM work. Also we
1192 // currently don't have a means to estimate how long a running LLVM worker
1193 // will still be busy with it's current WorkItem. However, we know the
1194 // maximal count of available Tokens that makes sense (=the number of CPU
1195 // cores), so we can take a conservative guess. The heuristic we use here
1196 // is implemented in the `queue_full_enough()` function.
1198 // Some Background on Jobservers
1199 // -----------------------------
1200 // It's worth also touching on the management of parallelism here. We don't
1201 // want to just spawn a thread per work item because while that's optimal
1202 // parallelism it may overload a system with too many threads or violate our
1203 // configuration for the maximum amount of cpu to use for this process. To
1204 // manage this we use the `jobserver` crate.
1206 // Job servers are an artifact of GNU make and are used to manage
1207 // parallelism between processes. A jobserver is a glorified IPC semaphore
1208 // basically. Whenever we want to run some work we acquire the semaphore,
1209 // and whenever we're done with that work we release the semaphore. In this
1210 // manner we can ensure that the maximum number of parallel workers is
1211 // capped at any one point in time.
1213 // LTO and the coordinator thread
1214 // ------------------------------
1216 // The final job the coordinator thread is responsible for is managing LTO
1217 // and how that works. When LTO is requested what we'll to is collect all
1218 // optimized LLVM modules into a local vector on the coordinator. Once all
1219 // modules have been codegened and optimized we hand this to the `lto`
1220 // module for further optimization. The `lto` module will return back a list
1221 // of more modules to work on, which the coordinator will continue to spawn
1224 // Each LLVM module is automatically sent back to the coordinator for LTO if
1225 // necessary. There's already optimizations in place to avoid sending work
1226 // back to the coordinator if LTO isn't requested.
1227 return B::spawn_thread(cgcx.time_trace, move || {
1228 let mut worker_id_counter = 0;
1229 let mut free_worker_ids = Vec::new();
1230 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1231 if let Some(id) = free_worker_ids.pop() {
1234 let id = worker_id_counter;
1235 worker_id_counter += 1;
1240 // This is where we collect codegen units that have gone all the way
1241 // through codegen and LLVM.
1242 let mut compiled_modules = vec![];
1243 let mut compiled_allocator_module = None;
1244 let mut needs_link = Vec::new();
1245 let mut needs_fat_lto = Vec::new();
1246 let mut needs_thin_lto = Vec::new();
1247 let mut lto_import_only_modules = Vec::new();
1248 let mut started_lto = false;
1249 let mut codegen_aborted = false;
1251 // This flag tracks whether all items have gone through codegens
1252 let mut codegen_done = false;
1254 // This is the queue of LLVM work items that still need processing.
1255 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1257 // This are the Jobserver Tokens we currently hold. Does not include
1258 // the implicit Token the compiler process owns no matter what.
1259 let mut tokens = Vec::new();
1261 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1262 let mut running = 0;
1264 let prof = &cgcx.prof;
1265 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1267 // Run the message loop while there's still anything that needs message
1268 // processing. Note that as soon as codegen is aborted we simply want to
1269 // wait for all existing work to finish, so many of the conditions here
1270 // only apply if codegen hasn't been aborted as they represent pending
1274 || main_thread_worker_state == MainThreadWorkerState::LLVMing
1275 || (!codegen_aborted
1276 && !(work_items.is_empty()
1277 && needs_fat_lto.is_empty()
1278 && needs_thin_lto.is_empty()
1279 && lto_import_only_modules.is_empty()
1280 && main_thread_worker_state == MainThreadWorkerState::Idle))
1282 // While there are still CGUs to be codegened, the coordinator has
1283 // to decide how to utilize the compiler processes implicit Token:
1284 // For codegenning more CGU or for running them through LLVM.
1286 if main_thread_worker_state == MainThreadWorkerState::Idle {
1287 // Compute the number of workers that will be running once we've taken as many
1288 // items from the work queue as we can, plus one for the main thread. It's not
1289 // critically important that we use this instead of just `running`, but it
1290 // prevents the `queue_full_enough` heuristic from fluctuating just because a
1291 // worker finished up and we decreased the `running` count, even though we're
1292 // just going to increase it right after this when we put a new worker to work.
1293 let extra_tokens = tokens.len().checked_sub(running).unwrap();
1294 let additional_running = std::cmp::min(extra_tokens, work_items.len());
1295 let anticipated_running = running + additional_running + 1;
1297 if !queue_full_enough(work_items.len(), anticipated_running) {
1298 // The queue is not full enough, codegen more items:
1299 if codegen_worker_send.send(Message::CodegenItem).is_err() {
1300 panic!("Could not send Message::CodegenItem to main thread")
1302 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1304 // The queue is full enough to not let the worker
1305 // threads starve. Use the implicit Token to do some
1308 work_items.pop().expect("queue empty - queue_full_enough() broken?");
1309 let cgcx = CodegenContext {
1310 worker: get_worker_id(&mut free_worker_ids),
1313 maybe_start_llvm_timer(
1315 cgcx.config(item.module_kind()),
1316 &mut llvm_start_time,
1318 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1319 spawn_work(cgcx, item);
1322 } else if codegen_aborted {
1323 // don't queue up any more work if codegen was aborted, we're
1324 // just waiting for our existing children to finish
1326 // If we've finished everything related to normal codegen
1327 // then it must be the case that we've got some LTO work to do.
1328 // Perform the serial work here of figuring out what we're
1329 // going to LTO and then push a bunch of work items onto our
1331 if work_items.is_empty()
1333 && main_thread_worker_state == MainThreadWorkerState::Idle
1335 assert!(!started_lto);
1338 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1339 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1340 let import_only_modules = mem::take(&mut lto_import_only_modules);
1343 generate_lto_work(&cgcx, needs_fat_lto, needs_thin_lto, import_only_modules)
1345 let insertion_index = work_items
1346 .binary_search_by_key(&cost, |&(_, cost)| cost)
1347 .unwrap_or_else(|e| e);
1348 work_items.insert(insertion_index, (work, cost));
1349 if !cgcx.opts.unstable_opts.no_parallel_llvm {
1350 helper.request_token();
1355 // In this branch, we know that everything has been codegened,
1356 // so it's just a matter of determining whether the implicit
1357 // Token is free to use for LLVM work.
1358 match main_thread_worker_state {
1359 MainThreadWorkerState::Idle => {
1360 if let Some((item, _)) = work_items.pop() {
1361 let cgcx = CodegenContext {
1362 worker: get_worker_id(&mut free_worker_ids),
1365 maybe_start_llvm_timer(
1367 cgcx.config(item.module_kind()),
1368 &mut llvm_start_time,
1370 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1371 spawn_work(cgcx, item);
1373 // There is no unstarted work, so let the main thread
1374 // take over for a running worker. Otherwise the
1375 // implicit token would just go to waste.
1376 // We reduce the `running` counter by one. The
1377 // `tokens.truncate()` below will take care of
1378 // giving the Token back.
1379 debug_assert!(running > 0);
1381 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1384 MainThreadWorkerState::Codegenning => bug!(
1385 "codegen worker should not be codegenning after \
1386 codegen was already completed"
1388 MainThreadWorkerState::LLVMing => {
1389 // Already making good use of that token
1394 // Spin up what work we can, only doing this while we've got available
1395 // parallelism slots and work left to spawn.
1396 while !codegen_aborted && !work_items.is_empty() && running < tokens.len() {
1397 let (item, _) = work_items.pop().unwrap();
1399 maybe_start_llvm_timer(prof, cgcx.config(item.module_kind()), &mut llvm_start_time);
1402 CodegenContext { worker: get_worker_id(&mut free_worker_ids), ..cgcx.clone() };
1404 spawn_work(cgcx, item);
1408 // Relinquish accidentally acquired extra tokens
1409 tokens.truncate(running);
1411 // If a thread exits successfully then we drop a token associated
1412 // with that worker and update our `running` count. We may later
1413 // re-acquire a token to continue running more work. We may also not
1414 // actually drop a token here if the worker was running with an
1415 // "ephemeral token"
1416 let mut free_worker = |worker_id| {
1417 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1418 main_thread_worker_state = MainThreadWorkerState::Idle;
1423 free_worker_ids.push(worker_id);
1426 let msg = coordinator_receive.recv().unwrap();
1427 match *msg.downcast::<Message<B>>().ok().unwrap() {
1428 // Save the token locally and the next turn of the loop will use
1429 // this to spawn a new unit of work, or it may get dropped
1430 // immediately if we have no more work to spawn.
1431 Message::Token(token) => {
1436 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1437 // If the main thread token is used for LLVM work
1438 // at the moment, we turn that thread into a regular
1439 // LLVM worker thread, so the main thread is free
1440 // to react to codegen demand.
1441 main_thread_worker_state = MainThreadWorkerState::Idle;
1446 let msg = &format!("failed to acquire jobserver token: {}", e);
1447 shared_emitter.fatal(msg);
1448 // Exit the coordinator thread
1454 Message::CodegenDone { llvm_work_item, cost } => {
1455 // We keep the queue sorted by estimated processing cost,
1456 // so that more expensive items are processed earlier. This
1457 // is good for throughput as it gives the main thread more
1458 // time to fill up the queue and it avoids scheduling
1459 // expensive items to the end.
1460 // Note, however, that this is not ideal for memory
1461 // consumption, as LLVM module sizes are not evenly
1463 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1464 let insertion_index = match insertion_index {
1465 Ok(idx) | Err(idx) => idx,
1467 work_items.insert(insertion_index, (llvm_work_item, cost));
1469 if !cgcx.opts.unstable_opts.no_parallel_llvm {
1470 helper.request_token();
1472 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1473 main_thread_worker_state = MainThreadWorkerState::Idle;
1476 Message::CodegenComplete => {
1477 codegen_done = true;
1478 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1479 main_thread_worker_state = MainThreadWorkerState::Idle;
1482 // If codegen is aborted that means translation was aborted due
1483 // to some normal-ish compiler error. In this situation we want
1484 // to exit as soon as possible, but we want to make sure all
1485 // existing work has finished. Flag codegen as being done, and
1486 // then conditions above will ensure no more work is spawned but
1487 // we'll keep executing this loop until `running` hits 0.
1488 Message::CodegenAborted => {
1489 codegen_done = true;
1490 codegen_aborted = true;
1492 Message::Done { result: Ok(compiled_module), worker_id } => {
1493 free_worker(worker_id);
1494 match compiled_module.kind {
1495 ModuleKind::Regular => {
1496 compiled_modules.push(compiled_module);
1498 ModuleKind::Allocator => {
1499 assert!(compiled_allocator_module.is_none());
1500 compiled_allocator_module = Some(compiled_module);
1502 ModuleKind::Metadata => bug!("Should be handled separately"),
1505 Message::NeedsLink { module, worker_id } => {
1506 free_worker(worker_id);
1507 needs_link.push(module);
1509 Message::NeedsFatLTO { result, worker_id } => {
1510 assert!(!started_lto);
1511 free_worker(worker_id);
1512 needs_fat_lto.push(result);
1514 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1515 assert!(!started_lto);
1516 free_worker(worker_id);
1517 needs_thin_lto.push((name, thin_buffer));
1519 Message::AddImportOnlyModule { module_data, work_product } => {
1520 assert!(!started_lto);
1521 assert!(!codegen_done);
1522 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1523 lto_import_only_modules.push((module_data, work_product));
1524 main_thread_worker_state = MainThreadWorkerState::Idle;
1526 // If the thread failed that means it panicked, so we abort immediately.
1527 Message::Done { result: Err(None), worker_id: _ } => {
1528 bug!("worker thread panicked");
1530 Message::Done { result: Err(Some(WorkerFatalError)), worker_id } => {
1531 // Similar to CodegenAborted, wait for remaining work to finish.
1532 free_worker(worker_id);
1533 codegen_done = true;
1534 codegen_aborted = true;
1536 Message::CodegenItem => bug!("the coordinator should not receive codegen requests"),
1540 if codegen_aborted {
1544 let needs_link = mem::take(&mut needs_link);
1545 if !needs_link.is_empty() {
1546 assert!(compiled_modules.is_empty());
1547 let diag_handler = cgcx.create_diag_handler();
1548 let module = B::run_link(&cgcx, &diag_handler, needs_link).map_err(|_| ())?;
1549 let module = unsafe {
1550 B::codegen(&cgcx, &diag_handler, module, cgcx.config(ModuleKind::Regular))
1553 compiled_modules.push(module);
1556 // Drop to print timings
1557 drop(llvm_start_time);
1559 // Regardless of what order these modules completed in, report them to
1560 // the backend in the same order every time to ensure that we're handing
1561 // out deterministic results.
1562 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1564 Ok(CompiledModules {
1565 modules: compiled_modules,
1566 allocator_module: compiled_allocator_module,
1570 // A heuristic that determines if we have enough LLVM WorkItems in the
1571 // queue so that the main thread can do LLVM work instead of codegen
1572 fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1573 // This heuristic scales ahead-of-time codegen according to available
1574 // concurrency, as measured by `workers_running`. The idea is that the
1575 // more concurrency we have available, the more demand there will be for
1576 // work items, and the fuller the queue should be kept to meet demand.
1577 // An important property of this approach is that we codegen ahead of
1578 // time only as much as necessary, so as to keep fewer LLVM modules in
1579 // memory at once, thereby reducing memory consumption.
1581 // When the number of workers running is less than the max concurrency
1582 // available to us, this heuristic can cause us to instruct the main
1583 // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1584 // of codegen, even though it seems like it *should* be codegenning so
1585 // that we can create more work items and spawn more LLVM workers.
1587 // But this is not a problem. When the main thread is told to LLVM,
1588 // according to this heuristic and how work is scheduled, there is
1589 // always at least one item in the queue, and therefore at least one
1590 // pending jobserver token request. If there *is* more concurrency
1591 // available, we will immediately receive a token, which will upgrade
1592 // the main thread's LLVM worker to a real one (conceptually), and free
1593 // up the main thread to codegen if necessary. On the other hand, if
1594 // there isn't more concurrency, then the main thread working on an LLVM
1595 // item is appropriate, as long as the queue is full enough for demand.
1597 // Speaking of which, how full should we keep the queue? Probably less
1598 // full than you'd think. A lot has to go wrong for the queue not to be
1599 // full enough and for that to have a negative effect on compile times.
1601 // Workers are unlikely to finish at exactly the same time, so when one
1602 // finishes and takes another work item off the queue, we often have
1603 // ample time to codegen at that point before the next worker finishes.
1604 // But suppose that codegen takes so long that the workers exhaust the
1605 // queue, and we have one or more workers that have nothing to work on.
1606 // Well, it might not be so bad. Of all the LLVM modules we create and
1607 // optimize, one has to finish last. It's not necessarily the case that
1608 // by losing some concurrency for a moment, we delay the point at which
1609 // that last LLVM module is finished and the rest of compilation can
1610 // proceed. Also, when we can't take advantage of some concurrency, we
1611 // give tokens back to the job server. That enables some other rustc to
1612 // potentially make use of the available concurrency. That could even
1613 // *decrease* overall compile time if we're lucky. But yes, if no other
1614 // rustc can make use of the concurrency, then we've squandered it.
1616 // However, keeping the queue full is also beneficial when we have a
1617 // surge in available concurrency. Then items can be taken from the
1618 // queue immediately, without having to wait for codegen.
1620 // So, the heuristic below tries to keep one item in the queue for every
1621 // four running workers. Based on limited benchmarking, this appears to
1622 // be more than sufficient to avoid increasing compilation times.
1623 let quarter_of_workers = workers_running - 3 * workers_running / 4;
1624 items_in_queue > 0 && items_in_queue >= quarter_of_workers
1627 fn maybe_start_llvm_timer<'a>(
1628 prof: &'a SelfProfilerRef,
1629 config: &ModuleConfig,
1630 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1632 if config.time_module && llvm_start_time.is_none() {
1633 *llvm_start_time = Some(prof.verbose_generic_activity("LLVM_passes"));
1638 /// `FatalError` is explicitly not `Send`.
1640 pub struct WorkerFatalError;
1642 fn spawn_work<B: ExtraBackendMethods>(cgcx: CodegenContext<B>, work: WorkItem<B>) {
1643 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1644 // Set up a destructor which will fire off a message that we're done as
1646 struct Bomb<B: ExtraBackendMethods> {
1647 coordinator_send: Sender<Box<dyn Any + Send>>,
1648 result: Option<Result<WorkItemResult<B>, FatalError>>,
1651 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1652 fn drop(&mut self) {
1653 let worker_id = self.worker_id;
1654 let msg = match self.result.take() {
1655 Some(Ok(WorkItemResult::Compiled(m))) => {
1656 Message::Done::<B> { result: Ok(m), worker_id }
1658 Some(Ok(WorkItemResult::NeedsLink(m))) => {
1659 Message::NeedsLink::<B> { module: m, worker_id }
1661 Some(Ok(WorkItemResult::NeedsFatLTO(m))) => {
1662 Message::NeedsFatLTO::<B> { result: m, worker_id }
1664 Some(Ok(WorkItemResult::NeedsThinLTO(name, thin_buffer))) => {
1665 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1667 Some(Err(FatalError)) => {
1668 Message::Done::<B> { result: Err(Some(WorkerFatalError)), worker_id }
1670 None => Message::Done::<B> { result: Err(None), worker_id },
1672 drop(self.coordinator_send.send(Box::new(msg)));
1676 let mut bomb = Bomb::<B> {
1677 coordinator_send: cgcx.coordinator_send.clone(),
1679 worker_id: cgcx.worker,
1682 // Execute the work itself, and if it finishes successfully then flag
1683 // ourselves as a success as well.
1685 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1686 // as a diagnostic was already sent off to the main thread - just
1687 // surface that there was an error in this worker.
1689 let _prof_timer = work.start_profiling(&cgcx);
1690 Some(execute_work_item(&cgcx, work))
1693 .expect("failed to spawn thread");
1696 enum SharedEmitterMessage {
1697 Diagnostic(Diagnostic),
1698 InlineAsmError(u32, String, Level, Option<(String, Vec<InnerSpan>)>),
1704 pub struct SharedEmitter {
1705 sender: Sender<SharedEmitterMessage>,
1708 pub struct SharedEmitterMain {
1709 receiver: Receiver<SharedEmitterMessage>,
1712 impl SharedEmitter {
1713 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1714 let (sender, receiver) = channel();
1716 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1719 pub fn inline_asm_error(
1724 source: Option<(String, Vec<InnerSpan>)>,
1726 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)));
1729 pub fn fatal(&self, msg: &str) {
1730 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1734 impl Translate for SharedEmitter {
1735 fn fluent_bundle(&self) -> Option<&Lrc<rustc_errors::FluentBundle>> {
1739 fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle {
1740 panic!("shared emitter attempted to translate a diagnostic");
1744 impl Emitter for SharedEmitter {
1745 fn emit_diagnostic(&mut self, diag: &rustc_errors::Diagnostic) {
1746 let fluent_args = to_fluent_args(diag.args());
1747 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1748 msg: self.translate_messages(&diag.message, &fluent_args).to_string(),
1749 code: diag.code.clone(),
1752 for child in &diag.children {
1753 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1754 msg: self.translate_messages(&child.message, &fluent_args).to_string(),
1759 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1762 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
1767 impl SharedEmitterMain {
1768 pub fn check(&self, sess: &Session, blocking: bool) {
1770 let message = if blocking {
1771 match self.receiver.recv() {
1772 Ok(message) => Ok(message),
1776 match self.receiver.try_recv() {
1777 Ok(message) => Ok(message),
1783 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1784 let handler = sess.diagnostic();
1785 let mut d = rustc_errors::Diagnostic::new(diag.lvl, &diag.msg);
1786 if let Some(code) = diag.code {
1789 handler.emit_diagnostic(&mut d);
1791 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => {
1792 let msg = msg.strip_prefix("error: ").unwrap_or(&msg);
1794 let mut err = match level {
1795 Level::Error { lint: false } => sess.struct_err(msg).forget_guarantee(),
1796 Level::Warning(_) => sess.struct_warn(msg),
1797 Level::Note => sess.struct_note_without_error(msg),
1798 _ => bug!("Invalid inline asm diagnostic level"),
1801 // If the cookie is 0 then we don't have span information.
1803 let pos = BytePos::from_u32(cookie);
1804 let span = Span::with_root_ctxt(pos, pos);
1808 // Point to the generated assembly if it is available.
1809 if let Some((buffer, spans)) = source {
1812 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
1813 let source_span = Span::with_root_ctxt(source.start_pos, source.end_pos);
1815 spans.iter().map(|sp| source_span.from_inner(*sp)).collect();
1816 err.span_note(spans, "instantiated into assembly here");
1821 Ok(SharedEmitterMessage::AbortIfErrors) => {
1822 sess.abort_if_errors();
1824 Ok(SharedEmitterMessage::Fatal(msg)) => {
1835 pub struct Coordinator<B: ExtraBackendMethods> {
1836 pub sender: Sender<Box<dyn Any + Send>>,
1837 future: Option<thread::JoinHandle<Result<CompiledModules, ()>>>,
1838 // Only used for the Message type.
1839 phantom: PhantomData<B>,
1842 impl<B: ExtraBackendMethods> Coordinator<B> {
1843 fn join(mut self) -> std::thread::Result<Result<CompiledModules, ()>> {
1844 self.future.take().unwrap().join()
1848 impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
1849 fn drop(&mut self) {
1850 if let Some(future) = self.future.take() {
1851 // If we haven't joined yet, signal to the coordinator that it should spawn no more
1852 // work, and wait for worker threads to finish.
1853 drop(self.sender.send(Box::new(Message::CodegenAborted::<B>)));
1854 drop(future.join());
1859 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1861 pub metadata: EncodedMetadata,
1862 pub metadata_module: Option<CompiledModule>,
1863 pub crate_info: CrateInfo,
1864 pub codegen_worker_receive: Receiver<Message<B>>,
1865 pub shared_emitter_main: SharedEmitterMain,
1866 pub output_filenames: Arc<OutputFilenames>,
1867 pub coordinator: Coordinator<B>,
1870 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1871 pub fn join(self, sess: &Session) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1872 let _timer = sess.timer("finish_ongoing_codegen");
1874 self.shared_emitter_main.check(sess, true);
1875 let compiled_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
1876 Ok(Ok(compiled_modules)) => compiled_modules,
1878 sess.abort_if_errors();
1879 panic!("expected abort due to worker thread errors")
1882 bug!("panic during codegen/LLVM phase");
1886 sess.cgu_reuse_tracker.check_expected_reuse(sess);
1888 sess.abort_if_errors();
1891 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
1892 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
1894 // FIXME: time_llvm_passes support - does this use a global context or
1896 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1897 self.backend.print_pass_timings()
1902 metadata: self.metadata,
1903 crate_info: self.crate_info,
1905 modules: compiled_modules.modules,
1906 allocator_module: compiled_modules.allocator_module,
1907 metadata_module: self.metadata_module,
1913 pub fn submit_pre_codegened_module_to_llvm(
1916 module: ModuleCodegen<B::Module>,
1918 self.wait_for_signal_to_codegen_item();
1919 self.check_for_errors(tcx.sess);
1921 // These are generally cheap and won't throw off scheduling.
1923 submit_codegened_module_to_llvm(&self.backend, &self.coordinator.sender, module, cost);
1926 pub fn codegen_finished(&self, tcx: TyCtxt<'_>) {
1927 self.wait_for_signal_to_codegen_item();
1928 self.check_for_errors(tcx.sess);
1929 drop(self.coordinator.sender.send(Box::new(Message::CodegenComplete::<B>)));
1932 pub fn check_for_errors(&self, sess: &Session) {
1933 self.shared_emitter_main.check(sess, false);
1936 pub fn wait_for_signal_to_codegen_item(&self) {
1937 match self.codegen_worker_receive.recv() {
1938 Ok(Message::CodegenItem) => {
1941 Ok(_) => panic!("unexpected message"),
1943 // One of the LLVM threads must have panicked, fall through so
1944 // error handling can be reached.
1950 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1952 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1953 module: ModuleCodegen<B::Module>,
1956 let llvm_work_item = WorkItem::Optimize(module);
1957 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost })));
1960 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1962 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1963 module: CachedModuleCodegen,
1965 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1966 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost: 0 })));
1969 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1972 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1973 module: CachedModuleCodegen,
1975 let filename = pre_lto_bitcode_filename(&module.name);
1976 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1977 let file = fs::File::open(&bc_path)
1978 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
1981 Mmap::map(file).unwrap_or_else(|e| {
1982 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1985 // Schedule the module to be loaded
1986 drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule::<B> {
1987 module_data: SerializedModule::FromUncompressedFile(mmap),
1988 work_product: module.source,
1992 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1993 format!("{}.{}", module_name, PRE_LTO_BC_EXT)
1996 fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
1997 // This should never be true (because it's not supported). If it is true,
1998 // something is wrong with commandline arg validation.
2000 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2001 && tcx.sess.target.is_like_windows
2002 && tcx.sess.opts.cg.prefer_dynamic)
2005 tcx.sess.target.is_like_windows &&
2006 tcx.sess.crate_types().iter().any(|ct| *ct == CrateType::Rlib) &&
2007 // ThinLTO can't handle this workaround in all cases, so we don't
2008 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2009 // dynamic linking when linker plugin LTO is enabled.
2010 !tcx.sess.opts.cg.linker_plugin_lto.enabled()