1 use super::link::{self, ensure_removed};
2 use super::linker::LinkerInfo;
3 use super::lto::{self, SerializedModule};
4 use super::symbol_export::symbol_name_for_instance_in_crate;
7 CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
11 use jobserver::{Acquired, Client};
12 use rustc_data_structures::fx::FxHashMap;
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;
18 use rustc_errors::{DiagnosticId, FatalError, Handler, Level};
19 use rustc_fs_util::link_or_copy;
20 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
21 use rustc_incremental::{
22 copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
24 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
25 use rustc_middle::middle::cstore::EncodedMetadata;
26 use rustc_middle::middle::exported_symbols::SymbolExportLevel;
27 use rustc_middle::ty::TyCtxt;
28 use rustc_session::cgu_reuse_tracker::CguReuseTracker;
29 use rustc_session::config::{self, CrateType, Lto, OutputFilenames, OutputType};
30 use rustc_session::config::{Passes, SanitizerSet, SwitchWithOptPath};
31 use rustc_session::Session;
32 use rustc_span::source_map::SourceMap;
33 use rustc_span::symbol::{sym, Symbol};
34 use rustc_span::{BytePos, FileName, InnerSpan, Pos, Span};
35 use rustc_target::spec::{MergeFunctions, PanicStrategy};
41 use std::path::{Path, PathBuf};
43 use std::sync::mpsc::{channel, Receiver, Sender};
47 const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
49 /// What kind of object file to emit.
50 #[derive(Clone, Copy, PartialEq)]
55 // Just uncompressed llvm bitcode. Provides easy compatibility with
56 // emscripten's ecc compiler, when used as the linker.
59 // Object code, possibly augmented with a bitcode section.
60 ObjectCode(BitcodeSection),
63 /// What kind of llvm bitcode section to embed in an object file.
64 #[derive(Clone, Copy, PartialEq)]
65 pub enum BitcodeSection {
66 // No bitcode section.
69 // A full, uncompressed bitcode section.
73 /// Module-specific configuration for `optimize_and_codegen`.
74 pub struct ModuleConfig {
75 /// Names of additional optimization passes to run.
76 pub passes: Vec<String>,
77 /// Some(level) to optimize at a certain level, or None to run
78 /// absolutely no optimizations (used for the metadata module).
79 pub opt_level: Option<config::OptLevel>,
81 /// Some(level) to optimize binary size, or None to not affect program size.
82 pub opt_size: Option<config::OptLevel>,
84 pub pgo_gen: SwitchWithOptPath,
85 pub pgo_use: Option<PathBuf>,
87 pub sanitizer: SanitizerSet,
88 pub sanitizer_recover: SanitizerSet,
89 pub sanitizer_memory_track_origins: usize,
91 // Flags indicating which outputs to produce.
92 pub emit_pre_lto_bc: bool,
93 pub emit_no_opt_bc: bool,
97 pub emit_obj: EmitObj,
98 pub bc_cmdline: String,
100 // Miscellaneous flags. These are mostly copied from command-line
102 pub verify_llvm_ir: bool,
103 pub no_prepopulate_passes: bool,
104 pub no_builtins: bool,
105 pub time_module: bool,
106 pub vectorize_loop: bool,
107 pub vectorize_slp: bool,
108 pub merge_functions: bool,
109 pub inline_threshold: Option<usize>,
110 pub new_llvm_pass_manager: bool,
111 pub emit_lifetime_markers: bool,
119 is_compiler_builtins: bool,
121 // If it's a regular module, use `$regular`, otherwise use `$other`.
122 // `$regular` and `$other` are evaluated lazily.
123 macro_rules! if_regular {
124 ($regular: expr, $other: expr) => {
125 if let ModuleKind::Regular = kind { $regular } else { $other }
129 let opt_level_and_size = if_regular!(Some(sess.opts.optimize), None);
131 let save_temps = sess.opts.cg.save_temps;
133 let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
135 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
136 ModuleKind::Allocator => false,
137 ModuleKind::Metadata => sess.opts.output_types.contains_key(&OutputType::Metadata),
140 let emit_obj = if !should_emit_obj {
142 } else if sess.target.obj_is_bitcode
143 || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
145 // This case is selected if the target uses objects as bitcode, or
146 // if linker plugin LTO is enabled. In the linker plugin LTO case
147 // the assumption is that the final link-step will read the bitcode
148 // and convert it to object code. This may be done by either the
149 // native linker or rustc itself.
151 // Note, however, that the linker-plugin-lto requested here is
152 // explicitly ignored for `#![no_builtins]` crates. These crates are
153 // specifically ignored by rustc's LTO passes and wouldn't work if
154 // loaded into the linker. These crates define symbols that LLVM
155 // lowers intrinsics to, and these symbol dependencies aren't known
156 // until after codegen. As a result any crate marked
157 // `#![no_builtins]` is assumed to not participate in LTO and
158 // instead goes on to generate object code.
160 } else if need_bitcode_in_object(sess) {
161 EmitObj::ObjectCode(BitcodeSection::Full)
163 EmitObj::ObjectCode(BitcodeSection::None)
169 let mut passes = sess.opts.cg.passes.clone();
170 // compiler_builtins overrides the codegen-units settings,
171 // which is incompatible with -Zprofile which requires that
172 // only a single codegen unit is used per crate.
173 if sess.opts.debugging_opts.profile && !is_compiler_builtins {
174 passes.push("insert-gcov-profiling".to_owned());
177 // The rustc option `-Zinstrument_coverage` injects intrinsic calls to
178 // `llvm.instrprof.increment()`, which requires the LLVM `instrprof` pass.
179 if sess.opts.debugging_opts.instrument_coverage {
180 passes.push("instrprof".to_owned());
187 opt_level: opt_level_and_size,
188 opt_size: opt_level_and_size,
190 pgo_gen: if_regular!(
191 sess.opts.cg.profile_generate.clone(),
192 SwitchWithOptPath::Disabled
194 pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
196 sanitizer: if_regular!(sess.opts.debugging_opts.sanitizer, SanitizerSet::empty()),
197 sanitizer_recover: if_regular!(
198 sess.opts.debugging_opts.sanitizer_recover,
199 SanitizerSet::empty()
201 sanitizer_memory_track_origins: if_regular!(
202 sess.opts.debugging_opts.sanitizer_memory_track_origins,
206 emit_pre_lto_bc: if_regular!(
207 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
210 emit_no_opt_bc: if_regular!(save_temps, false),
211 emit_bc: if_regular!(
212 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
215 emit_ir: if_regular!(
216 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
219 emit_asm: if_regular!(
220 sess.opts.output_types.contains_key(&OutputType::Assembly),
224 bc_cmdline: sess.target.bitcode_llvm_cmdline.clone(),
226 verify_llvm_ir: sess.verify_llvm_ir(),
227 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
228 no_builtins: no_builtins || sess.target.no_builtins,
230 // Exclude metadata and allocator modules from time_passes output,
231 // since they throw off the "LLVM passes" measurement.
232 time_module: if_regular!(true, false),
234 // Copy what clang does by turning on loop vectorization at O2 and
235 // slp vectorization at O3.
236 vectorize_loop: !sess.opts.cg.no_vectorize_loops
237 && (sess.opts.optimize == config::OptLevel::Default
238 || sess.opts.optimize == config::OptLevel::Aggressive),
239 vectorize_slp: !sess.opts.cg.no_vectorize_slp
240 && sess.opts.optimize == config::OptLevel::Aggressive,
242 // Some targets (namely, NVPTX) interact badly with the
243 // MergeFunctions pass. This is because MergeFunctions can generate
244 // new function calls which may interfere with the target calling
245 // convention; e.g. for the NVPTX target, PTX kernels should not
246 // call other PTX kernels. MergeFunctions can also be configured to
247 // generate aliases instead, but aliases are not supported by some
248 // backends (again, NVPTX). Therefore, allow targets to opt out of
249 // the MergeFunctions pass, but otherwise keep the pass enabled (at
250 // O2 and O3) since it can be useful for reducing code size.
251 merge_functions: match sess
255 .unwrap_or(sess.target.merge_functions)
257 MergeFunctions::Disabled => false,
258 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
259 sess.opts.optimize == config::OptLevel::Default
260 || sess.opts.optimize == config::OptLevel::Aggressive
264 inline_threshold: sess.opts.cg.inline_threshold,
265 new_llvm_pass_manager: sess.opts.debugging_opts.new_llvm_pass_manager,
266 emit_lifetime_markers: sess.emit_lifetime_markers(),
270 pub fn bitcode_needed(&self) -> bool {
272 || self.emit_obj == EmitObj::Bitcode
273 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
277 /// Configuration passed to the function returned by the `target_machine_factory`.
278 pub struct TargetMachineFactoryConfig {
279 /// Split DWARF is enabled in LLVM by checking that `TM.MCOptions.SplitDwarfFile` isn't empty,
280 /// so the path to the dwarf object has to be provided when we create the target machine.
281 /// This can be ignored by backends which do not need it for their Split DWARF support.
282 pub split_dwarf_file: Option<PathBuf>,
285 impl TargetMachineFactoryConfig {
287 cgcx: &CodegenContext<impl WriteBackendMethods>,
289 ) -> TargetMachineFactoryConfig {
290 let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
291 cgcx.output_filenames.split_dwarf_path(cgcx.split_debuginfo, Some(module_name))
295 TargetMachineFactoryConfig { split_dwarf_file }
299 pub type TargetMachineFactoryFn<B> = Arc<
300 dyn Fn(TargetMachineFactoryConfig) -> Result<<B as WriteBackendMethods>::TargetMachine, String>
305 pub type ExportedSymbols = FxHashMap<CrateNum, Arc<Vec<(String, SymbolExportLevel)>>>;
307 /// Additional resources used by optimize_and_codegen (not module specific)
309 pub struct CodegenContext<B: WriteBackendMethods> {
310 // Resources needed when running LTO
312 pub prof: SelfProfilerRef,
314 pub no_landing_pads: bool,
315 pub save_temps: bool,
316 pub fewer_names: bool,
317 pub exported_symbols: Option<Arc<ExportedSymbols>>,
318 pub opts: Arc<config::Options>,
319 pub crate_types: Vec<CrateType>,
320 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
321 pub output_filenames: Arc<OutputFilenames>,
322 pub regular_module_config: Arc<ModuleConfig>,
323 pub metadata_module_config: Arc<ModuleConfig>,
324 pub allocator_module_config: Arc<ModuleConfig>,
325 pub tm_factory: TargetMachineFactoryFn<B>,
326 pub msvc_imps_needed: bool,
327 pub is_pe_coff: bool,
328 pub target_can_use_split_dwarf: bool,
329 pub target_pointer_width: u32,
330 pub target_arch: String,
331 pub debuginfo: config::DebugInfo,
332 pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
334 // Number of cgus excluding the allocator/metadata modules
335 pub total_cgus: usize,
336 // Handler to use for diagnostics produced during codegen.
337 pub diag_emitter: SharedEmitter,
338 // LLVM optimizations for which we want to print remarks.
340 // Worker thread number
342 // The incremental compilation session directory, or None if we are not
343 // compiling incrementally
344 pub incr_comp_session_dir: Option<PathBuf>,
345 // Used to update CGU re-use information during the thinlto phase.
346 pub cgu_reuse_tracker: CguReuseTracker,
347 // Channel back to the main control thread to send messages to
348 pub coordinator_send: Sender<Box<dyn Any + Send>>,
351 impl<B: WriteBackendMethods> CodegenContext<B> {
352 pub fn create_diag_handler(&self) -> Handler {
353 Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
356 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
358 ModuleKind::Regular => &self.regular_module_config,
359 ModuleKind::Metadata => &self.metadata_module_config,
360 ModuleKind::Allocator => &self.allocator_module_config,
365 fn generate_lto_work<B: ExtraBackendMethods>(
366 cgcx: &CodegenContext<B>,
367 needs_fat_lto: Vec<FatLTOInput<B>>,
368 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
369 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
370 ) -> Vec<(WorkItem<B>, u64)> {
371 let _prof_timer = cgcx.prof.generic_activity("codegen_generate_lto_work");
373 let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
374 assert!(needs_thin_lto.is_empty());
376 B::run_fat_lto(cgcx, needs_fat_lto, import_only_modules).unwrap_or_else(|e| e.raise());
377 (vec![lto_module], vec![])
379 assert!(needs_fat_lto.is_empty());
380 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules).unwrap_or_else(|e| e.raise())
386 let cost = module.cost();
387 (WorkItem::LTO(module), cost)
389 .chain(copy_jobs.into_iter().map(|wp| {
391 WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
392 name: wp.cgu_name.clone(),
401 pub struct CompiledModules {
402 pub modules: Vec<CompiledModule>,
403 pub metadata_module: Option<CompiledModule>,
404 pub allocator_module: Option<CompiledModule>,
407 fn need_bitcode_in_object(sess: &Session) -> bool {
408 let requested_for_rlib = sess.opts.cg.embed_bitcode
409 && sess.crate_types().contains(&CrateType::Rlib)
410 && sess.opts.output_types.contains_key(&OutputType::Exe);
411 let forced_by_target = sess.target.forces_embed_bitcode;
412 requested_for_rlib || forced_by_target
415 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
416 if sess.opts.incremental.is_none() {
422 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
426 pub fn start_async_codegen<B: ExtraBackendMethods>(
429 metadata: EncodedMetadata,
431 ) -> OngoingCodegen<B> {
432 let (coordinator_send, coordinator_receive) = channel();
435 let crate_name = tcx.crate_name(LOCAL_CRATE);
436 let no_builtins = tcx.sess.contains_name(&tcx.hir().krate().item.attrs, sym::no_builtins);
437 let is_compiler_builtins =
438 tcx.sess.contains_name(&tcx.hir().krate().item.attrs, sym::compiler_builtins);
441 .first_attr_value_str_by_name(&tcx.hir().krate().item.attrs, sym::windows_subsystem);
442 let windows_subsystem = subsystem.map(|subsystem| {
443 if subsystem != sym::windows && subsystem != sym::console {
444 tcx.sess.fatal(&format!(
445 "invalid windows subsystem `{}`, only \
446 `windows` and `console` are allowed",
450 subsystem.to_string()
453 let linker_info = LinkerInfo::new(tcx);
454 let crate_info = CrateInfo::new(tcx);
457 ModuleConfig::new(ModuleKind::Regular, sess, no_builtins, is_compiler_builtins);
458 let metadata_config =
459 ModuleConfig::new(ModuleKind::Metadata, sess, no_builtins, is_compiler_builtins);
460 let allocator_config =
461 ModuleConfig::new(ModuleKind::Allocator, sess, no_builtins, is_compiler_builtins);
463 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
464 let (codegen_worker_send, codegen_worker_receive) = channel();
466 let coordinator_thread = start_executing_work(
474 sess.jobserver.clone(),
475 Arc::new(regular_config),
476 Arc::new(metadata_config),
477 Arc::new(allocator_config),
478 coordinator_send.clone(),
490 codegen_worker_receive,
492 future: coordinator_thread,
493 output_filenames: tcx.output_filenames(LOCAL_CRATE),
497 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
499 compiled_modules: &CompiledModules,
500 ) -> FxHashMap<WorkProductId, WorkProduct> {
501 let mut work_products = FxHashMap::default();
503 if sess.opts.incremental.is_none() {
504 return work_products;
507 let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
509 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
510 let path = module.object.as_ref().cloned();
512 if let Some((id, product)) =
513 copy_cgu_workproduct_to_incr_comp_cache_dir(sess, &module.name, &path)
515 work_products.insert(id, product);
522 fn produce_final_output_artifacts(
524 compiled_modules: &CompiledModules,
525 crate_output: &OutputFilenames,
527 let mut user_wants_bitcode = false;
528 let mut user_wants_objects = false;
530 // Produce final compile outputs.
531 let copy_gracefully = |from: &Path, to: &Path| {
532 if let Err(e) = fs::copy(from, to) {
533 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
537 let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
538 if compiled_modules.modules.len() == 1 {
539 // 1) Only one codegen unit. In this case it's no difficulty
540 // to copy `foo.0.x` to `foo.x`.
541 let module_name = Some(&compiled_modules.modules[0].name[..]);
542 let path = crate_output.temp_path(output_type, module_name);
543 copy_gracefully(&path, &crate_output.path(output_type));
544 if !sess.opts.cg.save_temps && !keep_numbered {
545 // The user just wants `foo.x`, not `foo.#module-name#.x`.
546 ensure_removed(sess.diagnostic(), &path);
549 let ext = crate_output
550 .temp_path(output_type, None)
557 if crate_output.outputs.contains_key(&output_type) {
558 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
559 // no good solution for this case, so warn the user.
561 "ignoring emit path because multiple .{} files \
565 } else if crate_output.single_output_file.is_some() {
566 // 3) Multiple codegen units, with `-o some_name`. We have
567 // no good solution for this case, so warn the user.
569 "ignoring -o because multiple .{} files \
574 // 4) Multiple codegen units, but no explicit name. We
575 // just leave the `foo.0.x` files in place.
576 // (We don't have to do any work in this case.)
581 // Flag to indicate whether the user explicitly requested bitcode.
582 // Otherwise, we produced it only as a temporary output, and will need
584 for output_type in crate_output.outputs.keys() {
586 OutputType::Bitcode => {
587 user_wants_bitcode = true;
588 // Copy to .bc, but always keep the .0.bc. There is a later
589 // check to figure out if we should delete .0.bc files, or keep
590 // them for making an rlib.
591 copy_if_one_unit(OutputType::Bitcode, true);
593 OutputType::LlvmAssembly => {
594 copy_if_one_unit(OutputType::LlvmAssembly, false);
596 OutputType::Assembly => {
597 copy_if_one_unit(OutputType::Assembly, false);
599 OutputType::Object => {
600 user_wants_objects = true;
601 copy_if_one_unit(OutputType::Object, true);
603 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
607 // Clean up unwanted temporary files.
609 // We create the following files by default:
610 // - #crate#.#module-name#.bc
611 // - #crate#.#module-name#.o
612 // - #crate#.crate.metadata.bc
613 // - #crate#.crate.metadata.o
614 // - #crate#.o (linked from crate.##.o)
615 // - #crate#.bc (copied from crate.##.bc)
616 // We may create additional files if requested by the user (through
617 // `-C save-temps` or `--emit=` flags).
619 if !sess.opts.cg.save_temps {
620 // Remove the temporary .#module-name#.o objects. If the user didn't
621 // explicitly request bitcode (with --emit=bc), and the bitcode is not
622 // needed for building an rlib, then we must remove .#module-name#.bc as
625 // Specific rules for keeping .#module-name#.bc:
626 // - If the user requested bitcode (`user_wants_bitcode`), and
627 // codegen_units > 1, then keep it.
628 // - If the user requested bitcode but codegen_units == 1, then we
629 // can toss .#module-name#.bc because we copied it to .bc earlier.
630 // - If we're not building an rlib and the user didn't request
631 // bitcode, then delete .#module-name#.bc.
632 // If you change how this works, also update back::link::link_rlib,
633 // where .#module-name#.bc files are (maybe) deleted after making an
635 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
637 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
639 let keep_numbered_objects =
640 needs_crate_object || (user_wants_objects && sess.codegen_units() > 1);
642 for module in compiled_modules.modules.iter() {
643 if let Some(ref path) = module.object {
644 if !keep_numbered_objects {
645 ensure_removed(sess.diagnostic(), path);
649 if let Some(ref path) = module.dwarf_object {
650 if !keep_numbered_objects {
651 ensure_removed(sess.diagnostic(), path);
655 if let Some(ref path) = module.bytecode {
656 if !keep_numbered_bitcode {
657 ensure_removed(sess.diagnostic(), path);
662 if !user_wants_bitcode {
663 if let Some(ref metadata_module) = compiled_modules.metadata_module {
664 if let Some(ref path) = metadata_module.bytecode {
665 ensure_removed(sess.diagnostic(), &path);
669 if let Some(ref allocator_module) = compiled_modules.allocator_module {
670 if let Some(ref path) = allocator_module.bytecode {
671 ensure_removed(sess.diagnostic(), path);
677 // We leave the following files around by default:
679 // - #crate#.crate.metadata.o
681 // These are used in linking steps and will be cleaned up afterward.
684 pub enum WorkItem<B: WriteBackendMethods> {
685 /// Optimize a newly codegened, totally unoptimized module.
686 Optimize(ModuleCodegen<B::Module>),
687 /// Copy the post-LTO artifacts from the incremental cache to the output
689 CopyPostLtoArtifacts(CachedModuleCodegen),
690 /// Performs (Thin)LTO on the given module.
691 LTO(lto::LtoModuleCodegen<B>),
694 impl<B: WriteBackendMethods> WorkItem<B> {
695 pub fn module_kind(&self) -> ModuleKind {
697 WorkItem::Optimize(ref m) => m.kind,
698 WorkItem::CopyPostLtoArtifacts(_) | WorkItem::LTO(_) => ModuleKind::Regular,
702 fn start_profiling<'a>(&self, cgcx: &'a CodegenContext<B>) -> TimingGuard<'a> {
704 WorkItem::Optimize(ref m) => {
705 cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &m.name[..])
707 WorkItem::CopyPostLtoArtifacts(ref m) => cgcx
709 .generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &m.name[..]),
710 WorkItem::LTO(ref m) => {
711 cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name())
716 /// Generate a short description of this work item suitable for use as a thread name.
717 fn short_description(&self) -> String {
718 // `pthread_setname()` on *nix is limited to 15 characters and longer names are ignored.
719 // Use very short descriptions in this case to maximize the space available for the module name.
720 // Windows does not have that limitation so use slightly more descriptive names there.
722 WorkItem::Optimize(m) => {
724 return format!("optimize module {}", m.name);
726 return format!("opt {}", m.name);
728 WorkItem::CopyPostLtoArtifacts(m) => {
730 return format!("copy LTO artifacts for {}", m.name);
732 return format!("copy {}", m.name);
734 WorkItem::LTO(m) => {
736 return format!("LTO module {}", m.name());
738 return format!("LTO {}", m.name());
744 enum WorkItemResult<B: WriteBackendMethods> {
745 Compiled(CompiledModule),
746 NeedsLink(ModuleCodegen<B::Module>),
747 NeedsFatLTO(FatLTOInput<B>),
748 NeedsThinLTO(String, B::ThinBuffer),
751 pub enum FatLTOInput<B: WriteBackendMethods> {
752 Serialized { name: String, buffer: B::ModuleBuffer },
753 InMemory(ModuleCodegen<B::Module>),
756 fn execute_work_item<B: ExtraBackendMethods>(
757 cgcx: &CodegenContext<B>,
758 work_item: WorkItem<B>,
759 ) -> Result<WorkItemResult<B>, FatalError> {
760 let module_config = cgcx.config(work_item.module_kind());
763 WorkItem::Optimize(module) => execute_optimize_work_item(cgcx, module, module_config),
764 WorkItem::CopyPostLtoArtifacts(module) => {
765 Ok(execute_copy_from_cache_work_item(cgcx, module, module_config))
767 WorkItem::LTO(module) => execute_lto_work_item(cgcx, module, module_config),
771 // Actual LTO type we end up choosing based on multiple factors.
772 pub enum ComputedLtoType {
778 pub fn compute_per_cgu_lto_type(
780 opts: &config::Options,
781 sess_crate_types: &[CrateType],
782 module_kind: ModuleKind,
783 ) -> ComputedLtoType {
784 // Metadata modules never participate in LTO regardless of the lto
786 if module_kind == ModuleKind::Metadata {
787 return ComputedLtoType::No;
790 // If the linker does LTO, we don't have to do it. Note that we
791 // keep doing full LTO, if it is requested, as not to break the
792 // assumption that the output will be a single module.
793 let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
795 // When we're automatically doing ThinLTO for multi-codegen-unit
796 // builds we don't actually want to LTO the allocator modules if
797 // it shows up. This is due to various linker shenanigans that
798 // we'll encounter later.
799 let is_allocator = module_kind == ModuleKind::Allocator;
801 // We ignore a request for full crate grath LTO if the cate type
802 // is only an rlib, as there is no full crate graph to process,
803 // that'll happen later.
805 // This use case currently comes up primarily for targets that
806 // require LTO so the request for LTO is always unconditionally
807 // passed down to the backend, but we don't actually want to do
808 // anything about it yet until we've got a final product.
809 let is_rlib = sess_crate_types.len() == 1 && sess_crate_types[0] == CrateType::Rlib;
812 Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
813 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
814 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
815 _ => ComputedLtoType::No,
819 fn execute_optimize_work_item<B: ExtraBackendMethods>(
820 cgcx: &CodegenContext<B>,
821 module: ModuleCodegen<B::Module>,
822 module_config: &ModuleConfig,
823 ) -> Result<WorkItemResult<B>, FatalError> {
824 let diag_handler = cgcx.create_diag_handler();
827 B::optimize(cgcx, &diag_handler, &module, module_config)?;
830 // After we've done the initial round of optimizations we need to
831 // decide whether to synchronously codegen this module or ship it
832 // back to the coordinator thread for further LTO processing (which
833 // has to wait for all the initial modules to be optimized).
835 let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
837 // If we're doing some form of incremental LTO then we need to be sure to
838 // save our module to disk first.
839 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
840 let filename = pre_lto_bitcode_filename(&module.name);
841 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
847 ComputedLtoType::No => finish_intra_module_work(cgcx, module, module_config),
848 ComputedLtoType::Thin => {
849 let (name, thin_buffer) = B::prepare_thin(module);
850 if let Some(path) = bitcode {
851 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
852 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
855 Ok(WorkItemResult::NeedsThinLTO(name, thin_buffer))
857 ComputedLtoType::Fat => match bitcode {
859 let (name, buffer) = B::serialize_module(module);
860 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
861 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
863 Ok(WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer }))
865 None => Ok(WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module))),
870 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
871 cgcx: &CodegenContext<B>,
872 module: CachedModuleCodegen,
873 module_config: &ModuleConfig,
874 ) -> WorkItemResult<B> {
875 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
876 let mut object = None;
877 if let Some(saved_file) = module.source.saved_file {
878 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, Some(&module.name));
879 object = Some(obj_out.clone());
880 let source_file = in_incr_comp_dir(&incr_comp_session_dir, &saved_file);
882 "copying pre-existing module `{}` from {:?} to {}",
887 if let Err(err) = link_or_copy(&source_file, &obj_out) {
888 let diag_handler = cgcx.create_diag_handler();
889 diag_handler.err(&format!(
890 "unable to copy {} to {}: {}",
891 source_file.display(),
898 assert_eq!(object.is_some(), module_config.emit_obj != EmitObj::None);
900 WorkItemResult::Compiled(CompiledModule {
902 kind: ModuleKind::Regular,
909 fn execute_lto_work_item<B: ExtraBackendMethods>(
910 cgcx: &CodegenContext<B>,
911 mut module: lto::LtoModuleCodegen<B>,
912 module_config: &ModuleConfig,
913 ) -> Result<WorkItemResult<B>, FatalError> {
914 let module = unsafe { module.optimize(cgcx)? };
915 finish_intra_module_work(cgcx, module, module_config)
918 fn finish_intra_module_work<B: ExtraBackendMethods>(
919 cgcx: &CodegenContext<B>,
920 module: ModuleCodegen<B::Module>,
921 module_config: &ModuleConfig,
922 ) -> Result<WorkItemResult<B>, FatalError> {
923 let diag_handler = cgcx.create_diag_handler();
925 if !cgcx.opts.debugging_opts.combine_cgu
926 || module.kind == ModuleKind::Metadata
927 || module.kind == ModuleKind::Allocator
929 let module = unsafe { B::codegen(cgcx, &diag_handler, module, module_config)? };
930 Ok(WorkItemResult::Compiled(module))
932 Ok(WorkItemResult::NeedsLink(module))
936 pub enum Message<B: WriteBackendMethods> {
937 Token(io::Result<Acquired>),
939 result: FatLTOInput<B>,
944 thin_buffer: B::ThinBuffer,
948 module: ModuleCodegen<B::Module>,
952 result: Result<CompiledModule, Option<WorkerFatalError>>,
956 llvm_work_item: WorkItem<B>,
959 AddImportOnlyModule {
960 module_data: SerializedModule<B::ModuleBuffer>,
961 work_product: WorkProduct,
970 code: Option<DiagnosticId>,
974 #[derive(PartialEq, Clone, Copy, Debug)]
975 enum MainThreadWorkerState {
981 fn start_executing_work<B: ExtraBackendMethods>(
984 crate_info: &CrateInfo,
985 shared_emitter: SharedEmitter,
986 codegen_worker_send: Sender<Message<B>>,
987 coordinator_receive: Receiver<Box<dyn Any + Send>>,
990 regular_config: Arc<ModuleConfig>,
991 metadata_config: Arc<ModuleConfig>,
992 allocator_config: Arc<ModuleConfig>,
993 tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
994 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
995 let coordinator_send = tx_to_llvm_workers;
998 // Compute the set of symbols we need to retain when doing LTO (if we need to)
999 let exported_symbols = {
1000 let mut exported_symbols = FxHashMap::default();
1002 let copy_symbols = |cnum| {
1004 .exported_symbols(cnum)
1006 .map(|&(s, lvl)| (symbol_name_for_instance_in_crate(tcx, s, cnum), lvl))
1014 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1015 Some(Arc::new(exported_symbols))
1017 Lto::Fat | Lto::Thin => {
1018 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1019 for &cnum in tcx.crates().iter() {
1020 exported_symbols.insert(cnum, copy_symbols(cnum));
1022 Some(Arc::new(exported_symbols))
1027 // First up, convert our jobserver into a helper thread so we can use normal
1028 // mpsc channels to manage our messages and such.
1029 // After we've requested tokens then we'll, when we can,
1030 // get tokens on `coordinator_receive` which will
1031 // get managed in the main loop below.
1032 let coordinator_send2 = coordinator_send.clone();
1033 let helper = jobserver
1034 .into_helper_thread(move |token| {
1035 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
1037 .expect("failed to spawn helper thread");
1039 let mut each_linked_rlib_for_lto = Vec::new();
1040 drop(link::each_linked_rlib(crate_info, &mut |cnum, path| {
1041 if link::ignored_for_lto(sess, crate_info, cnum) {
1044 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1047 let ol = if tcx.sess.opts.debugging_opts.no_codegen
1048 || !tcx.sess.opts.output_types.should_codegen()
1050 // If we know that we won’t be doing codegen, create target machines without optimisation.
1051 config::OptLevel::No
1053 tcx.backend_optimization_level(LOCAL_CRATE)
1055 let cgcx = CodegenContext::<B> {
1056 backend: backend.clone(),
1057 crate_types: sess.crate_types().to_vec(),
1058 each_linked_rlib_for_lto,
1060 no_landing_pads: sess.panic_strategy() == PanicStrategy::Abort,
1061 fewer_names: sess.fewer_names(),
1062 save_temps: sess.opts.cg.save_temps,
1063 opts: Arc::new(sess.opts.clone()),
1064 prof: sess.prof.clone(),
1066 remark: sess.opts.cg.remark.clone(),
1068 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1069 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1071 diag_emitter: shared_emitter.clone(),
1072 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1073 regular_module_config: regular_config,
1074 metadata_module_config: metadata_config,
1075 allocator_module_config: allocator_config,
1076 tm_factory: backend.target_machine_factory(tcx.sess, ol),
1078 msvc_imps_needed: msvc_imps_needed(tcx),
1079 is_pe_coff: tcx.sess.target.is_like_windows,
1080 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1081 target_pointer_width: tcx.sess.target.pointer_width,
1082 target_arch: tcx.sess.target.arch.clone(),
1083 debuginfo: tcx.sess.opts.debuginfo,
1084 split_debuginfo: tcx.sess.split_debuginfo(),
1087 // This is the "main loop" of parallel work happening for parallel codegen.
1088 // It's here that we manage parallelism, schedule work, and work with
1089 // messages coming from clients.
1091 // There are a few environmental pre-conditions that shape how the system
1094 // - Error reporting only can happen on the main thread because that's the
1095 // only place where we have access to the compiler `Session`.
1096 // - LLVM work can be done on any thread.
1097 // - Codegen can only happen on the main thread.
1098 // - Each thread doing substantial work most be in possession of a `Token`
1099 // from the `Jobserver`.
1100 // - The compiler process always holds one `Token`. Any additional `Tokens`
1101 // have to be requested from the `Jobserver`.
1105 // The error reporting restriction is handled separately from the rest: We
1106 // set up a `SharedEmitter` the holds an open channel to the main thread.
1107 // When an error occurs on any thread, the shared emitter will send the
1108 // error message to the receiver main thread (`SharedEmitterMain`). The
1109 // main thread will periodically query this error message queue and emit
1110 // any error messages it has received. It might even abort compilation if
1111 // has received a fatal error. In this case we rely on all other threads
1112 // being torn down automatically with the main thread.
1113 // Since the main thread will often be busy doing codegen work, error
1114 // reporting will be somewhat delayed, since the message queue can only be
1115 // checked in between to work packages.
1117 // Work Processing Infrastructure
1118 // ==============================
1119 // The work processing infrastructure knows three major actors:
1121 // - the coordinator thread,
1122 // - the main thread, and
1123 // - LLVM worker threads
1125 // The coordinator thread is running a message loop. It instructs the main
1126 // thread about what work to do when, and it will spawn off LLVM worker
1127 // threads as open LLVM WorkItems become available.
1129 // The job of the main thread is to codegen CGUs into LLVM work package
1130 // (since the main thread is the only thread that can do this). The main
1131 // thread will block until it receives a message from the coordinator, upon
1132 // which it will codegen one CGU, send it to the coordinator and block
1133 // again. This way the coordinator can control what the main thread is
1136 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1137 // available, it will spawn off a new LLVM worker thread and let it process
1138 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1139 // it will just shut down, which also frees all resources associated with
1140 // the given LLVM module, and sends a message to the coordinator that the
1141 // has been completed.
1145 // The scheduler's goal is to minimize the time it takes to complete all
1146 // work there is, however, we also want to keep memory consumption low
1147 // if possible. These two goals are at odds with each other: If memory
1148 // consumption were not an issue, we could just let the main thread produce
1149 // LLVM WorkItems at full speed, assuring maximal utilization of
1150 // Tokens/LLVM worker threads. However, since codegen usual is faster
1151 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1152 // WorkItem potentially holds on to a substantial amount of memory.
1154 // So the actual goal is to always produce just enough LLVM WorkItems as
1155 // not to starve our LLVM worker threads. That means, once we have enough
1156 // WorkItems in our queue, we can block the main thread, so it does not
1157 // produce more until we need them.
1159 // Doing LLVM Work on the Main Thread
1160 // ----------------------------------
1161 // Since the main thread owns the compiler processes implicit `Token`, it is
1162 // wasteful to keep it blocked without doing any work. Therefore, what we do
1163 // in this case is: We spawn off an additional LLVM worker thread that helps
1164 // reduce the queue. The work it is doing corresponds to the implicit
1165 // `Token`. The coordinator will mark the main thread as being busy with
1166 // LLVM work. (The actual work happens on another OS thread but we just care
1167 // about `Tokens`, not actual threads).
1169 // When any LLVM worker thread finishes while the main thread is marked as
1170 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1171 // of the just finished thread to the LLVM worker thread that is working on
1172 // behalf of the main thread's implicit Token, thus freeing up the main
1173 // thread again. The coordinator can then again decide what the main thread
1174 // should do. This allows the coordinator to make decisions at more points
1177 // Striking a Balance between Throughput and Memory Consumption
1178 // ------------------------------------------------------------
1179 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1180 // memory consumption as low as possible, are in conflict with each other,
1181 // we have to find a trade off between them. Right now, the goal is to keep
1182 // all workers busy, which means that no worker should find the queue empty
1183 // when it is ready to start.
1184 // How do we do achieve this? Good question :) We actually never know how
1185 // many `Tokens` are potentially available so it's hard to say how much to
1186 // fill up the queue before switching the main thread to LLVM work. Also we
1187 // currently don't have a means to estimate how long a running LLVM worker
1188 // will still be busy with it's current WorkItem. However, we know the
1189 // maximal count of available Tokens that makes sense (=the number of CPU
1190 // cores), so we can take a conservative guess. The heuristic we use here
1191 // is implemented in the `queue_full_enough()` function.
1193 // Some Background on Jobservers
1194 // -----------------------------
1195 // It's worth also touching on the management of parallelism here. We don't
1196 // want to just spawn a thread per work item because while that's optimal
1197 // parallelism it may overload a system with too many threads or violate our
1198 // configuration for the maximum amount of cpu to use for this process. To
1199 // manage this we use the `jobserver` crate.
1201 // Job servers are an artifact of GNU make and are used to manage
1202 // parallelism between processes. A jobserver is a glorified IPC semaphore
1203 // basically. Whenever we want to run some work we acquire the semaphore,
1204 // and whenever we're done with that work we release the semaphore. In this
1205 // manner we can ensure that the maximum number of parallel workers is
1206 // capped at any one point in time.
1208 // LTO and the coordinator thread
1209 // ------------------------------
1211 // The final job the coordinator thread is responsible for is managing LTO
1212 // and how that works. When LTO is requested what we'll to is collect all
1213 // optimized LLVM modules into a local vector on the coordinator. Once all
1214 // modules have been codegened and optimized we hand this to the `lto`
1215 // module for further optimization. The `lto` module will return back a list
1216 // of more modules to work on, which the coordinator will continue to spawn
1219 // Each LLVM module is automatically sent back to the coordinator for LTO if
1220 // necessary. There's already optimizations in place to avoid sending work
1221 // back to the coordinator if LTO isn't requested.
1222 return thread::spawn(move || {
1223 let mut worker_id_counter = 0;
1224 let mut free_worker_ids = Vec::new();
1225 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1226 if let Some(id) = free_worker_ids.pop() {
1229 let id = worker_id_counter;
1230 worker_id_counter += 1;
1235 // This is where we collect codegen units that have gone all the way
1236 // through codegen and LLVM.
1237 let mut compiled_modules = vec![];
1238 let mut compiled_metadata_module = None;
1239 let mut compiled_allocator_module = None;
1240 let mut needs_link = Vec::new();
1241 let mut needs_fat_lto = Vec::new();
1242 let mut needs_thin_lto = Vec::new();
1243 let mut lto_import_only_modules = Vec::new();
1244 let mut started_lto = false;
1245 let mut codegen_aborted = false;
1247 // This flag tracks whether all items have gone through codegens
1248 let mut codegen_done = false;
1250 // This is the queue of LLVM work items that still need processing.
1251 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1253 // This are the Jobserver Tokens we currently hold. Does not include
1254 // the implicit Token the compiler process owns no matter what.
1255 let mut tokens = Vec::new();
1257 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1258 let mut running = 0;
1260 let prof = &cgcx.prof;
1261 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1263 // Run the message loop while there's still anything that needs message
1264 // processing. Note that as soon as codegen is aborted we simply want to
1265 // wait for all existing work to finish, so many of the conditions here
1266 // only apply if codegen hasn't been aborted as they represent pending
1270 || (!codegen_aborted
1271 && !(work_items.is_empty()
1272 && needs_fat_lto.is_empty()
1273 && needs_thin_lto.is_empty()
1274 && lto_import_only_modules.is_empty()
1275 && main_thread_worker_state == MainThreadWorkerState::Idle))
1277 // While there are still CGUs to be codegened, the coordinator has
1278 // to decide how to utilize the compiler processes implicit Token:
1279 // For codegenning more CGU or for running them through LLVM.
1281 if main_thread_worker_state == MainThreadWorkerState::Idle {
1282 // Compute the number of workers that will be running once we've taken as many
1283 // items from the work queue as we can, plus one for the main thread. It's not
1284 // critically important that we use this instead of just `running`, but it
1285 // prevents the `queue_full_enough` heuristic from fluctuating just because a
1286 // worker finished up and we decreased the `running` count, even though we're
1287 // just going to increase it right after this when we put a new worker to work.
1288 let extra_tokens = tokens.len().checked_sub(running).unwrap();
1289 let additional_running = std::cmp::min(extra_tokens, work_items.len());
1290 let anticipated_running = running + additional_running + 1;
1292 if !queue_full_enough(work_items.len(), anticipated_running) {
1293 // The queue is not full enough, codegen more items:
1294 if codegen_worker_send.send(Message::CodegenItem).is_err() {
1295 panic!("Could not send Message::CodegenItem to main thread")
1297 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1299 // The queue is full enough to not let the worker
1300 // threads starve. Use the implicit Token to do some
1303 work_items.pop().expect("queue empty - queue_full_enough() broken?");
1304 let cgcx = CodegenContext {
1305 worker: get_worker_id(&mut free_worker_ids),
1308 maybe_start_llvm_timer(
1310 cgcx.config(item.module_kind()),
1311 &mut llvm_start_time,
1313 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1314 spawn_work(cgcx, item);
1317 } else if codegen_aborted {
1318 // don't queue up any more work if codegen was aborted, we're
1319 // just waiting for our existing children to finish
1321 // If we've finished everything related to normal codegen
1322 // then it must be the case that we've got some LTO work to do.
1323 // Perform the serial work here of figuring out what we're
1324 // going to LTO and then push a bunch of work items onto our
1326 if work_items.is_empty()
1328 && main_thread_worker_state == MainThreadWorkerState::Idle
1330 assert!(!started_lto);
1333 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1334 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1335 let import_only_modules = mem::take(&mut lto_import_only_modules);
1338 generate_lto_work(&cgcx, needs_fat_lto, needs_thin_lto, import_only_modules)
1340 let insertion_index = work_items
1341 .binary_search_by_key(&cost, |&(_, cost)| cost)
1342 .unwrap_or_else(|e| e);
1343 work_items.insert(insertion_index, (work, cost));
1344 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1345 helper.request_token();
1350 // In this branch, we know that everything has been codegened,
1351 // so it's just a matter of determining whether the implicit
1352 // Token is free to use for LLVM work.
1353 match main_thread_worker_state {
1354 MainThreadWorkerState::Idle => {
1355 if let Some((item, _)) = work_items.pop() {
1356 let cgcx = CodegenContext {
1357 worker: get_worker_id(&mut free_worker_ids),
1360 maybe_start_llvm_timer(
1362 cgcx.config(item.module_kind()),
1363 &mut llvm_start_time,
1365 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1366 spawn_work(cgcx, item);
1368 // There is no unstarted work, so let the main thread
1369 // take over for a running worker. Otherwise the
1370 // implicit token would just go to waste.
1371 // We reduce the `running` counter by one. The
1372 // `tokens.truncate()` below will take care of
1373 // giving the Token back.
1374 debug_assert!(running > 0);
1376 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1379 MainThreadWorkerState::Codegenning => bug!(
1380 "codegen worker should not be codegenning after \
1381 codegen was already completed"
1383 MainThreadWorkerState::LLVMing => {
1384 // Already making good use of that token
1389 // Spin up what work we can, only doing this while we've got available
1390 // parallelism slots and work left to spawn.
1391 while !codegen_aborted && !work_items.is_empty() && running < tokens.len() {
1392 let (item, _) = work_items.pop().unwrap();
1394 maybe_start_llvm_timer(prof, cgcx.config(item.module_kind()), &mut llvm_start_time);
1397 CodegenContext { worker: get_worker_id(&mut free_worker_ids), ..cgcx.clone() };
1399 spawn_work(cgcx, item);
1403 // Relinquish accidentally acquired extra tokens
1404 tokens.truncate(running);
1406 // If a thread exits successfully then we drop a token associated
1407 // with that worker and update our `running` count. We may later
1408 // re-acquire a token to continue running more work. We may also not
1409 // actually drop a token here if the worker was running with an
1410 // "ephemeral token"
1411 let mut free_worker = |worker_id| {
1412 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1413 main_thread_worker_state = MainThreadWorkerState::Idle;
1418 free_worker_ids.push(worker_id);
1421 let msg = coordinator_receive.recv().unwrap();
1422 match *msg.downcast::<Message<B>>().ok().unwrap() {
1423 // Save the token locally and the next turn of the loop will use
1424 // this to spawn a new unit of work, or it may get dropped
1425 // immediately if we have no more work to spawn.
1426 Message::Token(token) => {
1431 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1432 // If the main thread token is used for LLVM work
1433 // at the moment, we turn that thread into a regular
1434 // LLVM worker thread, so the main thread is free
1435 // to react to codegen demand.
1436 main_thread_worker_state = MainThreadWorkerState::Idle;
1441 let msg = &format!("failed to acquire jobserver token: {}", e);
1442 shared_emitter.fatal(msg);
1443 // Exit the coordinator thread
1449 Message::CodegenDone { llvm_work_item, cost } => {
1450 // We keep the queue sorted by estimated processing cost,
1451 // so that more expensive items are processed earlier. This
1452 // is good for throughput as it gives the main thread more
1453 // time to fill up the queue and it avoids scheduling
1454 // expensive items to the end.
1455 // Note, however, that this is not ideal for memory
1456 // consumption, as LLVM module sizes are not evenly
1458 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1459 let insertion_index = match insertion_index {
1460 Ok(idx) | Err(idx) => idx,
1462 work_items.insert(insertion_index, (llvm_work_item, cost));
1464 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1465 helper.request_token();
1467 assert!(!codegen_aborted);
1468 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1469 main_thread_worker_state = MainThreadWorkerState::Idle;
1472 Message::CodegenComplete => {
1473 codegen_done = true;
1474 assert!(!codegen_aborted);
1475 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1476 main_thread_worker_state = MainThreadWorkerState::Idle;
1479 // If codegen is aborted that means translation was aborted due
1480 // to some normal-ish compiler error. In this situation we want
1481 // to exit as soon as possible, but we want to make sure all
1482 // existing work has finished. Flag codegen as being done, and
1483 // then conditions above will ensure no more work is spawned but
1484 // we'll keep executing this loop until `running` hits 0.
1485 Message::CodegenAborted => {
1486 assert!(!codegen_aborted);
1487 codegen_done = true;
1488 codegen_aborted = true;
1489 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1491 Message::Done { result: Ok(compiled_module), worker_id } => {
1492 free_worker(worker_id);
1493 match compiled_module.kind {
1494 ModuleKind::Regular => {
1495 compiled_modules.push(compiled_module);
1497 ModuleKind::Metadata => {
1498 assert!(compiled_metadata_module.is_none());
1499 compiled_metadata_module = Some(compiled_module);
1501 ModuleKind::Allocator => {
1502 assert!(compiled_allocator_module.is_none());
1503 compiled_allocator_module = Some(compiled_module);
1507 Message::NeedsLink { module, worker_id } => {
1508 free_worker(worker_id);
1509 needs_link.push(module);
1511 Message::NeedsFatLTO { result, worker_id } => {
1512 assert!(!started_lto);
1513 free_worker(worker_id);
1514 needs_fat_lto.push(result);
1516 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1517 assert!(!started_lto);
1518 free_worker(worker_id);
1519 needs_thin_lto.push((name, thin_buffer));
1521 Message::AddImportOnlyModule { module_data, work_product } => {
1522 assert!(!started_lto);
1523 assert!(!codegen_done);
1524 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1525 lto_import_only_modules.push((module_data, work_product));
1526 main_thread_worker_state = MainThreadWorkerState::Idle;
1528 // If the thread failed that means it panicked, so we abort immediately.
1529 Message::Done { result: Err(None), worker_id: _ } => {
1530 bug!("worker thread panicked");
1532 Message::Done { result: Err(Some(WorkerFatalError)), worker_id: _ } => {
1535 Message::CodegenItem => bug!("the coordinator should not receive codegen requests"),
1539 let needs_link = mem::take(&mut needs_link);
1540 if !needs_link.is_empty() {
1541 assert!(compiled_modules.is_empty());
1542 let diag_handler = cgcx.create_diag_handler();
1543 let module = B::run_link(&cgcx, &diag_handler, needs_link).map_err(|_| ())?;
1544 let module = unsafe {
1545 B::codegen(&cgcx, &diag_handler, module, cgcx.config(ModuleKind::Regular))
1548 compiled_modules.push(module);
1551 // Drop to print timings
1552 drop(llvm_start_time);
1554 // Regardless of what order these modules completed in, report them to
1555 // the backend in the same order every time to ensure that we're handing
1556 // out deterministic results.
1557 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1559 Ok(CompiledModules {
1560 modules: compiled_modules,
1561 metadata_module: compiled_metadata_module,
1562 allocator_module: compiled_allocator_module,
1566 // A heuristic that determines if we have enough LLVM WorkItems in the
1567 // queue so that the main thread can do LLVM work instead of codegen
1568 fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1569 // This heuristic scales ahead-of-time codegen according to available
1570 // concurrency, as measured by `workers_running`. The idea is that the
1571 // more concurrency we have available, the more demand there will be for
1572 // work items, and the fuller the queue should be kept to meet demand.
1573 // An important property of this approach is that we codegen ahead of
1574 // time only as much as necessary, so as to keep fewer LLVM modules in
1575 // memory at once, thereby reducing memory consumption.
1577 // When the number of workers running is less than the max concurrency
1578 // available to us, this heuristic can cause us to instruct the main
1579 // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1580 // of codegen, even though it seems like it *should* be codegenning so
1581 // that we can create more work items and spawn more LLVM workers.
1583 // But this is not a problem. When the main thread is told to LLVM,
1584 // according to this heuristic and how work is scheduled, there is
1585 // always at least one item in the queue, and therefore at least one
1586 // pending jobserver token request. If there *is* more concurrency
1587 // available, we will immediately receive a token, which will upgrade
1588 // the main thread's LLVM worker to a real one (conceptually), and free
1589 // up the main thread to codegen if necessary. On the other hand, if
1590 // there isn't more concurrency, then the main thread working on an LLVM
1591 // item is appropriate, as long as the queue is full enough for demand.
1593 // Speaking of which, how full should we keep the queue? Probably less
1594 // full than you'd think. A lot has to go wrong for the queue not to be
1595 // full enough and for that to have a negative effect on compile times.
1597 // Workers are unlikely to finish at exactly the same time, so when one
1598 // finishes and takes another work item off the queue, we often have
1599 // ample time to codegen at that point before the next worker finishes.
1600 // But suppose that codegen takes so long that the workers exhaust the
1601 // queue, and we have one or more workers that have nothing to work on.
1602 // Well, it might not be so bad. Of all the LLVM modules we create and
1603 // optimize, one has to finish last. It's not necessarily the case that
1604 // by losing some concurrency for a moment, we delay the point at which
1605 // that last LLVM module is finished and the rest of compilation can
1606 // proceed. Also, when we can't take advantage of some concurrency, we
1607 // give tokens back to the job server. That enables some other rustc to
1608 // potentially make use of the available concurrency. That could even
1609 // *decrease* overall compile time if we're lucky. But yes, if no other
1610 // rustc can make use of the concurrency, then we've squandered it.
1612 // However, keeping the queue full is also beneficial when we have a
1613 // surge in available concurrency. Then items can be taken from the
1614 // queue immediately, without having to wait for codegen.
1616 // So, the heuristic below tries to keep one item in the queue for every
1617 // four running workers. Based on limited benchmarking, this appears to
1618 // be more than sufficient to avoid increasing compilation times.
1619 let quarter_of_workers = workers_running - 3 * workers_running / 4;
1620 items_in_queue > 0 && items_in_queue >= quarter_of_workers
1623 fn maybe_start_llvm_timer<'a>(
1624 prof: &'a SelfProfilerRef,
1625 config: &ModuleConfig,
1626 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1628 if config.time_module && llvm_start_time.is_none() {
1629 *llvm_start_time = Some(prof.extra_verbose_generic_activity("LLVM_passes", "crate"));
1634 /// `FatalError` is explicitly not `Send`.
1636 pub struct WorkerFatalError;
1638 fn spawn_work<B: ExtraBackendMethods>(cgcx: CodegenContext<B>, work: WorkItem<B>) {
1639 let builder = thread::Builder::new().name(work.short_description());
1642 // Set up a destructor which will fire off a message that we're done as
1644 struct Bomb<B: ExtraBackendMethods> {
1645 coordinator_send: Sender<Box<dyn Any + Send>>,
1646 result: Option<Result<WorkItemResult<B>, FatalError>>,
1649 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1650 fn drop(&mut self) {
1651 let worker_id = self.worker_id;
1652 let msg = match self.result.take() {
1653 Some(Ok(WorkItemResult::Compiled(m))) => {
1654 Message::Done::<B> { result: Ok(m), worker_id }
1656 Some(Ok(WorkItemResult::NeedsLink(m))) => {
1657 Message::NeedsLink::<B> { module: m, worker_id }
1659 Some(Ok(WorkItemResult::NeedsFatLTO(m))) => {
1660 Message::NeedsFatLTO::<B> { result: m, worker_id }
1662 Some(Ok(WorkItemResult::NeedsThinLTO(name, thin_buffer))) => {
1663 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1665 Some(Err(FatalError)) => {
1666 Message::Done::<B> { result: Err(Some(WorkerFatalError)), worker_id }
1668 None => Message::Done::<B> { result: Err(None), worker_id },
1670 drop(self.coordinator_send.send(Box::new(msg)));
1674 let mut bomb = Bomb::<B> {
1675 coordinator_send: cgcx.coordinator_send.clone(),
1677 worker_id: cgcx.worker,
1680 // Execute the work itself, and if it finishes successfully then flag
1681 // ourselves as a success as well.
1683 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1684 // as a diagnostic was already sent off to the main thread - just
1685 // surface that there was an error in this worker.
1687 let _prof_timer = work.start_profiling(&cgcx);
1688 Some(execute_work_item(&cgcx, work))
1691 .expect("failed to spawn thread");
1694 enum SharedEmitterMessage {
1695 Diagnostic(Diagnostic),
1696 InlineAsmError(u32, String, Level, Option<(String, Vec<InnerSpan>)>),
1702 pub struct SharedEmitter {
1703 sender: Sender<SharedEmitterMessage>,
1706 pub struct SharedEmitterMain {
1707 receiver: Receiver<SharedEmitterMessage>,
1710 impl SharedEmitter {
1711 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1712 let (sender, receiver) = channel();
1714 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1717 pub fn inline_asm_error(
1722 source: Option<(String, Vec<InnerSpan>)>,
1724 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)));
1727 pub fn fatal(&self, msg: &str) {
1728 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1732 impl Emitter for SharedEmitter {
1733 fn emit_diagnostic(&mut self, diag: &rustc_errors::Diagnostic) {
1734 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1735 msg: diag.message(),
1736 code: diag.code.clone(),
1739 for child in &diag.children {
1740 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1741 msg: child.message(),
1746 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1748 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
1753 impl SharedEmitterMain {
1754 pub fn check(&self, sess: &Session, blocking: bool) {
1756 let message = if blocking {
1757 match self.receiver.recv() {
1758 Ok(message) => Ok(message),
1762 match self.receiver.try_recv() {
1763 Ok(message) => Ok(message),
1769 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1770 let handler = sess.diagnostic();
1771 let mut d = rustc_errors::Diagnostic::new(diag.lvl, &diag.msg);
1772 if let Some(code) = diag.code {
1775 handler.emit_diagnostic(&d);
1777 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => {
1778 let msg = msg.strip_prefix("error: ").unwrap_or(&msg);
1780 let mut err = match level {
1781 Level::Error => sess.struct_err(&msg),
1782 Level::Warning => sess.struct_warn(&msg),
1783 Level::Note => sess.struct_note_without_error(&msg),
1784 _ => bug!("Invalid inline asm diagnostic level"),
1787 // If the cookie is 0 then we don't have span information.
1789 let pos = BytePos::from_u32(cookie);
1790 let span = Span::with_root_ctxt(pos, pos);
1794 // Point to the generated assembly if it is available.
1795 if let Some((buffer, spans)) = source {
1798 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
1799 let source_span = Span::with_root_ctxt(source.start_pos, source.end_pos);
1801 spans.iter().map(|sp| source_span.from_inner(*sp)).collect();
1802 err.span_note(spans, "instantiated into assembly here");
1807 Ok(SharedEmitterMessage::AbortIfErrors) => {
1808 sess.abort_if_errors();
1810 Ok(SharedEmitterMessage::Fatal(msg)) => {
1821 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1823 pub crate_name: Symbol,
1824 pub metadata: EncodedMetadata,
1825 pub windows_subsystem: Option<String>,
1826 pub linker_info: LinkerInfo,
1827 pub crate_info: CrateInfo,
1828 pub coordinator_send: Sender<Box<dyn Any + Send>>,
1829 pub codegen_worker_receive: Receiver<Message<B>>,
1830 pub shared_emitter_main: SharedEmitterMain,
1831 pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1832 pub output_filenames: Arc<OutputFilenames>,
1835 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1836 pub fn join(self, sess: &Session) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1837 let _timer = sess.timer("finish_ongoing_codegen");
1839 self.shared_emitter_main.check(sess, true);
1840 let future = self.future;
1841 let compiled_modules = sess.time("join_worker_thread", || match future.join() {
1842 Ok(Ok(compiled_modules)) => compiled_modules,
1844 sess.abort_if_errors();
1845 panic!("expected abort due to worker thread errors")
1848 bug!("panic during codegen/LLVM phase");
1852 sess.cgu_reuse_tracker.check_expected_reuse(sess.diagnostic());
1854 sess.abort_if_errors();
1857 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
1858 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
1860 // FIXME: time_llvm_passes support - does this use a global context or
1862 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1863 self.backend.print_pass_timings()
1868 crate_name: self.crate_name,
1869 metadata: self.metadata,
1870 windows_subsystem: self.windows_subsystem,
1871 linker_info: self.linker_info,
1872 crate_info: self.crate_info,
1874 modules: compiled_modules.modules,
1875 allocator_module: compiled_modules.allocator_module,
1876 metadata_module: compiled_modules.metadata_module,
1882 pub fn submit_pre_codegened_module_to_llvm(
1885 module: ModuleCodegen<B::Module>,
1887 self.wait_for_signal_to_codegen_item();
1888 self.check_for_errors(tcx.sess);
1890 // These are generally cheap and won't throw off scheduling.
1892 submit_codegened_module_to_llvm(&self.backend, &self.coordinator_send, module, cost);
1895 pub fn codegen_finished(&self, tcx: TyCtxt<'_>) {
1896 self.wait_for_signal_to_codegen_item();
1897 self.check_for_errors(tcx.sess);
1898 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1901 /// Consumes this context indicating that codegen was entirely aborted, and
1902 /// we need to exit as quickly as possible.
1904 /// This method blocks the current thread until all worker threads have
1905 /// finished, and all worker threads should have exited or be real close to
1906 /// exiting at this point.
1907 pub fn codegen_aborted(self) {
1908 // Signal to the coordinator it should spawn no more work and start
1910 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1911 drop(self.future.join());
1914 pub fn check_for_errors(&self, sess: &Session) {
1915 self.shared_emitter_main.check(sess, false);
1918 pub fn wait_for_signal_to_codegen_item(&self) {
1919 match self.codegen_worker_receive.recv() {
1920 Ok(Message::CodegenItem) => {
1923 Ok(_) => panic!("unexpected message"),
1925 // One of the LLVM threads must have panicked, fall through so
1926 // error handling can be reached.
1932 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1934 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1935 module: ModuleCodegen<B::Module>,
1938 let llvm_work_item = WorkItem::Optimize(module);
1939 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost })));
1942 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1944 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1945 module: CachedModuleCodegen,
1947 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1948 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost: 0 })));
1951 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1954 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1955 module: CachedModuleCodegen,
1957 let filename = pre_lto_bitcode_filename(&module.name);
1958 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1959 let file = fs::File::open(&bc_path)
1960 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
1963 memmap::Mmap::map(&file).unwrap_or_else(|e| {
1964 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1967 // Schedule the module to be loaded
1968 drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule::<B> {
1969 module_data: SerializedModule::FromUncompressedFile(mmap),
1970 work_product: module.source,
1974 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1975 format!("{}.{}", module_name, PRE_LTO_BC_EXT)
1978 fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
1979 // This should never be true (because it's not supported). If it is true,
1980 // something is wrong with commandline arg validation.
1982 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
1983 && tcx.sess.target.is_like_windows
1984 && tcx.sess.opts.cg.prefer_dynamic)
1987 tcx.sess.target.is_like_windows &&
1988 tcx.sess.crate_types().iter().any(|ct| *ct == CrateType::Rlib) &&
1989 // ThinLTO can't handle this workaround in all cases, so we don't
1990 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
1991 // dynamic linking when linker plugin LTO is enabled.
1992 !tcx.sess.opts.cg.linker_plugin_lto.enabled()