1use std::assert_matches::assert_matches;
2use std::marker::PhantomData;
3use std::panic::AssertUnwindSafe;
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_data_structures::fx::FxIndexMap;
12use rustc_data_structures::jobserver::{self, Acquired};
13use rustc_data_structures::memmap::Mmap;
14use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
15use rustc_errors::emitter::Emitter;
16use rustc_errors::translation::Translator;
17use rustc_errors::{
18 Diag, DiagArgMap, DiagCtxt, DiagMessage, ErrCode, FatalErrorMarker, Level, MultiSpan, Style,
19 Suggestions,
20};
21use rustc_fs_util::link_or_copy;
22use rustc_incremental::{
23 copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
24};
25use rustc_metadata::fs::copy_to_stdout;
26use rustc_middle::bug;
27use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
28use rustc_middle::ty::TyCtxt;
29use rustc_session::Session;
30use rustc_session::config::{
31 self, CrateType, Lto, OutFileName, OutputFilenames, OutputType, Passes, SwitchWithOptPath,
32};
33use rustc_span::source_map::SourceMap;
34use rustc_span::{FileName, InnerSpan, Span, SpanData, sym};
35use rustc_target::spec::{MergeFunctions, SanitizerSet};
36use tracing::debug;
37
38use super::link::{self, ensure_removed};
39use super::lto::{self, SerializedModule};
40use crate::back::lto::check_lto_allowed;
41use crate::errors::ErrorCreatingRemarkDir;
42use crate::traits::*;
43use crate::{
44 CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
45 errors,
46};
47
48const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
49
50#[derive(Clone, Copy, PartialEq)]
52pub enum EmitObj {
53 None,
55
56 Bitcode,
59
60 ObjectCode(BitcodeSection),
62}
63
64#[derive(Clone, Copy, PartialEq)]
66pub enum BitcodeSection {
67 None,
69
70 Full,
72}
73
74pub struct ModuleConfig {
76 pub passes: Vec<String>,
78 pub opt_level: Option<config::OptLevel>,
81
82 pub pgo_gen: SwitchWithOptPath,
83 pub pgo_use: Option<PathBuf>,
84 pub pgo_sample_use: Option<PathBuf>,
85 pub debug_info_for_profiling: bool,
86 pub instrument_coverage: bool,
87
88 pub sanitizer: SanitizerSet,
89 pub sanitizer_recover: SanitizerSet,
90 pub sanitizer_dataflow_abilist: Vec<String>,
91 pub sanitizer_memory_track_origins: usize,
92
93 pub emit_pre_lto_bc: bool,
95 pub emit_no_opt_bc: bool,
96 pub emit_bc: bool,
97 pub emit_ir: bool,
98 pub emit_asm: bool,
99 pub emit_obj: EmitObj,
100 pub emit_thin_lto: bool,
101 pub emit_thin_lto_summary: bool,
102
103 pub verify_llvm_ir: bool,
106 pub lint_llvm_ir: bool,
107 pub no_prepopulate_passes: bool,
108 pub no_builtins: bool,
109 pub vectorize_loop: bool,
110 pub vectorize_slp: bool,
111 pub merge_functions: bool,
112 pub emit_lifetime_markers: bool,
113 pub llvm_plugins: Vec<String>,
114 pub autodiff: Vec<config::AutoDiff>,
115 pub offload: Vec<config::Offload>,
116}
117
118impl ModuleConfig {
119 fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
120 macro_rules! if_regular {
123 ($regular: expr, $other: expr) => {
124 if let ModuleKind::Regular = kind { $regular } else { $other }
125 };
126 }
127
128 let sess = tcx.sess;
129 let opt_level_and_size = if_regular!(Some(sess.opts.optimize), None);
130
131 let save_temps = sess.opts.cg.save_temps;
132
133 let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
134 || match kind {
135 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
136 ModuleKind::Allocator => false,
137 };
138
139 let emit_obj = if !should_emit_obj {
140 EmitObj::None
141 } else if sess.target.obj_is_bitcode
142 || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
143 {
144 EmitObj::Bitcode
159 } else if need_bitcode_in_object(tcx) {
160 EmitObj::ObjectCode(BitcodeSection::Full)
161 } else {
162 EmitObj::ObjectCode(BitcodeSection::None)
163 };
164
165 ModuleConfig {
166 passes: if_regular!(sess.opts.cg.passes.clone(), vec![]),
167
168 opt_level: opt_level_and_size,
169
170 pgo_gen: if_regular!(
171 sess.opts.cg.profile_generate.clone(),
172 SwitchWithOptPath::Disabled
173 ),
174 pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
175 pgo_sample_use: if_regular!(sess.opts.unstable_opts.profile_sample_use.clone(), None),
176 debug_info_for_profiling: sess.opts.unstable_opts.debug_info_for_profiling,
177 instrument_coverage: if_regular!(sess.instrument_coverage(), false),
178
179 sanitizer: if_regular!(sess.opts.unstable_opts.sanitizer, SanitizerSet::empty()),
180 sanitizer_dataflow_abilist: if_regular!(
181 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
182 Vec::new()
183 ),
184 sanitizer_recover: if_regular!(
185 sess.opts.unstable_opts.sanitizer_recover,
186 SanitizerSet::empty()
187 ),
188 sanitizer_memory_track_origins: if_regular!(
189 sess.opts.unstable_opts.sanitizer_memory_track_origins,
190 0
191 ),
192
193 emit_pre_lto_bc: if_regular!(
194 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
195 false
196 ),
197 emit_no_opt_bc: if_regular!(save_temps, false),
198 emit_bc: if_regular!(
199 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
200 save_temps
201 ),
202 emit_ir: if_regular!(
203 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
204 false
205 ),
206 emit_asm: if_regular!(
207 sess.opts.output_types.contains_key(&OutputType::Assembly),
208 false
209 ),
210 emit_obj,
211 emit_thin_lto: sess.opts.unstable_opts.emit_thin_lto && sess.lto() != Lto::Fat,
214 emit_thin_lto_summary: if_regular!(
215 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
216 false
217 ),
218
219 verify_llvm_ir: sess.verify_llvm_ir(),
220 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
221 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
222 no_builtins: no_builtins || sess.target.no_builtins,
223
224 vectorize_loop: !sess.opts.cg.no_vectorize_loops
227 && (sess.opts.optimize == config::OptLevel::More
228 || sess.opts.optimize == config::OptLevel::Aggressive),
229 vectorize_slp: !sess.opts.cg.no_vectorize_slp
230 && sess.opts.optimize == config::OptLevel::Aggressive,
231
232 merge_functions: match sess
242 .opts
243 .unstable_opts
244 .merge_functions
245 .unwrap_or(sess.target.merge_functions)
246 {
247 MergeFunctions::Disabled => false,
248 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
249 use config::OptLevel::*;
250 match sess.opts.optimize {
251 Aggressive | More | SizeMin | Size => true,
252 Less | No => false,
253 }
254 }
255 },
256
257 emit_lifetime_markers: sess.emit_lifetime_markers(),
258 llvm_plugins: if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
259 autodiff: if_regular!(sess.opts.unstable_opts.autodiff.clone(), vec![]),
260 offload: if_regular!(sess.opts.unstable_opts.offload.clone(), vec![]),
261 }
262 }
263
264 pub fn bitcode_needed(&self) -> bool {
265 self.emit_bc
266 || self.emit_thin_lto_summary
267 || self.emit_obj == EmitObj::Bitcode
268 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
269 }
270
271 pub fn embed_bitcode(&self) -> bool {
272 self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
273 }
274}
275
276pub struct TargetMachineFactoryConfig {
278 pub split_dwarf_file: Option<PathBuf>,
282
283 pub output_obj_file: Option<PathBuf>,
286}
287
288impl TargetMachineFactoryConfig {
289 pub fn new(
290 cgcx: &CodegenContext<impl WriteBackendMethods>,
291 module_name: &str,
292 ) -> TargetMachineFactoryConfig {
293 let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
294 cgcx.output_filenames.split_dwarf_path(
295 cgcx.split_debuginfo,
296 cgcx.split_dwarf_kind,
297 module_name,
298 cgcx.invocation_temp.as_deref(),
299 )
300 } else {
301 None
302 };
303
304 let output_obj_file = Some(cgcx.output_filenames.temp_path_for_cgu(
305 OutputType::Object,
306 module_name,
307 cgcx.invocation_temp.as_deref(),
308 ));
309 TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
310 }
311}
312
313pub type TargetMachineFactoryFn<B> = Arc<
314 dyn Fn(
315 TargetMachineFactoryConfig,
316 ) -> Result<
317 <B as WriteBackendMethods>::TargetMachine,
318 <B as WriteBackendMethods>::TargetMachineError,
319 > + Send
320 + Sync,
321>;
322
323#[derive(Clone)]
325pub struct CodegenContext<B: WriteBackendMethods> {
326 pub prof: SelfProfilerRef,
328 pub lto: Lto,
329 pub save_temps: bool,
330 pub fewer_names: bool,
331 pub time_trace: bool,
332 pub opts: Arc<config::Options>,
333 pub crate_types: Vec<CrateType>,
334 pub output_filenames: Arc<OutputFilenames>,
335 pub invocation_temp: Option<String>,
336 pub module_config: Arc<ModuleConfig>,
337 pub allocator_config: Arc<ModuleConfig>,
338 pub tm_factory: TargetMachineFactoryFn<B>,
339 pub msvc_imps_needed: bool,
340 pub is_pe_coff: bool,
341 pub target_can_use_split_dwarf: bool,
342 pub target_arch: String,
343 pub target_is_like_darwin: bool,
344 pub target_is_like_aix: bool,
345 pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
346 pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
347 pub pointer_size: Size,
348
349 pub expanded_args: Vec<String>,
354
355 pub diag_emitter: SharedEmitter,
357 pub remark: Passes,
359 pub remark_dir: Option<PathBuf>,
362 pub incr_comp_session_dir: Option<PathBuf>,
365 pub parallel: bool,
369}
370
371impl<B: WriteBackendMethods> CodegenContext<B> {
372 pub fn create_dcx(&self) -> DiagCtxt {
373 DiagCtxt::new(Box::new(self.diag_emitter.clone()))
374 }
375}
376
377fn generate_thin_lto_work<B: ExtraBackendMethods>(
378 cgcx: &CodegenContext<B>,
379 exported_symbols_for_lto: &[String],
380 each_linked_rlib_for_lto: &[PathBuf],
381 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
382 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
383) -> Vec<(WorkItem<B>, u64)> {
384 let _prof_timer = cgcx.prof.generic_activity("codegen_thin_generate_lto_work");
385
386 let (lto_modules, copy_jobs) = B::run_thin_lto(
387 cgcx,
388 exported_symbols_for_lto,
389 each_linked_rlib_for_lto,
390 needs_thin_lto,
391 import_only_modules,
392 );
393 lto_modules
394 .into_iter()
395 .map(|module| {
396 let cost = module.cost();
397 (WorkItem::ThinLto(module), cost)
398 })
399 .chain(copy_jobs.into_iter().map(|wp| {
400 (
401 WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
402 name: wp.cgu_name.clone(),
403 source: wp,
404 }),
405 0, )
407 }))
408 .collect()
409}
410
411struct CompiledModules {
412 modules: Vec<CompiledModule>,
413 allocator_module: Option<CompiledModule>,
414}
415
416fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
417 let sess = tcx.sess;
418 sess.opts.cg.embed_bitcode
419 && tcx.crate_types().contains(&CrateType::Rlib)
420 && sess.opts.output_types.contains_key(&OutputType::Exe)
421}
422
423fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
424 if sess.opts.incremental.is_none() {
425 return false;
426 }
427
428 match sess.lto() {
429 Lto::No => false,
430 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
431 }
432}
433
434pub(crate) fn start_async_codegen<B: ExtraBackendMethods>(
435 backend: B,
436 tcx: TyCtxt<'_>,
437 target_cpu: String,
438 allocator_module: Option<ModuleCodegen<B::Module>>,
439) -> OngoingCodegen<B> {
440 let (coordinator_send, coordinator_receive) = channel();
441
442 let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
443 let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
444
445 let crate_info = CrateInfo::new(tcx, target_cpu);
446
447 let regular_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
448 let allocator_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
449
450 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
451 let (codegen_worker_send, codegen_worker_receive) = channel();
452
453 let coordinator_thread = start_executing_work(
454 backend.clone(),
455 tcx,
456 &crate_info,
457 shared_emitter,
458 codegen_worker_send,
459 coordinator_receive,
460 Arc::new(regular_config),
461 Arc::new(allocator_config),
462 allocator_module,
463 coordinator_send.clone(),
464 );
465
466 OngoingCodegen {
467 backend,
468 crate_info,
469
470 codegen_worker_receive,
471 shared_emitter_main,
472 coordinator: Coordinator {
473 sender: coordinator_send,
474 future: Some(coordinator_thread),
475 phantom: PhantomData,
476 },
477 output_filenames: Arc::clone(tcx.output_filenames(())),
478 }
479}
480
481fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
482 sess: &Session,
483 compiled_modules: &CompiledModules,
484) -> FxIndexMap<WorkProductId, WorkProduct> {
485 let mut work_products = FxIndexMap::default();
486
487 if sess.opts.incremental.is_none() {
488 return work_products;
489 }
490
491 let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
492
493 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
494 let mut files = Vec::new();
495 if let Some(object_file_path) = &module.object {
496 files.push((OutputType::Object.extension(), object_file_path.as_path()));
497 }
498 if let Some(dwarf_object_file_path) = &module.dwarf_object {
499 files.push(("dwo", dwarf_object_file_path.as_path()));
500 }
501 if let Some(path) = &module.assembly {
502 files.push((OutputType::Assembly.extension(), path.as_path()));
503 }
504 if let Some(path) = &module.llvm_ir {
505 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
506 }
507 if let Some(path) = &module.bytecode {
508 files.push((OutputType::Bitcode.extension(), path.as_path()));
509 }
510 if let Some((id, product)) = copy_cgu_workproduct_to_incr_comp_cache_dir(
511 sess,
512 &module.name,
513 files.as_slice(),
514 &module.links_from_incr_cache,
515 ) {
516 work_products.insert(id, product);
517 }
518 }
519
520 work_products
521}
522
523fn produce_final_output_artifacts(
524 sess: &Session,
525 compiled_modules: &CompiledModules,
526 crate_output: &OutputFilenames,
527) {
528 let mut user_wants_bitcode = false;
529 let mut user_wants_objects = false;
530
531 let copy_gracefully = |from: &Path, to: &OutFileName| match to {
533 OutFileName::Stdout if let Err(e) = copy_to_stdout(from) => {
534 sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
535 }
536 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
537 sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
538 }
539 _ => {}
540 };
541
542 let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
543 if let [module] = &compiled_modules.modules[..] {
544 let path = crate_output.temp_path_for_cgu(
547 output_type,
548 &module.name,
549 sess.invocation_temp.as_deref(),
550 );
551 let output = crate_output.path(output_type);
552 if !output_type.is_text_output() && output.is_tty() {
553 sess.dcx()
554 .emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
555 } else {
556 copy_gracefully(&path, &output);
557 }
558 if !sess.opts.cg.save_temps && !keep_numbered {
559 ensure_removed(sess.dcx(), &path);
561 }
562 } else {
563 if crate_output.outputs.contains_explicit_name(&output_type) {
564 sess.dcx()
567 .emit_warn(errors::IgnoringEmitPath { extension: output_type.extension() });
568 } else if crate_output.single_output_file.is_some() {
569 sess.dcx().emit_warn(errors::IgnoringOutput { extension: output_type.extension() });
572 } else {
573 }
577 }
578 };
579
580 for output_type in crate_output.outputs.keys() {
584 match *output_type {
585 OutputType::Bitcode => {
586 user_wants_bitcode = true;
587 copy_if_one_unit(OutputType::Bitcode, true);
591 }
592 OutputType::ThinLinkBitcode => {
593 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
594 }
595 OutputType::LlvmAssembly => {
596 copy_if_one_unit(OutputType::LlvmAssembly, false);
597 }
598 OutputType::Assembly => {
599 copy_if_one_unit(OutputType::Assembly, false);
600 }
601 OutputType::Object => {
602 user_wants_objects = true;
603 copy_if_one_unit(OutputType::Object, true);
604 }
605 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
606 }
607 }
608
609 if !sess.opts.cg.save_temps {
622 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
638
639 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
640
641 let keep_numbered_objects =
642 needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
643
644 for module in compiled_modules.modules.iter() {
645 if !keep_numbered_objects {
646 if let Some(ref path) = module.object {
647 ensure_removed(sess.dcx(), path);
648 }
649
650 if let Some(ref path) = module.dwarf_object {
651 ensure_removed(sess.dcx(), path);
652 }
653 }
654
655 if let Some(ref path) = module.bytecode {
656 if !keep_numbered_bitcode {
657 ensure_removed(sess.dcx(), path);
658 }
659 }
660 }
661
662 if !user_wants_bitcode
663 && let Some(ref allocator_module) = compiled_modules.allocator_module
664 && let Some(ref path) = allocator_module.bytecode
665 {
666 ensure_removed(sess.dcx(), path);
667 }
668 }
669
670 if sess.opts.json_artifact_notifications {
671 if let [module] = &compiled_modules.modules[..] {
672 module.for_each_output(|_path, ty| {
673 if sess.opts.output_types.contains_key(&ty) {
674 let descr = ty.shorthand();
675 let path = crate_output.path(ty);
678 sess.dcx().emit_artifact_notification(path.as_path(), descr);
679 }
680 });
681 } else {
682 for module in &compiled_modules.modules {
683 module.for_each_output(|path, ty| {
684 if sess.opts.output_types.contains_key(&ty) {
685 let descr = ty.shorthand();
686 sess.dcx().emit_artifact_notification(&path, descr);
687 }
688 });
689 }
690 }
691 }
692
693 }
699
700pub(crate) enum WorkItem<B: WriteBackendMethods> {
701 Optimize(ModuleCodegen<B::Module>),
703 CopyPostLtoArtifacts(CachedModuleCodegen),
706 FatLto {
708 exported_symbols_for_lto: Arc<Vec<String>>,
709 each_linked_rlib_for_lto: Vec<PathBuf>,
710 needs_fat_lto: Vec<FatLtoInput<B>>,
711 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
712 },
713 ThinLto(lto::ThinModule<B>),
715}
716
717impl<B: WriteBackendMethods> WorkItem<B> {
718 fn short_description(&self) -> String {
720 #[cfg(not(windows))]
724 fn desc(short: &str, _long: &str, name: &str) -> String {
725 assert_eq!(short.len(), 3);
745 let name = if let Some(index) = name.find("-cgu.") {
746 &name[index + 1..] } else {
748 name
749 };
750 format!("{short} {name}")
751 }
752
753 #[cfg(windows)]
755 fn desc(_short: &str, long: &str, name: &str) -> String {
756 format!("{long} {name}")
757 }
758
759 match self {
760 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
761 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
762 WorkItem::FatLto { .. } => desc("lto", "fat LTO module", "everything"),
763 WorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
764 }
765 }
766}
767
768pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
770 Finished(CompiledModule),
772
773 NeedsFatLto(FatLtoInput<B>),
776
777 NeedsThinLto(String, B::ThinBuffer),
780}
781
782pub enum FatLtoInput<B: WriteBackendMethods> {
783 Serialized { name: String, buffer: SerializedModule<B::ModuleBuffer> },
784 InMemory(ModuleCodegen<B::Module>),
785}
786
787pub(crate) enum ComputedLtoType {
789 No,
790 Thin,
791 Fat,
792}
793
794pub(crate) fn compute_per_cgu_lto_type(
795 sess_lto: &Lto,
796 opts: &config::Options,
797 sess_crate_types: &[CrateType],
798 module_kind: ModuleKind,
799) -> ComputedLtoType {
800 let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
804
805 let is_allocator = module_kind == ModuleKind::Allocator;
810
811 let is_rlib = matches!(sess_crate_types, [CrateType::Rlib]);
820
821 match sess_lto {
822 Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
823 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
824 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
825 _ => ComputedLtoType::No,
826 }
827}
828
829fn execute_optimize_work_item<B: ExtraBackendMethods>(
830 cgcx: &CodegenContext<B>,
831 mut module: ModuleCodegen<B::Module>,
832) -> WorkItemResult<B> {
833 let dcx = cgcx.create_dcx();
834 let dcx = dcx.handle();
835
836 let module_config = match module.kind {
837 ModuleKind::Regular => &cgcx.module_config,
838 ModuleKind::Allocator => &cgcx.allocator_config,
839 };
840
841 B::optimize(cgcx, dcx, &mut module, module_config);
842
843 let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
849
850 let bitcode = if module_config.emit_pre_lto_bc {
853 let filename = pre_lto_bitcode_filename(&module.name);
854 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
855 } else {
856 None
857 };
858
859 match lto_type {
860 ComputedLtoType::No => {
861 let module = B::codegen(cgcx, module, module_config);
862 WorkItemResult::Finished(module)
863 }
864 ComputedLtoType::Thin => {
865 let (name, thin_buffer) = B::prepare_thin(module, false);
866 if let Some(path) = bitcode {
867 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
868 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
869 });
870 }
871 WorkItemResult::NeedsThinLto(name, thin_buffer)
872 }
873 ComputedLtoType::Fat => match bitcode {
874 Some(path) => {
875 let (name, buffer) = B::serialize_module(module);
876 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
877 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
878 });
879 WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
880 name,
881 buffer: SerializedModule::Local(buffer),
882 })
883 }
884 None => WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module)),
885 },
886 }
887}
888
889fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
890 cgcx: &CodegenContext<B>,
891 module: CachedModuleCodegen,
892) -> WorkItemResult<B> {
893 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
894
895 let mut links_from_incr_cache = Vec::new();
896
897 let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
898 let source_file = in_incr_comp_dir(incr_comp_session_dir, saved_path);
899 debug!(
900 "copying preexisting module `{}` from {:?} to {}",
901 module.name,
902 source_file,
903 output_path.display()
904 );
905 match link_or_copy(&source_file, &output_path) {
906 Ok(_) => {
907 links_from_incr_cache.push(source_file);
908 Some(output_path)
909 }
910 Err(error) => {
911 cgcx.create_dcx().handle().emit_err(errors::CopyPathBuf {
912 source_file,
913 output_path,
914 error,
915 });
916 None
917 }
918 }
919 };
920
921 let dwarf_object =
922 module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
923 let dwarf_obj_out = cgcx
924 .output_filenames
925 .split_dwarf_path(
926 cgcx.split_debuginfo,
927 cgcx.split_dwarf_kind,
928 &module.name,
929 cgcx.invocation_temp.as_deref(),
930 )
931 .expect(
932 "saved dwarf object in work product but `split_dwarf_path` returned `None`",
933 );
934 load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
935 });
936
937 let mut load_from_incr_cache = |perform, output_type: OutputType| {
938 if perform {
939 let saved_file = module.source.saved_files.get(output_type.extension())?;
940 let output_path = cgcx.output_filenames.temp_path_for_cgu(
941 output_type,
942 &module.name,
943 cgcx.invocation_temp.as_deref(),
944 );
945 load_from_incr_comp_dir(output_path, &saved_file)
946 } else {
947 None
948 }
949 };
950
951 let module_config = &cgcx.module_config;
952 let should_emit_obj = module_config.emit_obj != EmitObj::None;
953 let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
954 let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
955 let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
956 let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
957 if should_emit_obj && object.is_none() {
958 cgcx.create_dcx().handle().emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
959 }
960
961 WorkItemResult::Finished(CompiledModule {
962 links_from_incr_cache,
963 kind: ModuleKind::Regular,
964 name: module.name,
965 object,
966 dwarf_object,
967 bytecode,
968 assembly,
969 llvm_ir,
970 })
971}
972
973fn execute_fat_lto_work_item<B: ExtraBackendMethods>(
974 cgcx: &CodegenContext<B>,
975 exported_symbols_for_lto: &[String],
976 each_linked_rlib_for_lto: &[PathBuf],
977 mut needs_fat_lto: Vec<FatLtoInput<B>>,
978 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
979) -> WorkItemResult<B> {
980 for (module, wp) in import_only_modules {
981 needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, buffer: module })
982 }
983
984 let module = B::run_and_optimize_fat_lto(
985 cgcx,
986 exported_symbols_for_lto,
987 each_linked_rlib_for_lto,
988 needs_fat_lto,
989 );
990 let module = B::codegen(cgcx, module, &cgcx.module_config);
991 WorkItemResult::Finished(module)
992}
993
994fn execute_thin_lto_work_item<B: ExtraBackendMethods>(
995 cgcx: &CodegenContext<B>,
996 module: lto::ThinModule<B>,
997) -> WorkItemResult<B> {
998 let module = B::optimize_thin(cgcx, module);
999 let module = B::codegen(cgcx, module, &cgcx.module_config);
1000 WorkItemResult::Finished(module)
1001}
1002
1003pub(crate) enum Message<B: WriteBackendMethods> {
1005 Token(io::Result<Acquired>),
1008
1009 WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
1012
1013 CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
1017
1018 AddImportOnlyModule {
1021 module_data: SerializedModule<B::ModuleBuffer>,
1022 work_product: WorkProduct,
1023 },
1024
1025 CodegenComplete,
1028
1029 CodegenAborted,
1032}
1033
1034pub struct CguMessage;
1037
1038struct Diagnostic {
1048 level: Level,
1049 messages: Vec<(DiagMessage, Style)>,
1050 code: Option<ErrCode>,
1051 children: Vec<Subdiagnostic>,
1052 args: DiagArgMap,
1053}
1054
1055pub(crate) struct Subdiagnostic {
1059 level: Level,
1060 messages: Vec<(DiagMessage, Style)>,
1061}
1062
1063#[derive(PartialEq, Clone, Copy, Debug)]
1064enum MainThreadState {
1065 Idle,
1067
1068 Codegenning,
1070
1071 Lending,
1073}
1074
1075fn start_executing_work<B: ExtraBackendMethods>(
1076 backend: B,
1077 tcx: TyCtxt<'_>,
1078 crate_info: &CrateInfo,
1079 shared_emitter: SharedEmitter,
1080 codegen_worker_send: Sender<CguMessage>,
1081 coordinator_receive: Receiver<Message<B>>,
1082 regular_config: Arc<ModuleConfig>,
1083 allocator_config: Arc<ModuleConfig>,
1084 allocator_module: Option<ModuleCodegen<B::Module>>,
1085 tx_to_llvm_workers: Sender<Message<B>>,
1086) -> thread::JoinHandle<Result<CompiledModules, ()>> {
1087 let coordinator_send = tx_to_llvm_workers;
1088 let sess = tcx.sess;
1089
1090 let mut each_linked_rlib_for_lto = Vec::new();
1091 let mut each_linked_rlib_file_for_lto = Vec::new();
1092 drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| {
1093 if link::ignored_for_lto(sess, crate_info, cnum) {
1094 return;
1095 }
1096 each_linked_rlib_for_lto.push(cnum);
1097 each_linked_rlib_file_for_lto.push(path.to_path_buf());
1098 }));
1099
1100 let exported_symbols_for_lto =
1102 Arc::new(lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto));
1103
1104 let coordinator_send2 = coordinator_send.clone();
1110 let helper = jobserver::client()
1111 .into_helper_thread(move |token| {
1112 drop(coordinator_send2.send(Message::Token::<B>(token)));
1113 })
1114 .expect("failed to spawn helper thread");
1115
1116 let ol =
1117 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
1118 config::OptLevel::No
1120 } else {
1121 tcx.backend_optimization_level(())
1122 };
1123 let backend_features = tcx.global_backend_features(());
1124
1125 let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1126 let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1127 match result {
1128 Ok(dir) => Some(dir),
1129 Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1130 }
1131 } else {
1132 None
1133 };
1134
1135 let cgcx = CodegenContext::<B> {
1136 crate_types: tcx.crate_types().to_vec(),
1137 lto: sess.lto(),
1138 fewer_names: sess.fewer_names(),
1139 save_temps: sess.opts.cg.save_temps,
1140 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1141 opts: Arc::new(sess.opts.clone()),
1142 prof: sess.prof.clone(),
1143 remark: sess.opts.cg.remark.clone(),
1144 remark_dir,
1145 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1146 expanded_args: tcx.sess.expanded_args.clone(),
1147 diag_emitter: shared_emitter.clone(),
1148 output_filenames: Arc::clone(tcx.output_filenames(())),
1149 module_config: regular_config,
1150 allocator_config,
1151 tm_factory: backend.target_machine_factory(tcx.sess, ol, backend_features),
1152 msvc_imps_needed: msvc_imps_needed(tcx),
1153 is_pe_coff: tcx.sess.target.is_like_windows,
1154 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1155 target_arch: tcx.sess.target.arch.to_string(),
1156 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1157 target_is_like_aix: tcx.sess.target.is_like_aix,
1158 split_debuginfo: tcx.sess.split_debuginfo(),
1159 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1160 parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1161 pointer_size: tcx.data_layout.pointer_size(),
1162 invocation_temp: sess.invocation_temp.clone(),
1163 };
1164
1165 return B::spawn_named_thread(cgcx.time_trace, "coordinator".to_string(), move || {
1301 let mut compiled_modules = vec![];
1304 let mut needs_fat_lto = Vec::new();
1305 let mut needs_thin_lto = Vec::new();
1306 let mut lto_import_only_modules = Vec::new();
1307 let mut started_lto = false;
1308
1309 #[derive(Debug, PartialEq)]
1314 enum CodegenState {
1315 Ongoing,
1316 Completed,
1317 Aborted,
1318 }
1319 use CodegenState::*;
1320 let mut codegen_state = Ongoing;
1321
1322 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1324
1325 let mut tokens = Vec::new();
1328
1329 let mut main_thread_state = MainThreadState::Idle;
1330
1331 let mut running_with_own_token = 0;
1334
1335 let running_with_any_token = |main_thread_state, running_with_own_token| {
1338 running_with_own_token
1339 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1340 };
1341
1342 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1343
1344 let compiled_allocator_module = allocator_module.and_then(|allocator_module| {
1345 match execute_optimize_work_item(&cgcx, allocator_module) {
1346 WorkItemResult::Finished(compiled_module) => return Some(compiled_module),
1347 WorkItemResult::NeedsFatLto(fat_lto_input) => needs_fat_lto.push(fat_lto_input),
1348 WorkItemResult::NeedsThinLto(name, thin_buffer) => {
1349 needs_thin_lto.push((name, thin_buffer))
1350 }
1351 }
1352 None
1353 });
1354
1355 loop {
1361 if codegen_state == Ongoing {
1365 if main_thread_state == MainThreadState::Idle {
1366 let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1374 let additional_running = std::cmp::min(extra_tokens, work_items.len());
1375 let anticipated_running = running_with_own_token + additional_running + 1;
1376
1377 if !queue_full_enough(work_items.len(), anticipated_running) {
1378 if codegen_worker_send.send(CguMessage).is_err() {
1380 panic!("Could not send CguMessage to main thread")
1381 }
1382 main_thread_state = MainThreadState::Codegenning;
1383 } else {
1384 let (item, _) =
1388 work_items.pop().expect("queue empty - queue_full_enough() broken?");
1389 main_thread_state = MainThreadState::Lending;
1390 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1391 }
1392 }
1393 } else if codegen_state == Completed {
1394 if running_with_any_token(main_thread_state, running_with_own_token) == 0
1395 && work_items.is_empty()
1396 {
1397 if needs_fat_lto.is_empty()
1399 && needs_thin_lto.is_empty()
1400 && lto_import_only_modules.is_empty()
1401 {
1402 break;
1404 }
1405
1406 assert!(!started_lto);
1412 started_lto = true;
1413
1414 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1415 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1416 let import_only_modules = mem::take(&mut lto_import_only_modules);
1417 let each_linked_rlib_file_for_lto =
1418 mem::take(&mut each_linked_rlib_file_for_lto);
1419
1420 check_lto_allowed(&cgcx);
1421
1422 if !needs_fat_lto.is_empty() {
1423 assert!(needs_thin_lto.is_empty());
1424
1425 work_items.push((
1426 WorkItem::FatLto {
1427 exported_symbols_for_lto: Arc::clone(&exported_symbols_for_lto),
1428 each_linked_rlib_for_lto: each_linked_rlib_file_for_lto,
1429 needs_fat_lto,
1430 import_only_modules,
1431 },
1432 0,
1433 ));
1434 if cgcx.parallel {
1435 helper.request_token();
1436 }
1437 } else {
1438 for (work, cost) in generate_thin_lto_work(
1439 &cgcx,
1440 &exported_symbols_for_lto,
1441 &each_linked_rlib_file_for_lto,
1442 needs_thin_lto,
1443 import_only_modules,
1444 ) {
1445 let insertion_index = work_items
1446 .binary_search_by_key(&cost, |&(_, cost)| cost)
1447 .unwrap_or_else(|e| e);
1448 work_items.insert(insertion_index, (work, cost));
1449 if cgcx.parallel {
1450 helper.request_token();
1451 }
1452 }
1453 }
1454 }
1455
1456 match main_thread_state {
1460 MainThreadState::Idle => {
1461 if let Some((item, _)) = work_items.pop() {
1462 main_thread_state = MainThreadState::Lending;
1463 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1464 } else {
1465 assert!(running_with_own_token > 0);
1472 running_with_own_token -= 1;
1473 main_thread_state = MainThreadState::Lending;
1474 }
1475 }
1476 MainThreadState::Codegenning => bug!(
1477 "codegen worker should not be codegenning after \
1478 codegen was already completed"
1479 ),
1480 MainThreadState::Lending => {
1481 }
1483 }
1484 } else {
1485 assert!(codegen_state == Aborted);
1488 if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1489 break;
1490 }
1491 }
1492
1493 if codegen_state != Aborted {
1496 while running_with_own_token < tokens.len()
1497 && let Some((item, _)) = work_items.pop()
1498 {
1499 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1500 running_with_own_token += 1;
1501 }
1502 }
1503
1504 tokens.truncate(running_with_own_token);
1506
1507 match coordinator_receive.recv().unwrap() {
1508 Message::Token(token) => {
1512 match token {
1513 Ok(token) => {
1514 tokens.push(token);
1515
1516 if main_thread_state == MainThreadState::Lending {
1517 main_thread_state = MainThreadState::Idle;
1522 running_with_own_token += 1;
1523 }
1524 }
1525 Err(e) => {
1526 let msg = &format!("failed to acquire jobserver token: {e}");
1527 shared_emitter.fatal(msg);
1528 codegen_state = Aborted;
1529 }
1530 }
1531 }
1532
1533 Message::CodegenDone { llvm_work_item, cost } => {
1534 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1543 let insertion_index = match insertion_index {
1544 Ok(idx) | Err(idx) => idx,
1545 };
1546 work_items.insert(insertion_index, (llvm_work_item, cost));
1547
1548 if cgcx.parallel {
1549 helper.request_token();
1550 }
1551 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1552 main_thread_state = MainThreadState::Idle;
1553 }
1554
1555 Message::CodegenComplete => {
1556 if codegen_state != Aborted {
1557 codegen_state = Completed;
1558 }
1559 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1560 main_thread_state = MainThreadState::Idle;
1561 }
1562
1563 Message::CodegenAborted => {
1571 codegen_state = Aborted;
1572 }
1573
1574 Message::WorkItem { result } => {
1575 if main_thread_state == MainThreadState::Lending {
1581 main_thread_state = MainThreadState::Idle;
1582 } else {
1583 running_with_own_token -= 1;
1584 }
1585
1586 match result {
1587 Ok(WorkItemResult::Finished(compiled_module)) => {
1588 compiled_modules.push(compiled_module);
1589 }
1590 Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1591 assert!(!started_lto);
1592 assert!(needs_thin_lto.is_empty());
1593 needs_fat_lto.push(fat_lto_input);
1594 }
1595 Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1596 assert!(!started_lto);
1597 assert!(needs_fat_lto.is_empty());
1598 needs_thin_lto.push((name, thin_buffer));
1599 }
1600 Err(Some(WorkerFatalError)) => {
1601 codegen_state = Aborted;
1603 }
1604 Err(None) => {
1605 bug!("worker thread panicked");
1608 }
1609 }
1610 }
1611
1612 Message::AddImportOnlyModule { module_data, work_product } => {
1613 assert!(!started_lto);
1614 assert_eq!(codegen_state, Ongoing);
1615 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1616 lto_import_only_modules.push((module_data, work_product));
1617 main_thread_state = MainThreadState::Idle;
1618 }
1619 }
1620 }
1621
1622 if codegen_state == Aborted {
1623 return Err(());
1624 }
1625
1626 drop(llvm_start_time);
1628
1629 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1633
1634 Ok(CompiledModules {
1635 modules: compiled_modules,
1636 allocator_module: compiled_allocator_module,
1637 })
1638 })
1639 .expect("failed to spawn coordinator thread");
1640
1641 fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1644 let quarter_of_workers = workers_running - 3 * workers_running / 4;
1695 items_in_queue > 0 && items_in_queue >= quarter_of_workers
1696 }
1697}
1698
1699#[must_use]
1701pub(crate) struct WorkerFatalError;
1702
1703fn spawn_work<'a, B: ExtraBackendMethods>(
1704 cgcx: &'a CodegenContext<B>,
1705 coordinator_send: Sender<Message<B>>,
1706 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1707 work: WorkItem<B>,
1708) {
1709 if llvm_start_time.is_none() {
1710 *llvm_start_time = Some(cgcx.prof.verbose_generic_activity("LLVM_passes"));
1711 }
1712
1713 let cgcx = cgcx.clone();
1714
1715 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1716 let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1717 WorkItem::Optimize(m) => {
1718 let _timer =
1719 cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &*m.name);
1720 execute_optimize_work_item(&cgcx, m)
1721 }
1722 WorkItem::CopyPostLtoArtifacts(m) => {
1723 let _timer = cgcx
1724 .prof
1725 .generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &*m.name);
1726 execute_copy_from_cache_work_item(&cgcx, m)
1727 }
1728 WorkItem::FatLto {
1729 exported_symbols_for_lto,
1730 each_linked_rlib_for_lto,
1731 needs_fat_lto,
1732 import_only_modules,
1733 } => {
1734 let _timer =
1735 cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", "everything");
1736 execute_fat_lto_work_item(
1737 &cgcx,
1738 &exported_symbols_for_lto,
1739 &each_linked_rlib_for_lto,
1740 needs_fat_lto,
1741 import_only_modules,
1742 )
1743 }
1744 WorkItem::ThinLto(m) => {
1745 let _timer =
1746 cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name());
1747 execute_thin_lto_work_item(&cgcx, m)
1748 }
1749 }));
1750
1751 let msg = match result {
1752 Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
1753
1754 Err(err) if err.is::<FatalErrorMarker>() => {
1758 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1759 }
1760
1761 Err(_) => Message::WorkItem::<B> { result: Err(None) },
1762 };
1763 drop(coordinator_send.send(msg));
1764 })
1765 .expect("failed to spawn work thread");
1766}
1767
1768enum SharedEmitterMessage {
1769 Diagnostic(Diagnostic),
1770 InlineAsmError(SpanData, String, Level, Option<(String, Vec<InnerSpan>)>),
1771 Fatal(String),
1772}
1773
1774#[derive(Clone)]
1775pub struct SharedEmitter {
1776 sender: Sender<SharedEmitterMessage>,
1777}
1778
1779pub struct SharedEmitterMain {
1780 receiver: Receiver<SharedEmitterMessage>,
1781}
1782
1783impl SharedEmitter {
1784 fn new() -> (SharedEmitter, SharedEmitterMain) {
1785 let (sender, receiver) = channel();
1786
1787 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1788 }
1789
1790 pub fn inline_asm_error(
1791 &self,
1792 span: SpanData,
1793 msg: String,
1794 level: Level,
1795 source: Option<(String, Vec<InnerSpan>)>,
1796 ) {
1797 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(span, msg, level, source)));
1798 }
1799
1800 fn fatal(&self, msg: &str) {
1801 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1802 }
1803}
1804
1805impl Emitter for SharedEmitter {
1806 fn emit_diagnostic(
1807 &mut self,
1808 mut diag: rustc_errors::DiagInner,
1809 _registry: &rustc_errors::registry::Registry,
1810 ) {
1811 assert_eq!(diag.span, MultiSpan::new());
1814 assert_eq!(diag.suggestions, Suggestions::Enabled(vec![]));
1815 assert_eq!(diag.sort_span, rustc_span::DUMMY_SP);
1816 assert_eq!(diag.is_lint, None);
1817 let args = mem::replace(&mut diag.args, DiagArgMap::default());
1820 drop(
1821 self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1822 level: diag.level(),
1823 messages: diag.messages,
1824 code: diag.code,
1825 children: diag
1826 .children
1827 .into_iter()
1828 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
1829 .collect(),
1830 args,
1831 })),
1832 );
1833 }
1834
1835 fn source_map(&self) -> Option<&SourceMap> {
1836 None
1837 }
1838
1839 fn translator(&self) -> &Translator {
1840 panic!("shared emitter attempted to translate a diagnostic");
1841 }
1842}
1843
1844impl SharedEmitterMain {
1845 fn check(&self, sess: &Session, blocking: bool) {
1846 loop {
1847 let message = if blocking {
1848 match self.receiver.recv() {
1849 Ok(message) => Ok(message),
1850 Err(_) => Err(()),
1851 }
1852 } else {
1853 match self.receiver.try_recv() {
1854 Ok(message) => Ok(message),
1855 Err(_) => Err(()),
1856 }
1857 };
1858
1859 match message {
1860 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1861 let dcx = sess.dcx();
1864 let mut d =
1865 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
1866 d.code = diag.code; d.children = diag
1868 .children
1869 .into_iter()
1870 .map(|sub| rustc_errors::Subdiag {
1871 level: sub.level,
1872 messages: sub.messages,
1873 span: MultiSpan::new(),
1874 })
1875 .collect();
1876 d.args = diag.args;
1877 dcx.emit_diagnostic(d);
1878 sess.dcx().abort_if_errors();
1879 }
1880 Ok(SharedEmitterMessage::InlineAsmError(span, msg, level, source)) => {
1881 assert_matches!(level, Level::Error | Level::Warning | Level::Note);
1882 let mut err = Diag::<()>::new(sess.dcx(), level, msg);
1883 if !span.is_dummy() {
1884 err.span(span.span());
1885 }
1886
1887 if let Some((buffer, spans)) = source {
1889 let source = sess
1890 .source_map()
1891 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
1892 let spans: Vec<_> = spans
1893 .iter()
1894 .map(|sp| {
1895 Span::with_root_ctxt(
1896 source.normalized_byte_pos(sp.start as u32),
1897 source.normalized_byte_pos(sp.end as u32),
1898 )
1899 })
1900 .collect();
1901 err.span_note(spans, "instantiated into assembly here");
1902 }
1903
1904 err.emit();
1905 }
1906 Ok(SharedEmitterMessage::Fatal(msg)) => {
1907 sess.dcx().fatal(msg);
1908 }
1909 Err(_) => {
1910 break;
1911 }
1912 }
1913 }
1914 }
1915}
1916
1917pub struct Coordinator<B: ExtraBackendMethods> {
1918 sender: Sender<Message<B>>,
1919 future: Option<thread::JoinHandle<Result<CompiledModules, ()>>>,
1920 phantom: PhantomData<B>,
1922}
1923
1924impl<B: ExtraBackendMethods> Coordinator<B> {
1925 fn join(mut self) -> std::thread::Result<Result<CompiledModules, ()>> {
1926 self.future.take().unwrap().join()
1927 }
1928}
1929
1930impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
1931 fn drop(&mut self) {
1932 if let Some(future) = self.future.take() {
1933 drop(self.sender.send(Message::CodegenAborted::<B>));
1936 drop(future.join());
1937 }
1938 }
1939}
1940
1941pub struct OngoingCodegen<B: ExtraBackendMethods> {
1942 pub backend: B,
1943 pub crate_info: CrateInfo,
1944 pub output_filenames: Arc<OutputFilenames>,
1945 pub coordinator: Coordinator<B>,
1949 pub codegen_worker_receive: Receiver<CguMessage>,
1950 pub shared_emitter_main: SharedEmitterMain,
1951}
1952
1953impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1954 pub fn join(self, sess: &Session) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
1955 self.shared_emitter_main.check(sess, true);
1956 let compiled_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
1957 Ok(Ok(compiled_modules)) => compiled_modules,
1958 Ok(Err(())) => {
1959 sess.dcx().abort_if_errors();
1960 panic!("expected abort due to worker thread errors")
1961 }
1962 Err(_) => {
1963 bug!("panic during codegen/LLVM phase");
1964 }
1965 });
1966
1967 sess.dcx().abort_if_errors();
1968
1969 let work_products =
1970 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
1971 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
1972
1973 if sess.codegen_units().as_usize() == 1 && sess.opts.unstable_opts.time_llvm_passes {
1976 self.backend.print_pass_timings()
1977 }
1978
1979 if sess.print_llvm_stats() {
1980 self.backend.print_statistics()
1981 }
1982
1983 (
1984 CodegenResults {
1985 crate_info: self.crate_info,
1986
1987 modules: compiled_modules.modules,
1988 allocator_module: compiled_modules.allocator_module,
1989 },
1990 work_products,
1991 )
1992 }
1993
1994 pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
1995 self.wait_for_signal_to_codegen_item();
1996 self.check_for_errors(tcx.sess);
1997 drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
1998 }
1999
2000 pub(crate) fn check_for_errors(&self, sess: &Session) {
2001 self.shared_emitter_main.check(sess, false);
2002 }
2003
2004 pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2005 match self.codegen_worker_receive.recv() {
2006 Ok(CguMessage) => {
2007 }
2009 Err(_) => {
2010 }
2013 }
2014 }
2015}
2016
2017pub(crate) fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
2018 coordinator: &Coordinator<B>,
2019 module: ModuleCodegen<B::Module>,
2020 cost: u64,
2021) {
2022 let llvm_work_item = WorkItem::Optimize(module);
2023 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2024}
2025
2026pub(crate) fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
2027 coordinator: &Coordinator<B>,
2028 module: CachedModuleCodegen,
2029) {
2030 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2031 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2032}
2033
2034pub(crate) fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
2035 tcx: TyCtxt<'_>,
2036 coordinator: &Coordinator<B>,
2037 module: CachedModuleCodegen,
2038) {
2039 let filename = pre_lto_bitcode_filename(&module.name);
2040 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2041 let file = fs::File::open(&bc_path)
2042 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
2043
2044 let mmap = unsafe {
2045 Mmap::map(file).unwrap_or_else(|e| {
2046 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2047 })
2048 };
2049 drop(coordinator.sender.send(Message::AddImportOnlyModule::<B> {
2051 module_data: SerializedModule::FromUncompressedFile(mmap),
2052 work_product: module.source,
2053 }));
2054}
2055
2056fn pre_lto_bitcode_filename(module_name: &str) -> String {
2057 format!("{module_name}.{PRE_LTO_BC_EXT}")
2058}
2059
2060fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2061 assert!(
2064 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2065 && tcx.sess.target.is_like_windows
2066 && tcx.sess.opts.cg.prefer_dynamic)
2067 );
2068
2069 let can_have_static_objects =
2073 tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
2074
2075 tcx.sess.target.is_like_windows &&
2076 can_have_static_objects &&
2077 !tcx.sess.opts.cg.linker_plugin_lto.enabled()
2081}