1use std::any::Any;
2use std::assert_matches::assert_matches;
3use std::marker::PhantomData;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::sync::mpsc::{Receiver, Sender, channel};
7use std::{fs, io, mem, str, thread};
8
9use rustc_abi::Size;
10use rustc_ast::attr;
11use rustc_ast::expand::autodiff_attrs::AutoDiffItem;
12use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
13use rustc_data_structures::jobserver::{self, Acquired};
14use rustc_data_structures::memmap::Mmap;
15use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
16use rustc_errors::emitter::Emitter;
17use rustc_errors::translation::Translate;
18use rustc_errors::{
19 Diag, DiagArgMap, DiagCtxt, DiagMessage, ErrCode, FatalError, FluentBundle, Level, MultiSpan,
20 Style, Suggestions,
21};
22use rustc_fs_util::link_or_copy;
23use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
24use rustc_incremental::{
25 copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
26};
27use rustc_metadata::EncodedMetadata;
28use rustc_metadata::fs::copy_to_stdout;
29use rustc_middle::bug;
30use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
31use rustc_middle::middle::exported_symbols::SymbolExportInfo;
32use rustc_middle::ty::TyCtxt;
33use rustc_session::Session;
34use rustc_session::config::{
35 self, CrateType, Lto, OutFileName, OutputFilenames, OutputType, Passes, SwitchWithOptPath,
36};
37use rustc_span::source_map::SourceMap;
38use rustc_span::{FileName, InnerSpan, Span, SpanData, sym};
39use rustc_target::spec::{MergeFunctions, SanitizerSet};
40use tracing::debug;
41
42use super::link::{self, ensure_removed};
43use super::lto::{self, SerializedModule};
44use super::symbol_export::symbol_name_for_instance_in_crate;
45use crate::errors::{AutodiffWithoutLto, ErrorCreatingRemarkDir};
46use crate::traits::*;
47use crate::{
48 CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
49 errors,
50};
51
52const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
53
54#[derive(Clone, Copy, PartialEq)]
56pub enum EmitObj {
57 None,
59
60 Bitcode,
63
64 ObjectCode(BitcodeSection),
66}
67
68#[derive(Clone, Copy, PartialEq)]
70pub enum BitcodeSection {
71 None,
73
74 Full,
76}
77
78pub struct ModuleConfig {
80 pub passes: Vec<String>,
82 pub opt_level: Option<config::OptLevel>,
85
86 pub opt_size: Option<config::OptLevel>,
88
89 pub pgo_gen: SwitchWithOptPath,
90 pub pgo_use: Option<PathBuf>,
91 pub pgo_sample_use: Option<PathBuf>,
92 pub debug_info_for_profiling: bool,
93 pub instrument_coverage: bool,
94
95 pub sanitizer: SanitizerSet,
96 pub sanitizer_recover: SanitizerSet,
97 pub sanitizer_dataflow_abilist: Vec<String>,
98 pub sanitizer_memory_track_origins: usize,
99
100 pub emit_pre_lto_bc: bool,
102 pub emit_no_opt_bc: bool,
103 pub emit_bc: bool,
104 pub emit_ir: bool,
105 pub emit_asm: bool,
106 pub emit_obj: EmitObj,
107 pub emit_thin_lto: bool,
108 pub emit_thin_lto_summary: bool,
109 pub bc_cmdline: String,
110
111 pub verify_llvm_ir: bool,
114 pub lint_llvm_ir: bool,
115 pub no_prepopulate_passes: bool,
116 pub no_builtins: bool,
117 pub time_module: bool,
118 pub vectorize_loop: bool,
119 pub vectorize_slp: bool,
120 pub merge_functions: bool,
121 pub emit_lifetime_markers: bool,
122 pub llvm_plugins: Vec<String>,
123 pub autodiff: Vec<config::AutoDiff>,
124}
125
126impl ModuleConfig {
127 fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
128 macro_rules! if_regular {
131 ($regular: expr, $other: expr) => {
132 if let ModuleKind::Regular = kind { $regular } else { $other }
133 };
134 }
135
136 let sess = tcx.sess;
137 let opt_level_and_size = if_regular!(Some(sess.opts.optimize), None);
138
139 let save_temps = sess.opts.cg.save_temps;
140
141 let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
142 || match kind {
143 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
144 ModuleKind::Allocator => false,
145 ModuleKind::Metadata => sess.opts.output_types.contains_key(&OutputType::Metadata),
146 };
147
148 let emit_obj = if !should_emit_obj {
149 EmitObj::None
150 } else if sess.target.obj_is_bitcode
151 || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
152 {
153 EmitObj::Bitcode
168 } else if need_bitcode_in_object(tcx) {
169 EmitObj::ObjectCode(BitcodeSection::Full)
170 } else {
171 EmitObj::ObjectCode(BitcodeSection::None)
172 };
173
174 ModuleConfig {
175 passes: if_regular!(sess.opts.cg.passes.clone(), vec![]),
176
177 opt_level: opt_level_and_size,
178 opt_size: opt_level_and_size,
179
180 pgo_gen: if_regular!(
181 sess.opts.cg.profile_generate.clone(),
182 SwitchWithOptPath::Disabled
183 ),
184 pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
185 pgo_sample_use: if_regular!(sess.opts.unstable_opts.profile_sample_use.clone(), None),
186 debug_info_for_profiling: sess.opts.unstable_opts.debug_info_for_profiling,
187 instrument_coverage: if_regular!(sess.instrument_coverage(), false),
188
189 sanitizer: if_regular!(sess.opts.unstable_opts.sanitizer, SanitizerSet::empty()),
190 sanitizer_dataflow_abilist: if_regular!(
191 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
192 Vec::new()
193 ),
194 sanitizer_recover: if_regular!(
195 sess.opts.unstable_opts.sanitizer_recover,
196 SanitizerSet::empty()
197 ),
198 sanitizer_memory_track_origins: if_regular!(
199 sess.opts.unstable_opts.sanitizer_memory_track_origins,
200 0
201 ),
202
203 emit_pre_lto_bc: if_regular!(
204 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
205 false
206 ),
207 emit_no_opt_bc: if_regular!(save_temps, false),
208 emit_bc: if_regular!(
209 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
210 save_temps
211 ),
212 emit_ir: if_regular!(
213 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
214 false
215 ),
216 emit_asm: if_regular!(
217 sess.opts.output_types.contains_key(&OutputType::Assembly),
218 false
219 ),
220 emit_obj,
221 emit_thin_lto: sess.opts.unstable_opts.emit_thin_lto,
222 emit_thin_lto_summary: if_regular!(
223 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
224 false
225 ),
226 bc_cmdline: sess.target.bitcode_llvm_cmdline.to_string(),
227
228 verify_llvm_ir: sess.verify_llvm_ir(),
229 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
230 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
231 no_builtins: no_builtins || sess.target.no_builtins,
232
233 time_module: if_regular!(true, false),
236
237 vectorize_loop: !sess.opts.cg.no_vectorize_loops
240 && (sess.opts.optimize == config::OptLevel::More
241 || sess.opts.optimize == config::OptLevel::Aggressive),
242 vectorize_slp: !sess.opts.cg.no_vectorize_slp
243 && sess.opts.optimize == config::OptLevel::Aggressive,
244
245 merge_functions: match sess
255 .opts
256 .unstable_opts
257 .merge_functions
258 .unwrap_or(sess.target.merge_functions)
259 {
260 MergeFunctions::Disabled => false,
261 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
262 use config::OptLevel::*;
263 match sess.opts.optimize {
264 Aggressive | More | SizeMin | Size => true,
265 Less | No => false,
266 }
267 }
268 },
269
270 emit_lifetime_markers: sess.emit_lifetime_markers(),
271 llvm_plugins: if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
272 autodiff: if_regular!(sess.opts.unstable_opts.autodiff.clone(), vec![]),
273 }
274 }
275
276 pub fn bitcode_needed(&self) -> bool {
277 self.emit_bc
278 || self.emit_thin_lto_summary
279 || self.emit_obj == EmitObj::Bitcode
280 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
281 }
282
283 pub fn embed_bitcode(&self) -> bool {
284 self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
285 }
286}
287
288pub struct TargetMachineFactoryConfig {
290 pub split_dwarf_file: Option<PathBuf>,
294
295 pub output_obj_file: Option<PathBuf>,
298}
299
300impl TargetMachineFactoryConfig {
301 pub fn new(
302 cgcx: &CodegenContext<impl WriteBackendMethods>,
303 module_name: &str,
304 ) -> TargetMachineFactoryConfig {
305 let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
306 cgcx.output_filenames.split_dwarf_path(
307 cgcx.split_debuginfo,
308 cgcx.split_dwarf_kind,
309 module_name,
310 cgcx.invocation_temp.as_deref(),
311 )
312 } else {
313 None
314 };
315
316 let output_obj_file = Some(cgcx.output_filenames.temp_path_for_cgu(
317 OutputType::Object,
318 module_name,
319 cgcx.invocation_temp.as_deref(),
320 ));
321 TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
322 }
323}
324
325pub type TargetMachineFactoryFn<B> = Arc<
326 dyn Fn(
327 TargetMachineFactoryConfig,
328 ) -> Result<
329 <B as WriteBackendMethods>::TargetMachine,
330 <B as WriteBackendMethods>::TargetMachineError,
331 > + Send
332 + Sync,
333>;
334
335type ExportedSymbols = FxHashMap<CrateNum, Arc<Vec<(String, SymbolExportInfo)>>>;
336
337#[derive(Clone)]
339pub struct CodegenContext<B: WriteBackendMethods> {
340 pub prof: SelfProfilerRef,
342 pub lto: Lto,
343 pub save_temps: bool,
344 pub fewer_names: bool,
345 pub time_trace: bool,
346 pub exported_symbols: Option<Arc<ExportedSymbols>>,
347 pub opts: Arc<config::Options>,
348 pub crate_types: Vec<CrateType>,
349 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
350 pub output_filenames: Arc<OutputFilenames>,
351 pub invocation_temp: Option<String>,
352 pub regular_module_config: Arc<ModuleConfig>,
353 pub metadata_module_config: Arc<ModuleConfig>,
354 pub allocator_module_config: Arc<ModuleConfig>,
355 pub tm_factory: TargetMachineFactoryFn<B>,
356 pub msvc_imps_needed: bool,
357 pub is_pe_coff: bool,
358 pub target_can_use_split_dwarf: bool,
359 pub target_arch: String,
360 pub target_is_like_darwin: bool,
361 pub target_is_like_aix: bool,
362 pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
363 pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
364 pub pointer_size: Size,
365
366 pub expanded_args: Vec<String>,
371
372 pub diag_emitter: SharedEmitter,
374 pub remark: Passes,
376 pub remark_dir: Option<PathBuf>,
379 pub incr_comp_session_dir: Option<PathBuf>,
382 pub coordinator_send: Sender<Box<dyn Any + Send>>,
384 pub parallel: bool,
388}
389
390impl<B: WriteBackendMethods> CodegenContext<B> {
391 pub fn create_dcx(&self) -> DiagCtxt {
392 DiagCtxt::new(Box::new(self.diag_emitter.clone()))
393 }
394
395 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
396 match kind {
397 ModuleKind::Regular => &self.regular_module_config,
398 ModuleKind::Metadata => &self.metadata_module_config,
399 ModuleKind::Allocator => &self.allocator_module_config,
400 }
401 }
402}
403
404fn generate_lto_work<B: ExtraBackendMethods>(
405 cgcx: &CodegenContext<B>,
406 autodiff: Vec<AutoDiffItem>,
407 needs_fat_lto: Vec<FatLtoInput<B>>,
408 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
409 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
410) -> Vec<(WorkItem<B>, u64)> {
411 let _prof_timer = cgcx.prof.generic_activity("codegen_generate_lto_work");
412
413 if !needs_fat_lto.is_empty() {
414 assert!(needs_thin_lto.is_empty());
415 let mut module =
416 B::run_fat_lto(cgcx, needs_fat_lto, import_only_modules).unwrap_or_else(|e| e.raise());
417 if cgcx.lto == Lto::Fat && !autodiff.is_empty() {
418 let config = cgcx.config(ModuleKind::Regular);
419 module = module.autodiff(cgcx, autodiff, config).unwrap_or_else(|e| e.raise());
420 }
421 vec![(WorkItem::LTO(module), 0)]
423 } else {
424 if !autodiff.is_empty() {
425 let dcx = cgcx.create_dcx();
426 dcx.handle().emit_fatal(AutodiffWithoutLto {});
427 }
428 assert!(needs_fat_lto.is_empty());
429 let (lto_modules, copy_jobs) = B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules)
430 .unwrap_or_else(|e| e.raise());
431 lto_modules
432 .into_iter()
433 .map(|module| {
434 let cost = module.cost();
435 (WorkItem::LTO(module), cost)
436 })
437 .chain(copy_jobs.into_iter().map(|wp| {
438 (
439 WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
440 name: wp.cgu_name.clone(),
441 source: wp,
442 }),
443 0, )
445 }))
446 .collect()
447 }
448}
449
450struct CompiledModules {
451 modules: Vec<CompiledModule>,
452 allocator_module: Option<CompiledModule>,
453}
454
455fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
456 let sess = tcx.sess;
457 sess.opts.cg.embed_bitcode
458 && tcx.crate_types().contains(&CrateType::Rlib)
459 && sess.opts.output_types.contains_key(&OutputType::Exe)
460}
461
462fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
463 if sess.opts.incremental.is_none() {
464 return false;
465 }
466
467 match sess.lto() {
468 Lto::No => false,
469 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
470 }
471}
472
473pub(crate) fn start_async_codegen<B: ExtraBackendMethods>(
474 backend: B,
475 tcx: TyCtxt<'_>,
476 target_cpu: String,
477 metadata: EncodedMetadata,
478 metadata_module: Option<CompiledModule>,
479) -> OngoingCodegen<B> {
480 let (coordinator_send, coordinator_receive) = channel();
481
482 let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
483 let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
484
485 let crate_info = CrateInfo::new(tcx, target_cpu);
486
487 let regular_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
488 let metadata_config = ModuleConfig::new(ModuleKind::Metadata, tcx, no_builtins);
489 let allocator_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
490
491 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
492 let (codegen_worker_send, codegen_worker_receive) = channel();
493
494 let coordinator_thread = start_executing_work(
495 backend.clone(),
496 tcx,
497 &crate_info,
498 shared_emitter,
499 codegen_worker_send,
500 coordinator_receive,
501 Arc::new(regular_config),
502 Arc::new(metadata_config),
503 Arc::new(allocator_config),
504 coordinator_send.clone(),
505 );
506
507 OngoingCodegen {
508 backend,
509 metadata,
510 metadata_module,
511 crate_info,
512
513 codegen_worker_receive,
514 shared_emitter_main,
515 coordinator: Coordinator {
516 sender: coordinator_send,
517 future: Some(coordinator_thread),
518 phantom: PhantomData,
519 },
520 output_filenames: Arc::clone(tcx.output_filenames(())),
521 }
522}
523
524fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
525 sess: &Session,
526 compiled_modules: &CompiledModules,
527) -> FxIndexMap<WorkProductId, WorkProduct> {
528 let mut work_products = FxIndexMap::default();
529
530 if sess.opts.incremental.is_none() {
531 return work_products;
532 }
533
534 let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
535
536 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
537 let mut files = Vec::new();
538 if let Some(object_file_path) = &module.object {
539 files.push((OutputType::Object.extension(), object_file_path.as_path()));
540 }
541 if let Some(dwarf_object_file_path) = &module.dwarf_object {
542 files.push(("dwo", dwarf_object_file_path.as_path()));
543 }
544 if let Some(path) = &module.assembly {
545 files.push((OutputType::Assembly.extension(), path.as_path()));
546 }
547 if let Some(path) = &module.llvm_ir {
548 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
549 }
550 if let Some(path) = &module.bytecode {
551 files.push((OutputType::Bitcode.extension(), path.as_path()));
552 }
553 if let Some((id, product)) = copy_cgu_workproduct_to_incr_comp_cache_dir(
554 sess,
555 &module.name,
556 files.as_slice(),
557 &module.links_from_incr_cache,
558 ) {
559 work_products.insert(id, product);
560 }
561 }
562
563 work_products
564}
565
566fn produce_final_output_artifacts(
567 sess: &Session,
568 compiled_modules: &CompiledModules,
569 crate_output: &OutputFilenames,
570) {
571 let mut user_wants_bitcode = false;
572 let mut user_wants_objects = false;
573
574 let copy_gracefully = |from: &Path, to: &OutFileName| match to {
576 OutFileName::Stdout if let Err(e) = copy_to_stdout(from) => {
577 sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
578 }
579 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
580 sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
581 }
582 _ => {}
583 };
584
585 let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
586 if let [module] = &compiled_modules.modules[..] {
587 let path = crate_output.temp_path_for_cgu(
590 output_type,
591 &module.name,
592 sess.invocation_temp.as_deref(),
593 );
594 let output = crate_output.path(output_type);
595 if !output_type.is_text_output() && output.is_tty() {
596 sess.dcx()
597 .emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
598 } else {
599 copy_gracefully(&path, &output);
600 }
601 if !sess.opts.cg.save_temps && !keep_numbered {
602 ensure_removed(sess.dcx(), &path);
604 }
605 } else {
606 if crate_output.outputs.contains_explicit_name(&output_type) {
607 sess.dcx()
610 .emit_warn(errors::IgnoringEmitPath { extension: output_type.extension() });
611 } else if crate_output.single_output_file.is_some() {
612 sess.dcx().emit_warn(errors::IgnoringOutput { extension: output_type.extension() });
615 } else {
616 }
620 }
621 };
622
623 for output_type in crate_output.outputs.keys() {
627 match *output_type {
628 OutputType::Bitcode => {
629 user_wants_bitcode = true;
630 copy_if_one_unit(OutputType::Bitcode, true);
634 }
635 OutputType::ThinLinkBitcode => {
636 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
637 }
638 OutputType::LlvmAssembly => {
639 copy_if_one_unit(OutputType::LlvmAssembly, false);
640 }
641 OutputType::Assembly => {
642 copy_if_one_unit(OutputType::Assembly, false);
643 }
644 OutputType::Object => {
645 user_wants_objects = true;
646 copy_if_one_unit(OutputType::Object, true);
647 }
648 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
649 }
650 }
651
652 if !sess.opts.cg.save_temps {
665 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
681
682 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
683
684 let keep_numbered_objects =
685 needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
686
687 for module in compiled_modules.modules.iter() {
688 if !keep_numbered_objects {
689 if let Some(ref path) = module.object {
690 ensure_removed(sess.dcx(), path);
691 }
692
693 if let Some(ref path) = module.dwarf_object {
694 ensure_removed(sess.dcx(), path);
695 }
696 }
697
698 if let Some(ref path) = module.bytecode {
699 if !keep_numbered_bitcode {
700 ensure_removed(sess.dcx(), path);
701 }
702 }
703 }
704
705 if !user_wants_bitcode
706 && let Some(ref allocator_module) = compiled_modules.allocator_module
707 && let Some(ref path) = allocator_module.bytecode
708 {
709 ensure_removed(sess.dcx(), path);
710 }
711 }
712
713 if sess.opts.json_artifact_notifications {
714 if let [module] = &compiled_modules.modules[..] {
715 module.for_each_output(|_path, ty| {
716 if sess.opts.output_types.contains_key(&ty) {
717 let descr = ty.shorthand();
718 let path = crate_output.path(ty);
721 sess.dcx().emit_artifact_notification(path.as_path(), descr);
722 }
723 });
724 } else {
725 for module in &compiled_modules.modules {
726 module.for_each_output(|path, ty| {
727 if sess.opts.output_types.contains_key(&ty) {
728 let descr = ty.shorthand();
729 sess.dcx().emit_artifact_notification(&path, descr);
730 }
731 });
732 }
733 }
734 }
735
736 }
742
743pub(crate) enum WorkItem<B: WriteBackendMethods> {
744 Optimize(ModuleCodegen<B::Module>),
746 CopyPostLtoArtifacts(CachedModuleCodegen),
749 LTO(lto::LtoModuleCodegen<B>),
751}
752
753impl<B: WriteBackendMethods> WorkItem<B> {
754 fn module_kind(&self) -> ModuleKind {
755 match *self {
756 WorkItem::Optimize(ref m) => m.kind,
757 WorkItem::CopyPostLtoArtifacts(_) | WorkItem::LTO(_) => ModuleKind::Regular,
758 }
759 }
760
761 fn short_description(&self) -> String {
763 #[cfg(not(windows))]
767 fn desc(short: &str, _long: &str, name: &str) -> String {
768 assert_eq!(short.len(), 3);
788 let name = if let Some(index) = name.find("-cgu.") {
789 &name[index + 1..] } else {
791 name
792 };
793 format!("{short} {name}")
794 }
795
796 #[cfg(windows)]
798 fn desc(_short: &str, long: &str, name: &str) -> String {
799 format!("{long} {name}")
800 }
801
802 match self {
803 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
804 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
805 WorkItem::LTO(m) => desc("lto", "LTO module", m.name()),
806 }
807 }
808}
809
810pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
812 Finished(CompiledModule),
814
815 NeedsLink(ModuleCodegen<B::Module>),
818
819 NeedsFatLto(FatLtoInput<B>),
822
823 NeedsThinLto(String, B::ThinBuffer),
826}
827
828pub enum FatLtoInput<B: WriteBackendMethods> {
829 Serialized { name: String, buffer: B::ModuleBuffer },
830 InMemory(ModuleCodegen<B::Module>),
831}
832
833pub(crate) enum ComputedLtoType {
835 No,
836 Thin,
837 Fat,
838}
839
840pub(crate) fn compute_per_cgu_lto_type(
841 sess_lto: &Lto,
842 opts: &config::Options,
843 sess_crate_types: &[CrateType],
844 module_kind: ModuleKind,
845) -> ComputedLtoType {
846 if module_kind == ModuleKind::Metadata {
849 return ComputedLtoType::No;
850 }
851
852 let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
856
857 let is_allocator = module_kind == ModuleKind::Allocator;
862
863 let is_rlib = matches!(sess_crate_types, [CrateType::Rlib]);
872
873 match sess_lto {
874 Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
875 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
876 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
877 _ => ComputedLtoType::No,
878 }
879}
880
881fn execute_optimize_work_item<B: ExtraBackendMethods>(
882 cgcx: &CodegenContext<B>,
883 mut module: ModuleCodegen<B::Module>,
884 module_config: &ModuleConfig,
885) -> Result<WorkItemResult<B>, FatalError> {
886 let dcx = cgcx.create_dcx();
887 let dcx = dcx.handle();
888
889 B::optimize(cgcx, dcx, &mut module, module_config)?;
890
891 let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
897
898 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
901 let filename = pre_lto_bitcode_filename(&module.name);
902 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
903 } else {
904 None
905 };
906
907 match lto_type {
908 ComputedLtoType::No => finish_intra_module_work(cgcx, module, module_config),
909 ComputedLtoType::Thin => {
910 let (name, thin_buffer) = B::prepare_thin(module, false);
911 if let Some(path) = bitcode {
912 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
913 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
914 });
915 }
916 Ok(WorkItemResult::NeedsThinLto(name, thin_buffer))
917 }
918 ComputedLtoType::Fat => match bitcode {
919 Some(path) => {
920 let (name, buffer) = B::serialize_module(module);
921 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
922 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
923 });
924 Ok(WorkItemResult::NeedsFatLto(FatLtoInput::Serialized { name, buffer }))
925 }
926 None => Ok(WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module))),
927 },
928 }
929}
930
931fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
932 cgcx: &CodegenContext<B>,
933 module: CachedModuleCodegen,
934 module_config: &ModuleConfig,
935) -> WorkItemResult<B> {
936 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
937
938 let mut links_from_incr_cache = Vec::new();
939
940 let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
941 let source_file = in_incr_comp_dir(incr_comp_session_dir, saved_path);
942 debug!(
943 "copying preexisting module `{}` from {:?} to {}",
944 module.name,
945 source_file,
946 output_path.display()
947 );
948 match link_or_copy(&source_file, &output_path) {
949 Ok(_) => {
950 links_from_incr_cache.push(source_file);
951 Some(output_path)
952 }
953 Err(error) => {
954 cgcx.create_dcx().handle().emit_err(errors::CopyPathBuf {
955 source_file,
956 output_path,
957 error,
958 });
959 None
960 }
961 }
962 };
963
964 let dwarf_object =
965 module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
966 let dwarf_obj_out = cgcx
967 .output_filenames
968 .split_dwarf_path(
969 cgcx.split_debuginfo,
970 cgcx.split_dwarf_kind,
971 &module.name,
972 cgcx.invocation_temp.as_deref(),
973 )
974 .expect(
975 "saved dwarf object in work product but `split_dwarf_path` returned `None`",
976 );
977 load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
978 });
979
980 let mut load_from_incr_cache = |perform, output_type: OutputType| {
981 if perform {
982 let saved_file = module.source.saved_files.get(output_type.extension())?;
983 let output_path = cgcx.output_filenames.temp_path_for_cgu(
984 output_type,
985 &module.name,
986 cgcx.invocation_temp.as_deref(),
987 );
988 load_from_incr_comp_dir(output_path, &saved_file)
989 } else {
990 None
991 }
992 };
993
994 let should_emit_obj = module_config.emit_obj != EmitObj::None;
995 let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
996 let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
997 let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
998 let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
999 if should_emit_obj && object.is_none() {
1000 cgcx.create_dcx().handle().emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
1001 }
1002
1003 WorkItemResult::Finished(CompiledModule {
1004 links_from_incr_cache,
1005 name: module.name,
1006 kind: ModuleKind::Regular,
1007 object,
1008 dwarf_object,
1009 bytecode,
1010 assembly,
1011 llvm_ir,
1012 })
1013}
1014
1015fn execute_lto_work_item<B: ExtraBackendMethods>(
1016 cgcx: &CodegenContext<B>,
1017 module: lto::LtoModuleCodegen<B>,
1018 module_config: &ModuleConfig,
1019) -> Result<WorkItemResult<B>, FatalError> {
1020 let module = module.optimize(cgcx)?;
1021 finish_intra_module_work(cgcx, module, module_config)
1022}
1023
1024fn finish_intra_module_work<B: ExtraBackendMethods>(
1025 cgcx: &CodegenContext<B>,
1026 module: ModuleCodegen<B::Module>,
1027 module_config: &ModuleConfig,
1028) -> Result<WorkItemResult<B>, FatalError> {
1029 let dcx = cgcx.create_dcx();
1030 let dcx = dcx.handle();
1031
1032 if !cgcx.opts.unstable_opts.combine_cgu
1033 || module.kind == ModuleKind::Metadata
1034 || module.kind == ModuleKind::Allocator
1035 {
1036 let module = B::codegen(cgcx, dcx, module, module_config)?;
1037 Ok(WorkItemResult::Finished(module))
1038 } else {
1039 Ok(WorkItemResult::NeedsLink(module))
1040 }
1041}
1042
1043pub(crate) enum Message<B: WriteBackendMethods> {
1045 Token(io::Result<Acquired>),
1048
1049 WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>>, worker_id: usize },
1052
1053 AddAutoDiffItems(Vec<AutoDiffItem>),
1055
1056 CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
1060
1061 AddImportOnlyModule {
1064 module_data: SerializedModule<B::ModuleBuffer>,
1065 work_product: WorkProduct,
1066 },
1067
1068 CodegenComplete,
1071
1072 CodegenAborted,
1075}
1076
1077pub struct CguMessage;
1080
1081struct Diagnostic {
1091 level: Level,
1092 messages: Vec<(DiagMessage, Style)>,
1093 code: Option<ErrCode>,
1094 children: Vec<Subdiagnostic>,
1095 args: DiagArgMap,
1096}
1097
1098pub(crate) struct Subdiagnostic {
1102 level: Level,
1103 messages: Vec<(DiagMessage, Style)>,
1104}
1105
1106#[derive(PartialEq, Clone, Copy, Debug)]
1107enum MainThreadState {
1108 Idle,
1110
1111 Codegenning,
1113
1114 Lending,
1116}
1117
1118fn start_executing_work<B: ExtraBackendMethods>(
1119 backend: B,
1120 tcx: TyCtxt<'_>,
1121 crate_info: &CrateInfo,
1122 shared_emitter: SharedEmitter,
1123 codegen_worker_send: Sender<CguMessage>,
1124 coordinator_receive: Receiver<Box<dyn Any + Send>>,
1125 regular_config: Arc<ModuleConfig>,
1126 metadata_config: Arc<ModuleConfig>,
1127 allocator_config: Arc<ModuleConfig>,
1128 tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
1129) -> thread::JoinHandle<Result<CompiledModules, ()>> {
1130 let coordinator_send = tx_to_llvm_workers;
1131 let sess = tcx.sess;
1132
1133 let mut each_linked_rlib_for_lto = Vec::new();
1134 drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| {
1135 if link::ignored_for_lto(sess, crate_info, cnum) {
1136 return;
1137 }
1138 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1139 }));
1140
1141 let exported_symbols = {
1143 let mut exported_symbols = FxHashMap::default();
1144
1145 let copy_symbols = |cnum| {
1146 let symbols = tcx
1147 .exported_symbols(cnum)
1148 .iter()
1149 .map(|&(s, lvl)| (symbol_name_for_instance_in_crate(tcx, s, cnum), lvl))
1150 .collect();
1151 Arc::new(symbols)
1152 };
1153
1154 match sess.lto() {
1155 Lto::No => None,
1156 Lto::ThinLocal => {
1157 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1158 Some(Arc::new(exported_symbols))
1159 }
1160 Lto::Fat | Lto::Thin => {
1161 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1162 for &(cnum, ref _path) in &each_linked_rlib_for_lto {
1163 exported_symbols.insert(cnum, copy_symbols(cnum));
1164 }
1165 Some(Arc::new(exported_symbols))
1166 }
1167 }
1168 };
1169
1170 let coordinator_send2 = coordinator_send.clone();
1176 let helper = jobserver::client()
1177 .into_helper_thread(move |token| {
1178 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
1179 })
1180 .expect("failed to spawn helper thread");
1181
1182 let ol =
1183 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
1184 config::OptLevel::No
1186 } else {
1187 tcx.backend_optimization_level(())
1188 };
1189 let backend_features = tcx.global_backend_features(());
1190
1191 let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1192 let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1193 match result {
1194 Ok(dir) => Some(dir),
1195 Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1196 }
1197 } else {
1198 None
1199 };
1200
1201 let cgcx = CodegenContext::<B> {
1202 crate_types: tcx.crate_types().to_vec(),
1203 each_linked_rlib_for_lto,
1204 lto: sess.lto(),
1205 fewer_names: sess.fewer_names(),
1206 save_temps: sess.opts.cg.save_temps,
1207 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1208 opts: Arc::new(sess.opts.clone()),
1209 prof: sess.prof.clone(),
1210 exported_symbols,
1211 remark: sess.opts.cg.remark.clone(),
1212 remark_dir,
1213 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1214 coordinator_send,
1215 expanded_args: tcx.sess.expanded_args.clone(),
1216 diag_emitter: shared_emitter.clone(),
1217 output_filenames: Arc::clone(tcx.output_filenames(())),
1218 regular_module_config: regular_config,
1219 metadata_module_config: metadata_config,
1220 allocator_module_config: allocator_config,
1221 tm_factory: backend.target_machine_factory(tcx.sess, ol, backend_features),
1222 msvc_imps_needed: msvc_imps_needed(tcx),
1223 is_pe_coff: tcx.sess.target.is_like_windows,
1224 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1225 target_arch: tcx.sess.target.arch.to_string(),
1226 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1227 target_is_like_aix: tcx.sess.target.is_like_aix,
1228 split_debuginfo: tcx.sess.split_debuginfo(),
1229 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1230 parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1231 pointer_size: tcx.data_layout.pointer_size,
1232 invocation_temp: sess.invocation_temp.clone(),
1233 };
1234
1235 return B::spawn_named_thread(cgcx.time_trace, "coordinator".to_string(), move || {
1371 let mut worker_id_counter = 0;
1372 let mut free_worker_ids = Vec::new();
1373 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1374 if let Some(id) = free_worker_ids.pop() {
1375 id
1376 } else {
1377 let id = worker_id_counter;
1378 worker_id_counter += 1;
1379 id
1380 }
1381 };
1382
1383 let mut autodiff_items = Vec::new();
1386 let mut compiled_modules = vec![];
1387 let mut compiled_allocator_module = None;
1388 let mut needs_link = Vec::new();
1389 let mut needs_fat_lto = Vec::new();
1390 let mut needs_thin_lto = Vec::new();
1391 let mut lto_import_only_modules = Vec::new();
1392 let mut started_lto = false;
1393
1394 #[derive(Debug, PartialEq)]
1399 enum CodegenState {
1400 Ongoing,
1401 Completed,
1402 Aborted,
1403 }
1404 use CodegenState::*;
1405 let mut codegen_state = Ongoing;
1406
1407 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1409
1410 let mut tokens = Vec::new();
1413
1414 let mut main_thread_state = MainThreadState::Idle;
1415
1416 let mut running_with_own_token = 0;
1419
1420 let running_with_any_token = |main_thread_state, running_with_own_token| {
1423 running_with_own_token
1424 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1425 };
1426
1427 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1428
1429 loop {
1435 if codegen_state == Ongoing {
1439 if main_thread_state == MainThreadState::Idle {
1440 let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1448 let additional_running = std::cmp::min(extra_tokens, work_items.len());
1449 let anticipated_running = running_with_own_token + additional_running + 1;
1450
1451 if !queue_full_enough(work_items.len(), anticipated_running) {
1452 if codegen_worker_send.send(CguMessage).is_err() {
1454 panic!("Could not send CguMessage to main thread")
1455 }
1456 main_thread_state = MainThreadState::Codegenning;
1457 } else {
1458 let (item, _) =
1462 work_items.pop().expect("queue empty - queue_full_enough() broken?");
1463 main_thread_state = MainThreadState::Lending;
1464 spawn_work(
1465 &cgcx,
1466 &mut llvm_start_time,
1467 get_worker_id(&mut free_worker_ids),
1468 item,
1469 );
1470 }
1471 }
1472 } else if codegen_state == Completed {
1473 if running_with_any_token(main_thread_state, running_with_own_token) == 0
1474 && work_items.is_empty()
1475 {
1476 if needs_fat_lto.is_empty()
1478 && needs_thin_lto.is_empty()
1479 && lto_import_only_modules.is_empty()
1480 {
1481 break;
1483 }
1484
1485 assert!(!started_lto);
1491 started_lto = true;
1492
1493 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1494 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1495 let import_only_modules = mem::take(&mut lto_import_only_modules);
1496
1497 for (work, cost) in generate_lto_work(
1498 &cgcx,
1499 autodiff_items.clone(),
1500 needs_fat_lto,
1501 needs_thin_lto,
1502 import_only_modules,
1503 ) {
1504 let insertion_index = work_items
1505 .binary_search_by_key(&cost, |&(_, cost)| cost)
1506 .unwrap_or_else(|e| e);
1507 work_items.insert(insertion_index, (work, cost));
1508 if cgcx.parallel {
1509 helper.request_token();
1510 }
1511 }
1512 }
1513
1514 match main_thread_state {
1518 MainThreadState::Idle => {
1519 if let Some((item, _)) = work_items.pop() {
1520 main_thread_state = MainThreadState::Lending;
1521 spawn_work(
1522 &cgcx,
1523 &mut llvm_start_time,
1524 get_worker_id(&mut free_worker_ids),
1525 item,
1526 );
1527 } else {
1528 assert!(running_with_own_token > 0);
1535 running_with_own_token -= 1;
1536 main_thread_state = MainThreadState::Lending;
1537 }
1538 }
1539 MainThreadState::Codegenning => bug!(
1540 "codegen worker should not be codegenning after \
1541 codegen was already completed"
1542 ),
1543 MainThreadState::Lending => {
1544 }
1546 }
1547 } else {
1548 assert!(codegen_state == Aborted);
1551 if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1552 break;
1553 }
1554 }
1555
1556 if codegen_state != Aborted {
1559 while running_with_own_token < tokens.len()
1560 && let Some((item, _)) = work_items.pop()
1561 {
1562 spawn_work(
1563 &cgcx,
1564 &mut llvm_start_time,
1565 get_worker_id(&mut free_worker_ids),
1566 item,
1567 );
1568 running_with_own_token += 1;
1569 }
1570 }
1571
1572 tokens.truncate(running_with_own_token);
1574
1575 let mut free_worker = |worker_id| {
1581 if main_thread_state == MainThreadState::Lending {
1582 main_thread_state = MainThreadState::Idle;
1583 } else {
1584 running_with_own_token -= 1;
1585 }
1586
1587 free_worker_ids.push(worker_id);
1588 };
1589
1590 let msg = coordinator_receive.recv().unwrap();
1591 match *msg.downcast::<Message<B>>().ok().unwrap() {
1592 Message::Token(token) => {
1596 match token {
1597 Ok(token) => {
1598 tokens.push(token);
1599
1600 if main_thread_state == MainThreadState::Lending {
1601 main_thread_state = MainThreadState::Idle;
1606 running_with_own_token += 1;
1607 }
1608 }
1609 Err(e) => {
1610 let msg = &format!("failed to acquire jobserver token: {e}");
1611 shared_emitter.fatal(msg);
1612 codegen_state = Aborted;
1613 }
1614 }
1615 }
1616
1617 Message::CodegenDone { llvm_work_item, cost } => {
1618 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1627 let insertion_index = match insertion_index {
1628 Ok(idx) | Err(idx) => idx,
1629 };
1630 work_items.insert(insertion_index, (llvm_work_item, cost));
1631
1632 if cgcx.parallel {
1633 helper.request_token();
1634 }
1635 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1636 main_thread_state = MainThreadState::Idle;
1637 }
1638
1639 Message::AddAutoDiffItems(mut items) => {
1640 autodiff_items.append(&mut items);
1641 }
1642
1643 Message::CodegenComplete => {
1644 if codegen_state != Aborted {
1645 codegen_state = Completed;
1646 }
1647 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1648 main_thread_state = MainThreadState::Idle;
1649 }
1650
1651 Message::CodegenAborted => {
1659 codegen_state = Aborted;
1660 }
1661
1662 Message::WorkItem { result, worker_id } => {
1663 free_worker(worker_id);
1664
1665 match result {
1666 Ok(WorkItemResult::Finished(compiled_module)) => {
1667 match compiled_module.kind {
1668 ModuleKind::Regular => {
1669 assert!(needs_link.is_empty());
1670 compiled_modules.push(compiled_module);
1671 }
1672 ModuleKind::Allocator => {
1673 assert!(compiled_allocator_module.is_none());
1674 compiled_allocator_module = Some(compiled_module);
1675 }
1676 ModuleKind::Metadata => bug!("Should be handled separately"),
1677 }
1678 }
1679 Ok(WorkItemResult::NeedsLink(module)) => {
1680 assert!(compiled_modules.is_empty());
1681 needs_link.push(module);
1682 }
1683 Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1684 assert!(!started_lto);
1685 assert!(needs_thin_lto.is_empty());
1686 needs_fat_lto.push(fat_lto_input);
1687 }
1688 Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1689 assert!(!started_lto);
1690 assert!(needs_fat_lto.is_empty());
1691 needs_thin_lto.push((name, thin_buffer));
1692 }
1693 Err(Some(WorkerFatalError)) => {
1694 codegen_state = Aborted;
1696 }
1697 Err(None) => {
1698 bug!("worker thread panicked");
1701 }
1702 }
1703 }
1704
1705 Message::AddImportOnlyModule { module_data, work_product } => {
1706 assert!(!started_lto);
1707 assert_eq!(codegen_state, Ongoing);
1708 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1709 lto_import_only_modules.push((module_data, work_product));
1710 main_thread_state = MainThreadState::Idle;
1711 }
1712 }
1713 }
1714
1715 if codegen_state == Aborted {
1716 return Err(());
1717 }
1718
1719 let needs_link = mem::take(&mut needs_link);
1720 if !needs_link.is_empty() {
1721 assert!(compiled_modules.is_empty());
1722 let dcx = cgcx.create_dcx();
1723 let dcx = dcx.handle();
1724 let module = B::run_link(&cgcx, dcx, needs_link).map_err(|_| ())?;
1725 let module =
1726 B::codegen(&cgcx, dcx, module, cgcx.config(ModuleKind::Regular)).map_err(|_| ())?;
1727 compiled_modules.push(module);
1728 }
1729
1730 drop(llvm_start_time);
1732
1733 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1737
1738 Ok(CompiledModules {
1739 modules: compiled_modules,
1740 allocator_module: compiled_allocator_module,
1741 })
1742 })
1743 .expect("failed to spawn coordinator thread");
1744
1745 fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1748 let quarter_of_workers = workers_running - 3 * workers_running / 4;
1799 items_in_queue > 0 && items_in_queue >= quarter_of_workers
1800 }
1801}
1802
1803#[must_use]
1805pub(crate) struct WorkerFatalError;
1806
1807fn spawn_work<'a, B: ExtraBackendMethods>(
1808 cgcx: &'a CodegenContext<B>,
1809 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1810 worker_id: usize,
1811 work: WorkItem<B>,
1812) {
1813 if cgcx.config(work.module_kind()).time_module && llvm_start_time.is_none() {
1814 *llvm_start_time = Some(cgcx.prof.verbose_generic_activity("LLVM_passes"));
1815 }
1816
1817 let cgcx = cgcx.clone();
1818
1819 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1820 struct Bomb<B: ExtraBackendMethods> {
1823 coordinator_send: Sender<Box<dyn Any + Send>>,
1824 result: Option<Result<WorkItemResult<B>, FatalError>>,
1825 worker_id: usize,
1826 }
1827 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1828 fn drop(&mut self) {
1829 let worker_id = self.worker_id;
1830 let msg = match self.result.take() {
1831 Some(Ok(result)) => Message::WorkItem::<B> { result: Ok(result), worker_id },
1832 Some(Err(FatalError)) => {
1833 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)), worker_id }
1834 }
1835 None => Message::WorkItem::<B> { result: Err(None), worker_id },
1836 };
1837 drop(self.coordinator_send.send(Box::new(msg)));
1838 }
1839 }
1840
1841 let mut bomb =
1842 Bomb::<B> { coordinator_send: cgcx.coordinator_send.clone(), result: None, worker_id };
1843
1844 bomb.result = {
1851 let module_config = cgcx.config(work.module_kind());
1852
1853 Some(match work {
1854 WorkItem::Optimize(m) => {
1855 let _timer =
1856 cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &*m.name);
1857 execute_optimize_work_item(&cgcx, m, module_config)
1858 }
1859 WorkItem::CopyPostLtoArtifacts(m) => {
1860 let _timer = cgcx.prof.generic_activity_with_arg(
1861 "codegen_copy_artifacts_from_incr_cache",
1862 &*m.name,
1863 );
1864 Ok(execute_copy_from_cache_work_item(&cgcx, m, module_config))
1865 }
1866 WorkItem::LTO(m) => {
1867 let _timer =
1868 cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name());
1869 execute_lto_work_item(&cgcx, m, module_config)
1870 }
1871 })
1872 };
1873 })
1874 .expect("failed to spawn work thread");
1875}
1876
1877enum SharedEmitterMessage {
1878 Diagnostic(Diagnostic),
1879 InlineAsmError(SpanData, String, Level, Option<(String, Vec<InnerSpan>)>),
1880 Fatal(String),
1881}
1882
1883#[derive(Clone)]
1884pub struct SharedEmitter {
1885 sender: Sender<SharedEmitterMessage>,
1886}
1887
1888pub struct SharedEmitterMain {
1889 receiver: Receiver<SharedEmitterMessage>,
1890}
1891
1892impl SharedEmitter {
1893 fn new() -> (SharedEmitter, SharedEmitterMain) {
1894 let (sender, receiver) = channel();
1895
1896 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1897 }
1898
1899 pub fn inline_asm_error(
1900 &self,
1901 span: SpanData,
1902 msg: String,
1903 level: Level,
1904 source: Option<(String, Vec<InnerSpan>)>,
1905 ) {
1906 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(span, msg, level, source)));
1907 }
1908
1909 fn fatal(&self, msg: &str) {
1910 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1911 }
1912}
1913
1914impl Translate for SharedEmitter {
1915 fn fluent_bundle(&self) -> Option<&FluentBundle> {
1916 None
1917 }
1918
1919 fn fallback_fluent_bundle(&self) -> &FluentBundle {
1920 panic!("shared emitter attempted to translate a diagnostic");
1921 }
1922}
1923
1924impl Emitter for SharedEmitter {
1925 fn emit_diagnostic(
1926 &mut self,
1927 mut diag: rustc_errors::DiagInner,
1928 _registry: &rustc_errors::registry::Registry,
1929 ) {
1930 assert_eq!(diag.span, MultiSpan::new());
1933 assert_eq!(diag.suggestions, Suggestions::Enabled(vec![]));
1934 assert_eq!(diag.sort_span, rustc_span::DUMMY_SP);
1935 assert_eq!(diag.is_lint, None);
1936 let args = mem::replace(&mut diag.args, DiagArgMap::default());
1939 drop(
1940 self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1941 level: diag.level(),
1942 messages: diag.messages,
1943 code: diag.code,
1944 children: diag
1945 .children
1946 .into_iter()
1947 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
1948 .collect(),
1949 args,
1950 })),
1951 );
1952 }
1953
1954 fn source_map(&self) -> Option<&SourceMap> {
1955 None
1956 }
1957}
1958
1959impl SharedEmitterMain {
1960 fn check(&self, sess: &Session, blocking: bool) {
1961 loop {
1962 let message = if blocking {
1963 match self.receiver.recv() {
1964 Ok(message) => Ok(message),
1965 Err(_) => Err(()),
1966 }
1967 } else {
1968 match self.receiver.try_recv() {
1969 Ok(message) => Ok(message),
1970 Err(_) => Err(()),
1971 }
1972 };
1973
1974 match message {
1975 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1976 let dcx = sess.dcx();
1979 let mut d =
1980 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
1981 d.code = diag.code; d.children = diag
1983 .children
1984 .into_iter()
1985 .map(|sub| rustc_errors::Subdiag {
1986 level: sub.level,
1987 messages: sub.messages,
1988 span: MultiSpan::new(),
1989 })
1990 .collect();
1991 d.args = diag.args;
1992 dcx.emit_diagnostic(d);
1993 sess.dcx().abort_if_errors();
1994 }
1995 Ok(SharedEmitterMessage::InlineAsmError(span, msg, level, source)) => {
1996 assert_matches!(level, Level::Error | Level::Warning | Level::Note);
1997 let mut err = Diag::<()>::new(sess.dcx(), level, msg);
1998 if !span.is_dummy() {
1999 err.span(span.span());
2000 }
2001
2002 if let Some((buffer, spans)) = source {
2004 let source = sess
2005 .source_map()
2006 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2007 let spans: Vec<_> = spans
2008 .iter()
2009 .map(|sp| {
2010 Span::with_root_ctxt(
2011 source.normalized_byte_pos(sp.start as u32),
2012 source.normalized_byte_pos(sp.end as u32),
2013 )
2014 })
2015 .collect();
2016 err.span_note(spans, "instantiated into assembly here");
2017 }
2018
2019 err.emit();
2020 }
2021 Ok(SharedEmitterMessage::Fatal(msg)) => {
2022 sess.dcx().fatal(msg);
2023 }
2024 Err(_) => {
2025 break;
2026 }
2027 }
2028 }
2029 }
2030}
2031
2032pub struct Coordinator<B: ExtraBackendMethods> {
2033 pub sender: Sender<Box<dyn Any + Send>>,
2034 future: Option<thread::JoinHandle<Result<CompiledModules, ()>>>,
2035 phantom: PhantomData<B>,
2037}
2038
2039impl<B: ExtraBackendMethods> Coordinator<B> {
2040 fn join(mut self) -> std::thread::Result<Result<CompiledModules, ()>> {
2041 self.future.take().unwrap().join()
2042 }
2043}
2044
2045impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
2046 fn drop(&mut self) {
2047 if let Some(future) = self.future.take() {
2048 drop(self.sender.send(Box::new(Message::CodegenAborted::<B>)));
2051 drop(future.join());
2052 }
2053 }
2054}
2055
2056pub struct OngoingCodegen<B: ExtraBackendMethods> {
2057 pub backend: B,
2058 pub metadata: EncodedMetadata,
2059 pub metadata_module: Option<CompiledModule>,
2060 pub crate_info: CrateInfo,
2061 pub codegen_worker_receive: Receiver<CguMessage>,
2062 pub shared_emitter_main: SharedEmitterMain,
2063 pub output_filenames: Arc<OutputFilenames>,
2064 pub coordinator: Coordinator<B>,
2065}
2066
2067impl<B: ExtraBackendMethods> OngoingCodegen<B> {
2068 pub fn join(self, sess: &Session) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
2069 self.shared_emitter_main.check(sess, true);
2070 let compiled_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2071 Ok(Ok(compiled_modules)) => compiled_modules,
2072 Ok(Err(())) => {
2073 sess.dcx().abort_if_errors();
2074 panic!("expected abort due to worker thread errors")
2075 }
2076 Err(_) => {
2077 bug!("panic during codegen/LLVM phase");
2078 }
2079 });
2080
2081 sess.dcx().abort_if_errors();
2082
2083 let work_products =
2084 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
2085 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
2086
2087 if sess.codegen_units().as_usize() == 1 && sess.opts.unstable_opts.time_llvm_passes {
2090 self.backend.print_pass_timings()
2091 }
2092
2093 if sess.print_llvm_stats() {
2094 self.backend.print_statistics()
2095 }
2096
2097 (
2098 CodegenResults {
2099 metadata: self.metadata,
2100 crate_info: self.crate_info,
2101
2102 modules: compiled_modules.modules,
2103 allocator_module: compiled_modules.allocator_module,
2104 metadata_module: self.metadata_module,
2105 },
2106 work_products,
2107 )
2108 }
2109
2110 pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2111 self.wait_for_signal_to_codegen_item();
2112 self.check_for_errors(tcx.sess);
2113 drop(self.coordinator.sender.send(Box::new(Message::CodegenComplete::<B>)));
2114 }
2115
2116 pub(crate) fn submit_autodiff_items(&self, items: Vec<AutoDiffItem>) {
2117 drop(self.coordinator.sender.send(Box::new(Message::<B>::AddAutoDiffItems(items))));
2118 }
2119
2120 pub(crate) fn check_for_errors(&self, sess: &Session) {
2121 self.shared_emitter_main.check(sess, false);
2122 }
2123
2124 pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2125 match self.codegen_worker_receive.recv() {
2126 Ok(CguMessage) => {
2127 }
2129 Err(_) => {
2130 }
2133 }
2134 }
2135}
2136
2137pub(crate) fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
2138 _backend: &B,
2139 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
2140 module: ModuleCodegen<B::Module>,
2141 cost: u64,
2142) {
2143 let llvm_work_item = WorkItem::Optimize(module);
2144 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost })));
2145}
2146
2147pub(crate) fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
2148 _backend: &B,
2149 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
2150 module: CachedModuleCodegen,
2151) {
2152 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2153 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost: 0 })));
2154}
2155
2156pub(crate) fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
2157 _backend: &B,
2158 tcx: TyCtxt<'_>,
2159 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
2160 module: CachedModuleCodegen,
2161) {
2162 let filename = pre_lto_bitcode_filename(&module.name);
2163 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2164 let file = fs::File::open(&bc_path)
2165 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
2166
2167 let mmap = unsafe {
2168 Mmap::map(file).unwrap_or_else(|e| {
2169 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2170 })
2171 };
2172 drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule::<B> {
2174 module_data: SerializedModule::FromUncompressedFile(mmap),
2175 work_product: module.source,
2176 })));
2177}
2178
2179fn pre_lto_bitcode_filename(module_name: &str) -> String {
2180 format!("{module_name}.{PRE_LTO_BC_EXT}")
2181}
2182
2183fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2184 assert!(
2187 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2188 && tcx.sess.target.is_like_windows
2189 && tcx.sess.opts.cg.prefer_dynamic)
2190 );
2191
2192 let can_have_static_objects =
2196 tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
2197
2198 tcx.sess.target.is_like_windows &&
2199 can_have_static_objects &&
2200 !tcx.sess.opts.cg.linker_plugin_lto.enabled()
2204}