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 =
420 unsafe { module.autodiff(cgcx, autodiff, config).unwrap_or_else(|e| e.raise()) };
421 }
422 vec![(WorkItem::LTO(module), 0)]
424 } else {
425 if !autodiff.is_empty() {
426 let dcx = cgcx.create_dcx();
427 dcx.handle().emit_fatal(AutodiffWithoutLto {});
428 }
429 assert!(needs_fat_lto.is_empty());
430 let (lto_modules, copy_jobs) = B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules)
431 .unwrap_or_else(|e| e.raise());
432 lto_modules
433 .into_iter()
434 .map(|module| {
435 let cost = module.cost();
436 (WorkItem::LTO(module), cost)
437 })
438 .chain(copy_jobs.into_iter().map(|wp| {
439 (
440 WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
441 name: wp.cgu_name.clone(),
442 source: wp,
443 }),
444 0, )
446 }))
447 .collect()
448 }
449}
450
451struct CompiledModules {
452 modules: Vec<CompiledModule>,
453 allocator_module: Option<CompiledModule>,
454}
455
456fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
457 let sess = tcx.sess;
458 sess.opts.cg.embed_bitcode
459 && tcx.crate_types().contains(&CrateType::Rlib)
460 && sess.opts.output_types.contains_key(&OutputType::Exe)
461}
462
463fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
464 if sess.opts.incremental.is_none() {
465 return false;
466 }
467
468 match sess.lto() {
469 Lto::No => false,
470 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
471 }
472}
473
474pub(crate) fn start_async_codegen<B: ExtraBackendMethods>(
475 backend: B,
476 tcx: TyCtxt<'_>,
477 target_cpu: String,
478 metadata: EncodedMetadata,
479 metadata_module: Option<CompiledModule>,
480) -> OngoingCodegen<B> {
481 let (coordinator_send, coordinator_receive) = channel();
482
483 let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
484 let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
485
486 let crate_info = CrateInfo::new(tcx, target_cpu);
487
488 let regular_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
489 let metadata_config = ModuleConfig::new(ModuleKind::Metadata, tcx, no_builtins);
490 let allocator_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
491
492 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
493 let (codegen_worker_send, codegen_worker_receive) = channel();
494
495 let coordinator_thread = start_executing_work(
496 backend.clone(),
497 tcx,
498 &crate_info,
499 shared_emitter,
500 codegen_worker_send,
501 coordinator_receive,
502 Arc::new(regular_config),
503 Arc::new(metadata_config),
504 Arc::new(allocator_config),
505 coordinator_send.clone(),
506 );
507
508 OngoingCodegen {
509 backend,
510 metadata,
511 metadata_module,
512 crate_info,
513
514 codegen_worker_receive,
515 shared_emitter_main,
516 coordinator: Coordinator {
517 sender: coordinator_send,
518 future: Some(coordinator_thread),
519 phantom: PhantomData,
520 },
521 output_filenames: Arc::clone(tcx.output_filenames(())),
522 }
523}
524
525fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
526 sess: &Session,
527 compiled_modules: &CompiledModules,
528) -> FxIndexMap<WorkProductId, WorkProduct> {
529 let mut work_products = FxIndexMap::default();
530
531 if sess.opts.incremental.is_none() {
532 return work_products;
533 }
534
535 let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
536
537 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
538 let mut files = Vec::new();
539 if let Some(object_file_path) = &module.object {
540 files.push((OutputType::Object.extension(), object_file_path.as_path()));
541 }
542 if let Some(dwarf_object_file_path) = &module.dwarf_object {
543 files.push(("dwo", dwarf_object_file_path.as_path()));
544 }
545 if let Some(path) = &module.assembly {
546 files.push((OutputType::Assembly.extension(), path.as_path()));
547 }
548 if let Some(path) = &module.llvm_ir {
549 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
550 }
551 if let Some(path) = &module.bytecode {
552 files.push((OutputType::Bitcode.extension(), path.as_path()));
553 }
554 if let Some((id, product)) = copy_cgu_workproduct_to_incr_comp_cache_dir(
555 sess,
556 &module.name,
557 files.as_slice(),
558 &module.links_from_incr_cache,
559 ) {
560 work_products.insert(id, product);
561 }
562 }
563
564 work_products
565}
566
567fn produce_final_output_artifacts(
568 sess: &Session,
569 compiled_modules: &CompiledModules,
570 crate_output: &OutputFilenames,
571) {
572 let mut user_wants_bitcode = false;
573 let mut user_wants_objects = false;
574
575 let copy_gracefully = |from: &Path, to: &OutFileName| match to {
577 OutFileName::Stdout if let Err(e) = copy_to_stdout(from) => {
578 sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
579 }
580 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
581 sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
582 }
583 _ => {}
584 };
585
586 let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
587 if let [module] = &compiled_modules.modules[..] {
588 let path = crate_output.temp_path_for_cgu(
591 output_type,
592 &module.name,
593 sess.invocation_temp.as_deref(),
594 );
595 let output = crate_output.path(output_type);
596 if !output_type.is_text_output() && output.is_tty() {
597 sess.dcx()
598 .emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
599 } else {
600 copy_gracefully(&path, &output);
601 }
602 if !sess.opts.cg.save_temps && !keep_numbered {
603 ensure_removed(sess.dcx(), &path);
605 }
606 } else {
607 if crate_output.outputs.contains_explicit_name(&output_type) {
608 sess.dcx()
611 .emit_warn(errors::IgnoringEmitPath { extension: output_type.extension() });
612 } else if crate_output.single_output_file.is_some() {
613 sess.dcx().emit_warn(errors::IgnoringOutput { extension: output_type.extension() });
616 } else {
617 }
621 }
622 };
623
624 for output_type in crate_output.outputs.keys() {
628 match *output_type {
629 OutputType::Bitcode => {
630 user_wants_bitcode = true;
631 copy_if_one_unit(OutputType::Bitcode, true);
635 }
636 OutputType::ThinLinkBitcode => {
637 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
638 }
639 OutputType::LlvmAssembly => {
640 copy_if_one_unit(OutputType::LlvmAssembly, false);
641 }
642 OutputType::Assembly => {
643 copy_if_one_unit(OutputType::Assembly, false);
644 }
645 OutputType::Object => {
646 user_wants_objects = true;
647 copy_if_one_unit(OutputType::Object, true);
648 }
649 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
650 }
651 }
652
653 if !sess.opts.cg.save_temps {
666 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
682
683 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
684
685 let keep_numbered_objects =
686 needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
687
688 for module in compiled_modules.modules.iter() {
689 if !keep_numbered_objects {
690 if let Some(ref path) = module.object {
691 ensure_removed(sess.dcx(), path);
692 }
693
694 if let Some(ref path) = module.dwarf_object {
695 ensure_removed(sess.dcx(), path);
696 }
697 }
698
699 if let Some(ref path) = module.bytecode {
700 if !keep_numbered_bitcode {
701 ensure_removed(sess.dcx(), path);
702 }
703 }
704 }
705
706 if !user_wants_bitcode
707 && let Some(ref allocator_module) = compiled_modules.allocator_module
708 && let Some(ref path) = allocator_module.bytecode
709 {
710 ensure_removed(sess.dcx(), path);
711 }
712 }
713
714 if sess.opts.json_artifact_notifications {
715 if let [module] = &compiled_modules.modules[..] {
716 module.for_each_output(|_path, ty| {
717 if sess.opts.output_types.contains_key(&ty) {
718 let descr = ty.shorthand();
719 let path = crate_output.path(ty);
722 sess.dcx().emit_artifact_notification(path.as_path(), descr);
723 }
724 });
725 } else {
726 for module in &compiled_modules.modules {
727 module.for_each_output(|path, ty| {
728 if sess.opts.output_types.contains_key(&ty) {
729 let descr = ty.shorthand();
730 sess.dcx().emit_artifact_notification(&path, descr);
731 }
732 });
733 }
734 }
735 }
736
737 }
743
744pub(crate) enum WorkItem<B: WriteBackendMethods> {
745 Optimize(ModuleCodegen<B::Module>),
747 CopyPostLtoArtifacts(CachedModuleCodegen),
750 LTO(lto::LtoModuleCodegen<B>),
752}
753
754impl<B: WriteBackendMethods> WorkItem<B> {
755 fn module_kind(&self) -> ModuleKind {
756 match *self {
757 WorkItem::Optimize(ref m) => m.kind,
758 WorkItem::CopyPostLtoArtifacts(_) | WorkItem::LTO(_) => ModuleKind::Regular,
759 }
760 }
761
762 fn short_description(&self) -> String {
764 #[cfg(not(windows))]
768 fn desc(short: &str, _long: &str, name: &str) -> String {
769 assert_eq!(short.len(), 3);
789 let name = if let Some(index) = name.find("-cgu.") {
790 &name[index + 1..] } else {
792 name
793 };
794 format!("{short} {name}")
795 }
796
797 #[cfg(windows)]
799 fn desc(_short: &str, long: &str, name: &str) -> String {
800 format!("{long} {name}")
801 }
802
803 match self {
804 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
805 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
806 WorkItem::LTO(m) => desc("lto", "LTO module", m.name()),
807 }
808 }
809}
810
811pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
813 Finished(CompiledModule),
815
816 NeedsLink(ModuleCodegen<B::Module>),
819
820 NeedsFatLto(FatLtoInput<B>),
823
824 NeedsThinLto(String, B::ThinBuffer),
827}
828
829pub enum FatLtoInput<B: WriteBackendMethods> {
830 Serialized { name: String, buffer: B::ModuleBuffer },
831 InMemory(ModuleCodegen<B::Module>),
832}
833
834pub(crate) enum ComputedLtoType {
836 No,
837 Thin,
838 Fat,
839}
840
841pub(crate) fn compute_per_cgu_lto_type(
842 sess_lto: &Lto,
843 opts: &config::Options,
844 sess_crate_types: &[CrateType],
845 module_kind: ModuleKind,
846) -> ComputedLtoType {
847 if module_kind == ModuleKind::Metadata {
850 return ComputedLtoType::No;
851 }
852
853 let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
857
858 let is_allocator = module_kind == ModuleKind::Allocator;
863
864 let is_rlib = matches!(sess_crate_types, [CrateType::Rlib]);
873
874 match sess_lto {
875 Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
876 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
877 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
878 _ => ComputedLtoType::No,
879 }
880}
881
882fn execute_optimize_work_item<B: ExtraBackendMethods>(
883 cgcx: &CodegenContext<B>,
884 mut module: ModuleCodegen<B::Module>,
885 module_config: &ModuleConfig,
886) -> Result<WorkItemResult<B>, FatalError> {
887 let dcx = cgcx.create_dcx();
888 let dcx = dcx.handle();
889
890 unsafe {
891 B::optimize(cgcx, dcx, &mut module, module_config)?;
892 }
893
894 let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
900
901 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
904 let filename = pre_lto_bitcode_filename(&module.name);
905 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
906 } else {
907 None
908 };
909
910 match lto_type {
911 ComputedLtoType::No => finish_intra_module_work(cgcx, module, module_config),
912 ComputedLtoType::Thin => {
913 let (name, thin_buffer) = B::prepare_thin(module, false);
914 if let Some(path) = bitcode {
915 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
916 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
917 });
918 }
919 Ok(WorkItemResult::NeedsThinLto(name, thin_buffer))
920 }
921 ComputedLtoType::Fat => match bitcode {
922 Some(path) => {
923 let (name, buffer) = B::serialize_module(module);
924 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
925 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
926 });
927 Ok(WorkItemResult::NeedsFatLto(FatLtoInput::Serialized { name, buffer }))
928 }
929 None => Ok(WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module))),
930 },
931 }
932}
933
934fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
935 cgcx: &CodegenContext<B>,
936 module: CachedModuleCodegen,
937 module_config: &ModuleConfig,
938) -> WorkItemResult<B> {
939 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
940
941 let mut links_from_incr_cache = Vec::new();
942
943 let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
944 let source_file = in_incr_comp_dir(incr_comp_session_dir, saved_path);
945 debug!(
946 "copying preexisting module `{}` from {:?} to {}",
947 module.name,
948 source_file,
949 output_path.display()
950 );
951 match link_or_copy(&source_file, &output_path) {
952 Ok(_) => {
953 links_from_incr_cache.push(source_file);
954 Some(output_path)
955 }
956 Err(error) => {
957 cgcx.create_dcx().handle().emit_err(errors::CopyPathBuf {
958 source_file,
959 output_path,
960 error,
961 });
962 None
963 }
964 }
965 };
966
967 let dwarf_object =
968 module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
969 let dwarf_obj_out = cgcx
970 .output_filenames
971 .split_dwarf_path(
972 cgcx.split_debuginfo,
973 cgcx.split_dwarf_kind,
974 &module.name,
975 cgcx.invocation_temp.as_deref(),
976 )
977 .expect(
978 "saved dwarf object in work product but `split_dwarf_path` returned `None`",
979 );
980 load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
981 });
982
983 let mut load_from_incr_cache = |perform, output_type: OutputType| {
984 if perform {
985 let saved_file = module.source.saved_files.get(output_type.extension())?;
986 let output_path = cgcx.output_filenames.temp_path_for_cgu(
987 output_type,
988 &module.name,
989 cgcx.invocation_temp.as_deref(),
990 );
991 load_from_incr_comp_dir(output_path, &saved_file)
992 } else {
993 None
994 }
995 };
996
997 let should_emit_obj = module_config.emit_obj != EmitObj::None;
998 let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
999 let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
1000 let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
1001 let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
1002 if should_emit_obj && object.is_none() {
1003 cgcx.create_dcx().handle().emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
1004 }
1005
1006 WorkItemResult::Finished(CompiledModule {
1007 links_from_incr_cache,
1008 name: module.name,
1009 kind: ModuleKind::Regular,
1010 object,
1011 dwarf_object,
1012 bytecode,
1013 assembly,
1014 llvm_ir,
1015 })
1016}
1017
1018fn execute_lto_work_item<B: ExtraBackendMethods>(
1019 cgcx: &CodegenContext<B>,
1020 module: lto::LtoModuleCodegen<B>,
1021 module_config: &ModuleConfig,
1022) -> Result<WorkItemResult<B>, FatalError> {
1023 let module = unsafe { module.optimize(cgcx)? };
1024 finish_intra_module_work(cgcx, module, module_config)
1025}
1026
1027fn finish_intra_module_work<B: ExtraBackendMethods>(
1028 cgcx: &CodegenContext<B>,
1029 module: ModuleCodegen<B::Module>,
1030 module_config: &ModuleConfig,
1031) -> Result<WorkItemResult<B>, FatalError> {
1032 let dcx = cgcx.create_dcx();
1033 let dcx = dcx.handle();
1034
1035 if !cgcx.opts.unstable_opts.combine_cgu
1036 || module.kind == ModuleKind::Metadata
1037 || module.kind == ModuleKind::Allocator
1038 {
1039 let module = unsafe { B::codegen(cgcx, dcx, module, module_config)? };
1040 Ok(WorkItemResult::Finished(module))
1041 } else {
1042 Ok(WorkItemResult::NeedsLink(module))
1043 }
1044}
1045
1046pub(crate) enum Message<B: WriteBackendMethods> {
1048 Token(io::Result<Acquired>),
1051
1052 WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>>, worker_id: usize },
1055
1056 AddAutoDiffItems(Vec<AutoDiffItem>),
1058
1059 CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
1063
1064 AddImportOnlyModule {
1067 module_data: SerializedModule<B::ModuleBuffer>,
1068 work_product: WorkProduct,
1069 },
1070
1071 CodegenComplete,
1074
1075 CodegenAborted,
1078}
1079
1080pub struct CguMessage;
1083
1084struct Diagnostic {
1094 level: Level,
1095 messages: Vec<(DiagMessage, Style)>,
1096 code: Option<ErrCode>,
1097 children: Vec<Subdiagnostic>,
1098 args: DiagArgMap,
1099}
1100
1101pub(crate) struct Subdiagnostic {
1105 level: Level,
1106 messages: Vec<(DiagMessage, Style)>,
1107}
1108
1109#[derive(PartialEq, Clone, Copy, Debug)]
1110enum MainThreadState {
1111 Idle,
1113
1114 Codegenning,
1116
1117 Lending,
1119}
1120
1121fn start_executing_work<B: ExtraBackendMethods>(
1122 backend: B,
1123 tcx: TyCtxt<'_>,
1124 crate_info: &CrateInfo,
1125 shared_emitter: SharedEmitter,
1126 codegen_worker_send: Sender<CguMessage>,
1127 coordinator_receive: Receiver<Box<dyn Any + Send>>,
1128 regular_config: Arc<ModuleConfig>,
1129 metadata_config: Arc<ModuleConfig>,
1130 allocator_config: Arc<ModuleConfig>,
1131 tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
1132) -> thread::JoinHandle<Result<CompiledModules, ()>> {
1133 let coordinator_send = tx_to_llvm_workers;
1134 let sess = tcx.sess;
1135
1136 let mut each_linked_rlib_for_lto = Vec::new();
1137 drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| {
1138 if link::ignored_for_lto(sess, crate_info, cnum) {
1139 return;
1140 }
1141 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1142 }));
1143
1144 let exported_symbols = {
1146 let mut exported_symbols = FxHashMap::default();
1147
1148 let copy_symbols = |cnum| {
1149 let symbols = tcx
1150 .exported_symbols(cnum)
1151 .iter()
1152 .map(|&(s, lvl)| (symbol_name_for_instance_in_crate(tcx, s, cnum), lvl))
1153 .collect();
1154 Arc::new(symbols)
1155 };
1156
1157 match sess.lto() {
1158 Lto::No => None,
1159 Lto::ThinLocal => {
1160 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1161 Some(Arc::new(exported_symbols))
1162 }
1163 Lto::Fat | Lto::Thin => {
1164 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1165 for &(cnum, ref _path) in &each_linked_rlib_for_lto {
1166 exported_symbols.insert(cnum, copy_symbols(cnum));
1167 }
1168 Some(Arc::new(exported_symbols))
1169 }
1170 }
1171 };
1172
1173 let coordinator_send2 = coordinator_send.clone();
1179 let helper = jobserver::client()
1180 .into_helper_thread(move |token| {
1181 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
1182 })
1183 .expect("failed to spawn helper thread");
1184
1185 let ol =
1186 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
1187 config::OptLevel::No
1189 } else {
1190 tcx.backend_optimization_level(())
1191 };
1192 let backend_features = tcx.global_backend_features(());
1193
1194 let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1195 let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1196 match result {
1197 Ok(dir) => Some(dir),
1198 Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1199 }
1200 } else {
1201 None
1202 };
1203
1204 let cgcx = CodegenContext::<B> {
1205 crate_types: tcx.crate_types().to_vec(),
1206 each_linked_rlib_for_lto,
1207 lto: sess.lto(),
1208 fewer_names: sess.fewer_names(),
1209 save_temps: sess.opts.cg.save_temps,
1210 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1211 opts: Arc::new(sess.opts.clone()),
1212 prof: sess.prof.clone(),
1213 exported_symbols,
1214 remark: sess.opts.cg.remark.clone(),
1215 remark_dir,
1216 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1217 coordinator_send,
1218 expanded_args: tcx.sess.expanded_args.clone(),
1219 diag_emitter: shared_emitter.clone(),
1220 output_filenames: Arc::clone(tcx.output_filenames(())),
1221 regular_module_config: regular_config,
1222 metadata_module_config: metadata_config,
1223 allocator_module_config: allocator_config,
1224 tm_factory: backend.target_machine_factory(tcx.sess, ol, backend_features),
1225 msvc_imps_needed: msvc_imps_needed(tcx),
1226 is_pe_coff: tcx.sess.target.is_like_windows,
1227 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1228 target_arch: tcx.sess.target.arch.to_string(),
1229 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1230 target_is_like_aix: tcx.sess.target.is_like_aix,
1231 split_debuginfo: tcx.sess.split_debuginfo(),
1232 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1233 parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1234 pointer_size: tcx.data_layout.pointer_size,
1235 invocation_temp: sess.invocation_temp.clone(),
1236 };
1237
1238 return B::spawn_named_thread(cgcx.time_trace, "coordinator".to_string(), move || {
1374 let mut worker_id_counter = 0;
1375 let mut free_worker_ids = Vec::new();
1376 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1377 if let Some(id) = free_worker_ids.pop() {
1378 id
1379 } else {
1380 let id = worker_id_counter;
1381 worker_id_counter += 1;
1382 id
1383 }
1384 };
1385
1386 let mut autodiff_items = Vec::new();
1389 let mut compiled_modules = vec![];
1390 let mut compiled_allocator_module = None;
1391 let mut needs_link = Vec::new();
1392 let mut needs_fat_lto = Vec::new();
1393 let mut needs_thin_lto = Vec::new();
1394 let mut lto_import_only_modules = Vec::new();
1395 let mut started_lto = false;
1396
1397 #[derive(Debug, PartialEq)]
1402 enum CodegenState {
1403 Ongoing,
1404 Completed,
1405 Aborted,
1406 }
1407 use CodegenState::*;
1408 let mut codegen_state = Ongoing;
1409
1410 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1412
1413 let mut tokens = Vec::new();
1416
1417 let mut main_thread_state = MainThreadState::Idle;
1418
1419 let mut running_with_own_token = 0;
1422
1423 let running_with_any_token = |main_thread_state, running_with_own_token| {
1426 running_with_own_token
1427 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1428 };
1429
1430 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1431
1432 loop {
1438 if codegen_state == Ongoing {
1442 if main_thread_state == MainThreadState::Idle {
1443 let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1451 let additional_running = std::cmp::min(extra_tokens, work_items.len());
1452 let anticipated_running = running_with_own_token + additional_running + 1;
1453
1454 if !queue_full_enough(work_items.len(), anticipated_running) {
1455 if codegen_worker_send.send(CguMessage).is_err() {
1457 panic!("Could not send CguMessage to main thread")
1458 }
1459 main_thread_state = MainThreadState::Codegenning;
1460 } else {
1461 let (item, _) =
1465 work_items.pop().expect("queue empty - queue_full_enough() broken?");
1466 main_thread_state = MainThreadState::Lending;
1467 spawn_work(
1468 &cgcx,
1469 &mut llvm_start_time,
1470 get_worker_id(&mut free_worker_ids),
1471 item,
1472 );
1473 }
1474 }
1475 } else if codegen_state == Completed {
1476 if running_with_any_token(main_thread_state, running_with_own_token) == 0
1477 && work_items.is_empty()
1478 {
1479 if needs_fat_lto.is_empty()
1481 && needs_thin_lto.is_empty()
1482 && lto_import_only_modules.is_empty()
1483 {
1484 break;
1486 }
1487
1488 assert!(!started_lto);
1494 started_lto = true;
1495
1496 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1497 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1498 let import_only_modules = mem::take(&mut lto_import_only_modules);
1499
1500 for (work, cost) in generate_lto_work(
1501 &cgcx,
1502 autodiff_items.clone(),
1503 needs_fat_lto,
1504 needs_thin_lto,
1505 import_only_modules,
1506 ) {
1507 let insertion_index = work_items
1508 .binary_search_by_key(&cost, |&(_, cost)| cost)
1509 .unwrap_or_else(|e| e);
1510 work_items.insert(insertion_index, (work, cost));
1511 if cgcx.parallel {
1512 helper.request_token();
1513 }
1514 }
1515 }
1516
1517 match main_thread_state {
1521 MainThreadState::Idle => {
1522 if let Some((item, _)) = work_items.pop() {
1523 main_thread_state = MainThreadState::Lending;
1524 spawn_work(
1525 &cgcx,
1526 &mut llvm_start_time,
1527 get_worker_id(&mut free_worker_ids),
1528 item,
1529 );
1530 } else {
1531 assert!(running_with_own_token > 0);
1538 running_with_own_token -= 1;
1539 main_thread_state = MainThreadState::Lending;
1540 }
1541 }
1542 MainThreadState::Codegenning => bug!(
1543 "codegen worker should not be codegenning after \
1544 codegen was already completed"
1545 ),
1546 MainThreadState::Lending => {
1547 }
1549 }
1550 } else {
1551 assert!(codegen_state == Aborted);
1554 if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1555 break;
1556 }
1557 }
1558
1559 if codegen_state != Aborted {
1562 while running_with_own_token < tokens.len()
1563 && let Some((item, _)) = work_items.pop()
1564 {
1565 spawn_work(
1566 &cgcx,
1567 &mut llvm_start_time,
1568 get_worker_id(&mut free_worker_ids),
1569 item,
1570 );
1571 running_with_own_token += 1;
1572 }
1573 }
1574
1575 tokens.truncate(running_with_own_token);
1577
1578 let mut free_worker = |worker_id| {
1584 if main_thread_state == MainThreadState::Lending {
1585 main_thread_state = MainThreadState::Idle;
1586 } else {
1587 running_with_own_token -= 1;
1588 }
1589
1590 free_worker_ids.push(worker_id);
1591 };
1592
1593 let msg = coordinator_receive.recv().unwrap();
1594 match *msg.downcast::<Message<B>>().ok().unwrap() {
1595 Message::Token(token) => {
1599 match token {
1600 Ok(token) => {
1601 tokens.push(token);
1602
1603 if main_thread_state == MainThreadState::Lending {
1604 main_thread_state = MainThreadState::Idle;
1609 running_with_own_token += 1;
1610 }
1611 }
1612 Err(e) => {
1613 let msg = &format!("failed to acquire jobserver token: {e}");
1614 shared_emitter.fatal(msg);
1615 codegen_state = Aborted;
1616 }
1617 }
1618 }
1619
1620 Message::CodegenDone { llvm_work_item, cost } => {
1621 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1630 let insertion_index = match insertion_index {
1631 Ok(idx) | Err(idx) => idx,
1632 };
1633 work_items.insert(insertion_index, (llvm_work_item, cost));
1634
1635 if cgcx.parallel {
1636 helper.request_token();
1637 }
1638 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1639 main_thread_state = MainThreadState::Idle;
1640 }
1641
1642 Message::AddAutoDiffItems(mut items) => {
1643 autodiff_items.append(&mut items);
1644 }
1645
1646 Message::CodegenComplete => {
1647 if codegen_state != Aborted {
1648 codegen_state = Completed;
1649 }
1650 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1651 main_thread_state = MainThreadState::Idle;
1652 }
1653
1654 Message::CodegenAborted => {
1662 codegen_state = Aborted;
1663 }
1664
1665 Message::WorkItem { result, worker_id } => {
1666 free_worker(worker_id);
1667
1668 match result {
1669 Ok(WorkItemResult::Finished(compiled_module)) => {
1670 match compiled_module.kind {
1671 ModuleKind::Regular => {
1672 assert!(needs_link.is_empty());
1673 compiled_modules.push(compiled_module);
1674 }
1675 ModuleKind::Allocator => {
1676 assert!(compiled_allocator_module.is_none());
1677 compiled_allocator_module = Some(compiled_module);
1678 }
1679 ModuleKind::Metadata => bug!("Should be handled separately"),
1680 }
1681 }
1682 Ok(WorkItemResult::NeedsLink(module)) => {
1683 assert!(compiled_modules.is_empty());
1684 needs_link.push(module);
1685 }
1686 Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1687 assert!(!started_lto);
1688 assert!(needs_thin_lto.is_empty());
1689 needs_fat_lto.push(fat_lto_input);
1690 }
1691 Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1692 assert!(!started_lto);
1693 assert!(needs_fat_lto.is_empty());
1694 needs_thin_lto.push((name, thin_buffer));
1695 }
1696 Err(Some(WorkerFatalError)) => {
1697 codegen_state = Aborted;
1699 }
1700 Err(None) => {
1701 bug!("worker thread panicked");
1704 }
1705 }
1706 }
1707
1708 Message::AddImportOnlyModule { module_data, work_product } => {
1709 assert!(!started_lto);
1710 assert_eq!(codegen_state, Ongoing);
1711 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1712 lto_import_only_modules.push((module_data, work_product));
1713 main_thread_state = MainThreadState::Idle;
1714 }
1715 }
1716 }
1717
1718 if codegen_state == Aborted {
1719 return Err(());
1720 }
1721
1722 let needs_link = mem::take(&mut needs_link);
1723 if !needs_link.is_empty() {
1724 assert!(compiled_modules.is_empty());
1725 let dcx = cgcx.create_dcx();
1726 let dcx = dcx.handle();
1727 let module = B::run_link(&cgcx, dcx, needs_link).map_err(|_| ())?;
1728 let module = unsafe {
1729 B::codegen(&cgcx, dcx, module, cgcx.config(ModuleKind::Regular)).map_err(|_| ())?
1730 };
1731 compiled_modules.push(module);
1732 }
1733
1734 drop(llvm_start_time);
1736
1737 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1741
1742 Ok(CompiledModules {
1743 modules: compiled_modules,
1744 allocator_module: compiled_allocator_module,
1745 })
1746 })
1747 .expect("failed to spawn coordinator thread");
1748
1749 fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1752 let quarter_of_workers = workers_running - 3 * workers_running / 4;
1803 items_in_queue > 0 && items_in_queue >= quarter_of_workers
1804 }
1805}
1806
1807#[must_use]
1809pub(crate) struct WorkerFatalError;
1810
1811fn spawn_work<'a, B: ExtraBackendMethods>(
1812 cgcx: &'a CodegenContext<B>,
1813 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1814 worker_id: usize,
1815 work: WorkItem<B>,
1816) {
1817 if cgcx.config(work.module_kind()).time_module && llvm_start_time.is_none() {
1818 *llvm_start_time = Some(cgcx.prof.verbose_generic_activity("LLVM_passes"));
1819 }
1820
1821 let cgcx = cgcx.clone();
1822
1823 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1824 struct Bomb<B: ExtraBackendMethods> {
1827 coordinator_send: Sender<Box<dyn Any + Send>>,
1828 result: Option<Result<WorkItemResult<B>, FatalError>>,
1829 worker_id: usize,
1830 }
1831 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1832 fn drop(&mut self) {
1833 let worker_id = self.worker_id;
1834 let msg = match self.result.take() {
1835 Some(Ok(result)) => Message::WorkItem::<B> { result: Ok(result), worker_id },
1836 Some(Err(FatalError)) => {
1837 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)), worker_id }
1838 }
1839 None => Message::WorkItem::<B> { result: Err(None), worker_id },
1840 };
1841 drop(self.coordinator_send.send(Box::new(msg)));
1842 }
1843 }
1844
1845 let mut bomb =
1846 Bomb::<B> { coordinator_send: cgcx.coordinator_send.clone(), result: None, worker_id };
1847
1848 bomb.result = {
1855 let module_config = cgcx.config(work.module_kind());
1856
1857 Some(match work {
1858 WorkItem::Optimize(m) => {
1859 let _timer =
1860 cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &*m.name);
1861 execute_optimize_work_item(&cgcx, m, module_config)
1862 }
1863 WorkItem::CopyPostLtoArtifacts(m) => {
1864 let _timer = cgcx.prof.generic_activity_with_arg(
1865 "codegen_copy_artifacts_from_incr_cache",
1866 &*m.name,
1867 );
1868 Ok(execute_copy_from_cache_work_item(&cgcx, m, module_config))
1869 }
1870 WorkItem::LTO(m) => {
1871 let _timer =
1872 cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name());
1873 execute_lto_work_item(&cgcx, m, module_config)
1874 }
1875 })
1876 };
1877 })
1878 .expect("failed to spawn work thread");
1879}
1880
1881enum SharedEmitterMessage {
1882 Diagnostic(Diagnostic),
1883 InlineAsmError(SpanData, String, Level, Option<(String, Vec<InnerSpan>)>),
1884 Fatal(String),
1885}
1886
1887#[derive(Clone)]
1888pub struct SharedEmitter {
1889 sender: Sender<SharedEmitterMessage>,
1890}
1891
1892pub struct SharedEmitterMain {
1893 receiver: Receiver<SharedEmitterMessage>,
1894}
1895
1896impl SharedEmitter {
1897 fn new() -> (SharedEmitter, SharedEmitterMain) {
1898 let (sender, receiver) = channel();
1899
1900 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1901 }
1902
1903 pub fn inline_asm_error(
1904 &self,
1905 span: SpanData,
1906 msg: String,
1907 level: Level,
1908 source: Option<(String, Vec<InnerSpan>)>,
1909 ) {
1910 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(span, msg, level, source)));
1911 }
1912
1913 fn fatal(&self, msg: &str) {
1914 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1915 }
1916}
1917
1918impl Translate for SharedEmitter {
1919 fn fluent_bundle(&self) -> Option<&FluentBundle> {
1920 None
1921 }
1922
1923 fn fallback_fluent_bundle(&self) -> &FluentBundle {
1924 panic!("shared emitter attempted to translate a diagnostic");
1925 }
1926}
1927
1928impl Emitter for SharedEmitter {
1929 fn emit_diagnostic(
1930 &mut self,
1931 mut diag: rustc_errors::DiagInner,
1932 _registry: &rustc_errors::registry::Registry,
1933 ) {
1934 assert_eq!(diag.span, MultiSpan::new());
1937 assert_eq!(diag.suggestions, Suggestions::Enabled(vec![]));
1938 assert_eq!(diag.sort_span, rustc_span::DUMMY_SP);
1939 assert_eq!(diag.is_lint, None);
1940 let args = mem::replace(&mut diag.args, DiagArgMap::default());
1943 drop(
1944 self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1945 level: diag.level(),
1946 messages: diag.messages,
1947 code: diag.code,
1948 children: diag
1949 .children
1950 .into_iter()
1951 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
1952 .collect(),
1953 args,
1954 })),
1955 );
1956 }
1957
1958 fn source_map(&self) -> Option<&SourceMap> {
1959 None
1960 }
1961}
1962
1963impl SharedEmitterMain {
1964 fn check(&self, sess: &Session, blocking: bool) {
1965 loop {
1966 let message = if blocking {
1967 match self.receiver.recv() {
1968 Ok(message) => Ok(message),
1969 Err(_) => Err(()),
1970 }
1971 } else {
1972 match self.receiver.try_recv() {
1973 Ok(message) => Ok(message),
1974 Err(_) => Err(()),
1975 }
1976 };
1977
1978 match message {
1979 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1980 let dcx = sess.dcx();
1983 let mut d =
1984 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
1985 d.code = diag.code; d.children = diag
1987 .children
1988 .into_iter()
1989 .map(|sub| rustc_errors::Subdiag {
1990 level: sub.level,
1991 messages: sub.messages,
1992 span: MultiSpan::new(),
1993 })
1994 .collect();
1995 d.args = diag.args;
1996 dcx.emit_diagnostic(d);
1997 sess.dcx().abort_if_errors();
1998 }
1999 Ok(SharedEmitterMessage::InlineAsmError(span, msg, level, source)) => {
2000 assert_matches!(level, Level::Error | Level::Warning | Level::Note);
2001 let mut err = Diag::<()>::new(sess.dcx(), level, msg);
2002 if !span.is_dummy() {
2003 err.span(span.span());
2004 }
2005
2006 if let Some((buffer, spans)) = source {
2008 let source = sess
2009 .source_map()
2010 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2011 let spans: Vec<_> = spans
2012 .iter()
2013 .map(|sp| {
2014 Span::with_root_ctxt(
2015 source.normalized_byte_pos(sp.start as u32),
2016 source.normalized_byte_pos(sp.end as u32),
2017 )
2018 })
2019 .collect();
2020 err.span_note(spans, "instantiated into assembly here");
2021 }
2022
2023 err.emit();
2024 }
2025 Ok(SharedEmitterMessage::Fatal(msg)) => {
2026 sess.dcx().fatal(msg);
2027 }
2028 Err(_) => {
2029 break;
2030 }
2031 }
2032 }
2033 }
2034}
2035
2036pub struct Coordinator<B: ExtraBackendMethods> {
2037 pub sender: Sender<Box<dyn Any + Send>>,
2038 future: Option<thread::JoinHandle<Result<CompiledModules, ()>>>,
2039 phantom: PhantomData<B>,
2041}
2042
2043impl<B: ExtraBackendMethods> Coordinator<B> {
2044 fn join(mut self) -> std::thread::Result<Result<CompiledModules, ()>> {
2045 self.future.take().unwrap().join()
2046 }
2047}
2048
2049impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
2050 fn drop(&mut self) {
2051 if let Some(future) = self.future.take() {
2052 drop(self.sender.send(Box::new(Message::CodegenAborted::<B>)));
2055 drop(future.join());
2056 }
2057 }
2058}
2059
2060pub struct OngoingCodegen<B: ExtraBackendMethods> {
2061 pub backend: B,
2062 pub metadata: EncodedMetadata,
2063 pub metadata_module: Option<CompiledModule>,
2064 pub crate_info: CrateInfo,
2065 pub codegen_worker_receive: Receiver<CguMessage>,
2066 pub shared_emitter_main: SharedEmitterMain,
2067 pub output_filenames: Arc<OutputFilenames>,
2068 pub coordinator: Coordinator<B>,
2069}
2070
2071impl<B: ExtraBackendMethods> OngoingCodegen<B> {
2072 pub fn join(self, sess: &Session) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
2073 self.shared_emitter_main.check(sess, true);
2074 let compiled_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2075 Ok(Ok(compiled_modules)) => compiled_modules,
2076 Ok(Err(())) => {
2077 sess.dcx().abort_if_errors();
2078 panic!("expected abort due to worker thread errors")
2079 }
2080 Err(_) => {
2081 bug!("panic during codegen/LLVM phase");
2082 }
2083 });
2084
2085 sess.dcx().abort_if_errors();
2086
2087 let work_products =
2088 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
2089 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
2090
2091 if sess.codegen_units().as_usize() == 1 && sess.opts.unstable_opts.time_llvm_passes {
2094 self.backend.print_pass_timings()
2095 }
2096
2097 if sess.print_llvm_stats() {
2098 self.backend.print_statistics()
2099 }
2100
2101 (
2102 CodegenResults {
2103 metadata: self.metadata,
2104 crate_info: self.crate_info,
2105
2106 modules: compiled_modules.modules,
2107 allocator_module: compiled_modules.allocator_module,
2108 metadata_module: self.metadata_module,
2109 },
2110 work_products,
2111 )
2112 }
2113
2114 pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2115 self.wait_for_signal_to_codegen_item();
2116 self.check_for_errors(tcx.sess);
2117 drop(self.coordinator.sender.send(Box::new(Message::CodegenComplete::<B>)));
2118 }
2119
2120 pub(crate) fn submit_autodiff_items(&self, items: Vec<AutoDiffItem>) {
2121 drop(self.coordinator.sender.send(Box::new(Message::<B>::AddAutoDiffItems(items))));
2122 }
2123
2124 pub(crate) fn check_for_errors(&self, sess: &Session) {
2125 self.shared_emitter_main.check(sess, false);
2126 }
2127
2128 pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2129 match self.codegen_worker_receive.recv() {
2130 Ok(CguMessage) => {
2131 }
2133 Err(_) => {
2134 }
2137 }
2138 }
2139}
2140
2141pub(crate) fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
2142 _backend: &B,
2143 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
2144 module: ModuleCodegen<B::Module>,
2145 cost: u64,
2146) {
2147 let llvm_work_item = WorkItem::Optimize(module);
2148 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost })));
2149}
2150
2151pub(crate) fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
2152 _backend: &B,
2153 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
2154 module: CachedModuleCodegen,
2155) {
2156 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2157 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost: 0 })));
2158}
2159
2160pub(crate) fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
2161 _backend: &B,
2162 tcx: TyCtxt<'_>,
2163 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
2164 module: CachedModuleCodegen,
2165) {
2166 let filename = pre_lto_bitcode_filename(&module.name);
2167 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2168 let file = fs::File::open(&bc_path)
2169 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
2170
2171 let mmap = unsafe {
2172 Mmap::map(file).unwrap_or_else(|e| {
2173 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2174 })
2175 };
2176 drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule::<B> {
2178 module_data: SerializedModule::FromUncompressedFile(mmap),
2179 work_product: module.source,
2180 })));
2181}
2182
2183fn pre_lto_bitcode_filename(module_name: &str) -> String {
2184 format!("{module_name}.{PRE_LTO_BC_EXT}")
2185}
2186
2187fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2188 assert!(
2191 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2192 && tcx.sess.target.is_like_windows
2193 && tcx.sess.opts.cg.prefer_dynamic)
2194 );
2195
2196 let can_have_static_objects =
2200 tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
2201
2202 tcx.sess.target.is_like_windows &&
2203 can_have_static_objects &&
2204 !tcx.sess.opts.cg.linker_plugin_lto.enabled()
2208}