1 use super::link::{self, remove};
2 use super::linker::LinkerInfo;
3 use super::lto::{self, SerializedModule};
4 use super::symbol_export::symbol_name_for_instance_in_crate;
7 CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
11 use jobserver::{Acquired, Client};
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_data_structures::profiling::SelfProfilerRef;
14 use rustc_data_structures::profiling::TimingGuard;
15 use rustc_data_structures::profiling::VerboseTimingGuard;
16 use rustc_data_structures::sync::Lrc;
17 use rustc_errors::emitter::Emitter;
18 use rustc_errors::{DiagnosticId, FatalError, Handler, Level};
19 use rustc_fs_util::link_or_copy;
20 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
21 use rustc_incremental::{
22 copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
24 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
25 use rustc_middle::middle::cstore::EncodedMetadata;
26 use rustc_middle::middle::exported_symbols::SymbolExportLevel;
27 use rustc_middle::ty::TyCtxt;
28 use rustc_session::cgu_reuse_tracker::CguReuseTracker;
29 use rustc_session::config::{self, CrateType, Lto, OutputFilenames, OutputType};
30 use rustc_session::config::{Passes, SanitizerSet, SwitchWithOptPath};
31 use rustc_session::Session;
32 use rustc_span::source_map::SourceMap;
33 use rustc_span::symbol::{sym, Symbol};
34 use rustc_span::{BytePos, FileName, InnerSpan, Pos, Span};
35 use rustc_target::spec::{MergeFunctions, PanicStrategy};
41 use std::path::{Path, PathBuf};
43 use std::sync::mpsc::{channel, Receiver, Sender};
47 const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
49 /// What kind of object file to emit.
50 #[derive(Clone, Copy, PartialEq)]
55 // Just uncompressed llvm bitcode. Provides easy compatibility with
56 // emscripten's ecc compiler, when used as the linker.
59 // Object code, possibly augmented with a bitcode section.
60 ObjectCode(BitcodeSection),
63 /// What kind of llvm bitcode section to embed in an object file.
64 #[derive(Clone, Copy, PartialEq)]
65 pub enum BitcodeSection {
66 // No bitcode section.
69 // A full, uncompressed bitcode section.
73 /// Module-specific configuration for `optimize_and_codegen`.
74 pub struct ModuleConfig {
75 /// Names of additional optimization passes to run.
76 pub passes: Vec<String>,
77 /// Some(level) to optimize at a certain level, or None to run
78 /// absolutely no optimizations (used for the metadata module).
79 pub opt_level: Option<config::OptLevel>,
81 /// Some(level) to optimize binary size, or None to not affect program size.
82 pub opt_size: Option<config::OptLevel>,
84 pub pgo_gen: SwitchWithOptPath,
85 pub pgo_use: Option<PathBuf>,
87 pub sanitizer: SanitizerSet,
88 pub sanitizer_recover: SanitizerSet,
89 pub sanitizer_memory_track_origins: usize,
91 // Flags indicating which outputs to produce.
92 pub emit_pre_lto_bc: bool,
93 pub emit_no_opt_bc: bool,
97 pub emit_obj: EmitObj,
98 pub bc_cmdline: String,
100 // Miscellaneous flags. These are mostly copied from command-line
102 pub verify_llvm_ir: bool,
103 pub no_prepopulate_passes: bool,
104 pub no_builtins: bool,
105 pub time_module: bool,
106 pub vectorize_loop: bool,
107 pub vectorize_slp: bool,
108 pub merge_functions: bool,
109 pub inline_threshold: Option<usize>,
110 pub new_llvm_pass_manager: bool,
111 pub emit_lifetime_markers: bool,
119 is_compiler_builtins: bool,
121 // If it's a regular module, use `$regular`, otherwise use `$other`.
122 // `$regular` and `$other` are evaluated lazily.
123 macro_rules! if_regular {
124 ($regular: expr, $other: expr) => {
125 if let ModuleKind::Regular = kind { $regular } else { $other }
129 let opt_level_and_size = if_regular!(Some(sess.opts.optimize), None);
131 let save_temps = sess.opts.cg.save_temps;
133 let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
135 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
136 ModuleKind::Allocator => false,
137 ModuleKind::Metadata => sess.opts.output_types.contains_key(&OutputType::Metadata),
140 let emit_obj = if !should_emit_obj {
142 } else if sess.target.target.options.obj_is_bitcode
143 || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
145 // This case is selected if the target uses objects as bitcode, or
146 // if linker plugin LTO is enabled. In the linker plugin LTO case
147 // the assumption is that the final link-step will read the bitcode
148 // and convert it to object code. This may be done by either the
149 // native linker or rustc itself.
151 // Note, however, that the linker-plugin-lto requested here is
152 // explicitly ignored for `#![no_builtins]` crates. These crates are
153 // specifically ignored by rustc's LTO passes and wouldn't work if
154 // loaded into the linker. These crates define symbols that LLVM
155 // lowers intrinsics to, and these symbol dependencies aren't known
156 // until after codegen. As a result any crate marked
157 // `#![no_builtins]` is assumed to not participate in LTO and
158 // instead goes on to generate object code.
160 } else if need_bitcode_in_object(sess) {
161 EmitObj::ObjectCode(BitcodeSection::Full)
163 EmitObj::ObjectCode(BitcodeSection::None)
169 let mut passes = sess.opts.cg.passes.clone();
170 // compiler_builtins overrides the codegen-units settings,
171 // which is incompatible with -Zprofile which requires that
172 // only a single codegen unit is used per crate.
173 if sess.opts.debugging_opts.profile && !is_compiler_builtins {
174 passes.push("insert-gcov-profiling".to_owned());
177 // The rustc option `-Zinstrument_coverage` injects intrinsic calls to
178 // `llvm.instrprof.increment()`, which requires the LLVM `instrprof` pass.
179 if sess.opts.debugging_opts.instrument_coverage {
180 passes.push("instrprof".to_owned());
187 opt_level: opt_level_and_size,
188 opt_size: opt_level_and_size,
190 pgo_gen: if_regular!(
191 sess.opts.cg.profile_generate.clone(),
192 SwitchWithOptPath::Disabled
194 pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
196 sanitizer: if_regular!(sess.opts.debugging_opts.sanitizer, SanitizerSet::empty()),
197 sanitizer_recover: if_regular!(
198 sess.opts.debugging_opts.sanitizer_recover,
199 SanitizerSet::empty()
201 sanitizer_memory_track_origins: if_regular!(
202 sess.opts.debugging_opts.sanitizer_memory_track_origins,
206 emit_pre_lto_bc: if_regular!(
207 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
210 emit_no_opt_bc: if_regular!(save_temps, false),
211 emit_bc: if_regular!(
212 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
215 emit_ir: if_regular!(
216 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
219 emit_asm: if_regular!(
220 sess.opts.output_types.contains_key(&OutputType::Assembly),
224 bc_cmdline: sess.target.target.options.bitcode_llvm_cmdline.clone(),
226 verify_llvm_ir: sess.verify_llvm_ir(),
227 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
228 no_builtins: no_builtins || sess.target.target.options.no_builtins,
230 // Exclude metadata and allocator modules from time_passes output,
231 // since they throw off the "LLVM passes" measurement.
232 time_module: if_regular!(true, false),
234 // Copy what clang does by turning on loop vectorization at O2 and
235 // slp vectorization at O3.
236 vectorize_loop: !sess.opts.cg.no_vectorize_loops
237 && (sess.opts.optimize == config::OptLevel::Default
238 || sess.opts.optimize == config::OptLevel::Aggressive),
239 vectorize_slp: !sess.opts.cg.no_vectorize_slp
240 && sess.opts.optimize == config::OptLevel::Aggressive,
242 // Some targets (namely, NVPTX) interact badly with the
243 // MergeFunctions pass. This is because MergeFunctions can generate
244 // new function calls which may interfere with the target calling
245 // convention; e.g. for the NVPTX target, PTX kernels should not
246 // call other PTX kernels. MergeFunctions can also be configured to
247 // generate aliases instead, but aliases are not supported by some
248 // backends (again, NVPTX). Therefore, allow targets to opt out of
249 // the MergeFunctions pass, but otherwise keep the pass enabled (at
250 // O2 and O3) since it can be useful for reducing code size.
251 merge_functions: match sess
255 .unwrap_or(sess.target.target.options.merge_functions)
257 MergeFunctions::Disabled => false,
258 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
259 sess.opts.optimize == config::OptLevel::Default
260 || sess.opts.optimize == config::OptLevel::Aggressive
264 inline_threshold: sess.opts.cg.inline_threshold,
265 new_llvm_pass_manager: sess.opts.debugging_opts.new_llvm_pass_manager,
266 emit_lifetime_markers: sess.emit_lifetime_markers(),
270 pub fn bitcode_needed(&self) -> bool {
272 || self.emit_obj == EmitObj::Bitcode
273 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
277 // HACK(eddyb) work around `#[derive]` producing wrong bounds for `Clone`.
278 pub struct TargetMachineFactory<B: WriteBackendMethods>(
279 pub Arc<dyn Fn() -> Result<B::TargetMachine, String> + Send + Sync>,
282 impl<B: WriteBackendMethods> Clone for TargetMachineFactory<B> {
283 fn clone(&self) -> Self {
284 TargetMachineFactory(self.0.clone())
288 pub type ExportedSymbols = FxHashMap<CrateNum, Arc<Vec<(String, SymbolExportLevel)>>>;
290 /// Additional resources used by optimize_and_codegen (not module specific)
292 pub struct CodegenContext<B: WriteBackendMethods> {
293 // Resources needed when running LTO
295 pub prof: SelfProfilerRef,
297 pub no_landing_pads: bool,
298 pub save_temps: bool,
299 pub fewer_names: bool,
300 pub exported_symbols: Option<Arc<ExportedSymbols>>,
301 pub opts: Arc<config::Options>,
302 pub crate_types: Vec<CrateType>,
303 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
304 pub output_filenames: Arc<OutputFilenames>,
305 pub regular_module_config: Arc<ModuleConfig>,
306 pub metadata_module_config: Arc<ModuleConfig>,
307 pub allocator_module_config: Arc<ModuleConfig>,
308 pub tm_factory: TargetMachineFactory<B>,
309 pub msvc_imps_needed: bool,
310 pub target_pointer_width: String,
311 pub target_arch: String,
312 pub debuginfo: config::DebugInfo,
314 // Number of cgus excluding the allocator/metadata modules
315 pub total_cgus: usize,
316 // Handler to use for diagnostics produced during codegen.
317 pub diag_emitter: SharedEmitter,
318 // LLVM optimizations for which we want to print remarks.
320 // Worker thread number
322 // The incremental compilation session directory, or None if we are not
323 // compiling incrementally
324 pub incr_comp_session_dir: Option<PathBuf>,
325 // Used to update CGU re-use information during the thinlto phase.
326 pub cgu_reuse_tracker: CguReuseTracker,
327 // Channel back to the main control thread to send messages to
328 pub coordinator_send: Sender<Box<dyn Any + Send>>,
331 impl<B: WriteBackendMethods> CodegenContext<B> {
332 pub fn create_diag_handler(&self) -> Handler {
333 Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
336 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
338 ModuleKind::Regular => &self.regular_module_config,
339 ModuleKind::Metadata => &self.metadata_module_config,
340 ModuleKind::Allocator => &self.allocator_module_config,
345 fn generate_lto_work<B: ExtraBackendMethods>(
346 cgcx: &CodegenContext<B>,
347 needs_fat_lto: Vec<FatLTOInput<B>>,
348 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
349 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
350 ) -> Vec<(WorkItem<B>, u64)> {
351 let _prof_timer = cgcx.prof.generic_activity("codegen_generate_lto_work");
353 let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
354 assert!(needs_thin_lto.is_empty());
356 B::run_fat_lto(cgcx, needs_fat_lto, import_only_modules).unwrap_or_else(|e| e.raise());
357 (vec![lto_module], vec![])
359 assert!(needs_fat_lto.is_empty());
360 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules).unwrap_or_else(|e| e.raise())
366 let cost = module.cost();
367 (WorkItem::LTO(module), cost)
369 .chain(copy_jobs.into_iter().map(|wp| {
371 WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
372 name: wp.cgu_name.clone(),
381 pub struct CompiledModules {
382 pub modules: Vec<CompiledModule>,
383 pub metadata_module: Option<CompiledModule>,
384 pub allocator_module: Option<CompiledModule>,
387 fn need_bitcode_in_object(sess: &Session) -> bool {
388 let requested_for_rlib = sess.opts.cg.embed_bitcode
389 && sess.crate_types().contains(&CrateType::Rlib)
390 && sess.opts.output_types.contains_key(&OutputType::Exe);
391 let forced_by_target = sess.target.target.options.forces_embed_bitcode;
392 requested_for_rlib || forced_by_target
395 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
396 if sess.opts.incremental.is_none() {
402 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
406 pub fn start_async_codegen<B: ExtraBackendMethods>(
409 metadata: EncodedMetadata,
411 ) -> OngoingCodegen<B> {
412 let (coordinator_send, coordinator_receive) = channel();
415 let crate_name = tcx.crate_name(LOCAL_CRATE);
416 let no_builtins = tcx.sess.contains_name(&tcx.hir().krate().item.attrs, sym::no_builtins);
417 let is_compiler_builtins =
418 tcx.sess.contains_name(&tcx.hir().krate().item.attrs, sym::compiler_builtins);
421 .first_attr_value_str_by_name(&tcx.hir().krate().item.attrs, sym::windows_subsystem);
422 let windows_subsystem = subsystem.map(|subsystem| {
423 if subsystem != sym::windows && subsystem != sym::console {
424 tcx.sess.fatal(&format!(
425 "invalid windows subsystem `{}`, only \
426 `windows` and `console` are allowed",
430 subsystem.to_string()
433 let linker_info = LinkerInfo::new(tcx);
434 let crate_info = CrateInfo::new(tcx);
437 ModuleConfig::new(ModuleKind::Regular, sess, no_builtins, is_compiler_builtins);
438 let metadata_config =
439 ModuleConfig::new(ModuleKind::Metadata, sess, no_builtins, is_compiler_builtins);
440 let allocator_config =
441 ModuleConfig::new(ModuleKind::Allocator, sess, no_builtins, is_compiler_builtins);
443 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
444 let (codegen_worker_send, codegen_worker_receive) = channel();
446 let coordinator_thread = start_executing_work(
454 sess.jobserver.clone(),
455 Arc::new(regular_config),
456 Arc::new(metadata_config),
457 Arc::new(allocator_config),
458 coordinator_send.clone(),
470 codegen_worker_receive,
472 future: coordinator_thread,
473 output_filenames: tcx.output_filenames(LOCAL_CRATE),
477 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
479 compiled_modules: &CompiledModules,
480 ) -> FxHashMap<WorkProductId, WorkProduct> {
481 let mut work_products = FxHashMap::default();
483 if sess.opts.incremental.is_none() {
484 return work_products;
487 let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
489 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
490 let path = module.object.as_ref().cloned();
492 if let Some((id, product)) =
493 copy_cgu_workproduct_to_incr_comp_cache_dir(sess, &module.name, &path)
495 work_products.insert(id, product);
502 fn produce_final_output_artifacts(
504 compiled_modules: &CompiledModules,
505 crate_output: &OutputFilenames,
507 let mut user_wants_bitcode = false;
508 let mut user_wants_objects = false;
510 // Produce final compile outputs.
511 let copy_gracefully = |from: &Path, to: &Path| {
512 if let Err(e) = fs::copy(from, to) {
513 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
517 let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
518 if compiled_modules.modules.len() == 1 {
519 // 1) Only one codegen unit. In this case it's no difficulty
520 // to copy `foo.0.x` to `foo.x`.
521 let module_name = Some(&compiled_modules.modules[0].name[..]);
522 let path = crate_output.temp_path(output_type, module_name);
523 copy_gracefully(&path, &crate_output.path(output_type));
524 if !sess.opts.cg.save_temps && !keep_numbered {
525 // The user just wants `foo.x`, not `foo.#module-name#.x`.
529 let ext = crate_output
530 .temp_path(output_type, None)
537 if crate_output.outputs.contains_key(&output_type) {
538 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
539 // no good solution for this case, so warn the user.
541 "ignoring emit path because multiple .{} files \
545 } else if crate_output.single_output_file.is_some() {
546 // 3) Multiple codegen units, with `-o some_name`. We have
547 // no good solution for this case, so warn the user.
549 "ignoring -o because multiple .{} files \
554 // 4) Multiple codegen units, but no explicit name. We
555 // just leave the `foo.0.x` files in place.
556 // (We don't have to do any work in this case.)
561 // Flag to indicate whether the user explicitly requested bitcode.
562 // Otherwise, we produced it only as a temporary output, and will need
564 for output_type in crate_output.outputs.keys() {
566 OutputType::Bitcode => {
567 user_wants_bitcode = true;
568 // Copy to .bc, but always keep the .0.bc. There is a later
569 // check to figure out if we should delete .0.bc files, or keep
570 // them for making an rlib.
571 copy_if_one_unit(OutputType::Bitcode, true);
573 OutputType::LlvmAssembly => {
574 copy_if_one_unit(OutputType::LlvmAssembly, false);
576 OutputType::Assembly => {
577 copy_if_one_unit(OutputType::Assembly, false);
579 OutputType::Object => {
580 user_wants_objects = true;
581 copy_if_one_unit(OutputType::Object, true);
583 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
587 // Clean up unwanted temporary files.
589 // We create the following files by default:
590 // - #crate#.#module-name#.bc
591 // - #crate#.#module-name#.o
592 // - #crate#.crate.metadata.bc
593 // - #crate#.crate.metadata.o
594 // - #crate#.o (linked from crate.##.o)
595 // - #crate#.bc (copied from crate.##.bc)
596 // We may create additional files if requested by the user (through
597 // `-C save-temps` or `--emit=` flags).
599 if !sess.opts.cg.save_temps {
600 // Remove the temporary .#module-name#.o objects. If the user didn't
601 // explicitly request bitcode (with --emit=bc), and the bitcode is not
602 // needed for building an rlib, then we must remove .#module-name#.bc as
605 // Specific rules for keeping .#module-name#.bc:
606 // - If the user requested bitcode (`user_wants_bitcode`), and
607 // codegen_units > 1, then keep it.
608 // - If the user requested bitcode but codegen_units == 1, then we
609 // can toss .#module-name#.bc because we copied it to .bc earlier.
610 // - If we're not building an rlib and the user didn't request
611 // bitcode, then delete .#module-name#.bc.
612 // If you change how this works, also update back::link::link_rlib,
613 // where .#module-name#.bc files are (maybe) deleted after making an
615 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
617 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
619 let keep_numbered_objects =
620 needs_crate_object || (user_wants_objects && sess.codegen_units() > 1);
622 for module in compiled_modules.modules.iter() {
623 if let Some(ref path) = module.object {
624 if !keep_numbered_objects {
629 if let Some(ref path) = module.bytecode {
630 if !keep_numbered_bitcode {
636 if !user_wants_bitcode {
637 if let Some(ref metadata_module) = compiled_modules.metadata_module {
638 if let Some(ref path) = metadata_module.bytecode {
643 if let Some(ref allocator_module) = compiled_modules.allocator_module {
644 if let Some(ref path) = allocator_module.bytecode {
651 // We leave the following files around by default:
653 // - #crate#.crate.metadata.o
655 // These are used in linking steps and will be cleaned up afterward.
658 pub enum WorkItem<B: WriteBackendMethods> {
659 /// Optimize a newly codegened, totally unoptimized module.
660 Optimize(ModuleCodegen<B::Module>),
661 /// Copy the post-LTO artifacts from the incremental cache to the output
663 CopyPostLtoArtifacts(CachedModuleCodegen),
664 /// Performs (Thin)LTO on the given module.
665 LTO(lto::LtoModuleCodegen<B>),
668 impl<B: WriteBackendMethods> WorkItem<B> {
669 pub fn module_kind(&self) -> ModuleKind {
671 WorkItem::Optimize(ref m) => m.kind,
672 WorkItem::CopyPostLtoArtifacts(_) | WorkItem::LTO(_) => ModuleKind::Regular,
676 fn start_profiling<'a>(&self, cgcx: &'a CodegenContext<B>) -> TimingGuard<'a> {
678 WorkItem::Optimize(ref m) => {
679 cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &m.name[..])
681 WorkItem::CopyPostLtoArtifacts(ref m) => cgcx
683 .generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &m.name[..]),
684 WorkItem::LTO(ref m) => {
685 cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name())
691 enum WorkItemResult<B: WriteBackendMethods> {
692 Compiled(CompiledModule),
693 NeedsLink(ModuleCodegen<B::Module>),
694 NeedsFatLTO(FatLTOInput<B>),
695 NeedsThinLTO(String, B::ThinBuffer),
698 pub enum FatLTOInput<B: WriteBackendMethods> {
699 Serialized { name: String, buffer: B::ModuleBuffer },
700 InMemory(ModuleCodegen<B::Module>),
703 fn execute_work_item<B: ExtraBackendMethods>(
704 cgcx: &CodegenContext<B>,
705 work_item: WorkItem<B>,
706 ) -> Result<WorkItemResult<B>, FatalError> {
707 let module_config = cgcx.config(work_item.module_kind());
710 WorkItem::Optimize(module) => execute_optimize_work_item(cgcx, module, module_config),
711 WorkItem::CopyPostLtoArtifacts(module) => {
712 execute_copy_from_cache_work_item(cgcx, module, module_config)
714 WorkItem::LTO(module) => execute_lto_work_item(cgcx, module, module_config),
718 // Actual LTO type we end up choosing based on multiple factors.
719 pub enum ComputedLtoType {
725 pub fn compute_per_cgu_lto_type(
727 opts: &config::Options,
728 sess_crate_types: &[CrateType],
729 module_kind: ModuleKind,
730 ) -> ComputedLtoType {
731 // Metadata modules never participate in LTO regardless of the lto
733 if module_kind == ModuleKind::Metadata {
734 return ComputedLtoType::No;
737 // If the linker does LTO, we don't have to do it. Note that we
738 // keep doing full LTO, if it is requested, as not to break the
739 // assumption that the output will be a single module.
740 let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
742 // When we're automatically doing ThinLTO for multi-codegen-unit
743 // builds we don't actually want to LTO the allocator modules if
744 // it shows up. This is due to various linker shenanigans that
745 // we'll encounter later.
746 let is_allocator = module_kind == ModuleKind::Allocator;
748 // We ignore a request for full crate grath LTO if the cate type
749 // is only an rlib, as there is no full crate graph to process,
750 // that'll happen later.
752 // This use case currently comes up primarily for targets that
753 // require LTO so the request for LTO is always unconditionally
754 // passed down to the backend, but we don't actually want to do
755 // anything about it yet until we've got a final product.
756 let is_rlib = sess_crate_types.len() == 1 && sess_crate_types[0] == CrateType::Rlib;
759 Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
760 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
761 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
762 _ => ComputedLtoType::No,
766 fn execute_optimize_work_item<B: ExtraBackendMethods>(
767 cgcx: &CodegenContext<B>,
768 module: ModuleCodegen<B::Module>,
769 module_config: &ModuleConfig,
770 ) -> Result<WorkItemResult<B>, FatalError> {
771 let diag_handler = cgcx.create_diag_handler();
774 B::optimize(cgcx, &diag_handler, &module, module_config)?;
777 // After we've done the initial round of optimizations we need to
778 // decide whether to synchronously codegen this module or ship it
779 // back to the coordinator thread for further LTO processing (which
780 // has to wait for all the initial modules to be optimized).
782 let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
784 // If we're doing some form of incremental LTO then we need to be sure to
785 // save our module to disk first.
786 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
787 let filename = pre_lto_bitcode_filename(&module.name);
788 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
794 ComputedLtoType::No => finish_intra_module_work(cgcx, module, module_config),
795 ComputedLtoType::Thin => {
796 let (name, thin_buffer) = B::prepare_thin(module);
797 if let Some(path) = bitcode {
798 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
799 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
802 Ok(WorkItemResult::NeedsThinLTO(name, thin_buffer))
804 ComputedLtoType::Fat => match bitcode {
806 let (name, buffer) = B::serialize_module(module);
807 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
808 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
810 Ok(WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer }))
812 None => Ok(WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module))),
817 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
818 cgcx: &CodegenContext<B>,
819 module: CachedModuleCodegen,
820 module_config: &ModuleConfig,
821 ) -> Result<WorkItemResult<B>, FatalError> {
822 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
823 let mut object = None;
824 if let Some(saved_file) = module.source.saved_file {
825 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, Some(&module.name));
826 object = Some(obj_out.clone());
827 let source_file = in_incr_comp_dir(&incr_comp_session_dir, &saved_file);
829 "copying pre-existing module `{}` from {:?} to {}",
834 if let Err(err) = link_or_copy(&source_file, &obj_out) {
835 let diag_handler = cgcx.create_diag_handler();
836 diag_handler.err(&format!(
837 "unable to copy {} to {}: {}",
838 source_file.display(),
845 assert_eq!(object.is_some(), module_config.emit_obj != EmitObj::None);
847 Ok(WorkItemResult::Compiled(CompiledModule {
849 kind: ModuleKind::Regular,
855 fn execute_lto_work_item<B: ExtraBackendMethods>(
856 cgcx: &CodegenContext<B>,
857 mut module: lto::LtoModuleCodegen<B>,
858 module_config: &ModuleConfig,
859 ) -> Result<WorkItemResult<B>, FatalError> {
860 let module = unsafe { module.optimize(cgcx)? };
861 finish_intra_module_work(cgcx, module, module_config)
864 fn finish_intra_module_work<B: ExtraBackendMethods>(
865 cgcx: &CodegenContext<B>,
866 module: ModuleCodegen<B::Module>,
867 module_config: &ModuleConfig,
868 ) -> Result<WorkItemResult<B>, FatalError> {
869 let diag_handler = cgcx.create_diag_handler();
871 if !cgcx.opts.debugging_opts.combine_cgu
872 || module.kind == ModuleKind::Metadata
873 || module.kind == ModuleKind::Allocator
875 let module = unsafe { B::codegen(cgcx, &diag_handler, module, module_config)? };
876 Ok(WorkItemResult::Compiled(module))
878 Ok(WorkItemResult::NeedsLink(module))
882 pub enum Message<B: WriteBackendMethods> {
883 Token(io::Result<Acquired>),
885 result: FatLTOInput<B>,
890 thin_buffer: B::ThinBuffer,
894 module: ModuleCodegen<B::Module>,
898 result: Result<CompiledModule, Option<WorkerFatalError>>,
902 llvm_work_item: WorkItem<B>,
905 AddImportOnlyModule {
906 module_data: SerializedModule<B::ModuleBuffer>,
907 work_product: WorkProduct,
916 code: Option<DiagnosticId>,
920 #[derive(PartialEq, Clone, Copy, Debug)]
921 enum MainThreadWorkerState {
927 fn start_executing_work<B: ExtraBackendMethods>(
930 crate_info: &CrateInfo,
931 shared_emitter: SharedEmitter,
932 codegen_worker_send: Sender<Message<B>>,
933 coordinator_receive: Receiver<Box<dyn Any + Send>>,
936 regular_config: Arc<ModuleConfig>,
937 metadata_config: Arc<ModuleConfig>,
938 allocator_config: Arc<ModuleConfig>,
939 tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
940 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
941 let coordinator_send = tx_to_llvm_workers;
944 // Compute the set of symbols we need to retain when doing LTO (if we need to)
945 let exported_symbols = {
946 let mut exported_symbols = FxHashMap::default();
948 let copy_symbols = |cnum| {
950 .exported_symbols(cnum)
952 .map(|&(s, lvl)| (symbol_name_for_instance_in_crate(tcx, s, cnum), lvl))
960 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
961 Some(Arc::new(exported_symbols))
963 Lto::Fat | Lto::Thin => {
964 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
965 for &cnum in tcx.crates().iter() {
966 exported_symbols.insert(cnum, copy_symbols(cnum));
968 Some(Arc::new(exported_symbols))
973 // First up, convert our jobserver into a helper thread so we can use normal
974 // mpsc channels to manage our messages and such.
975 // After we've requested tokens then we'll, when we can,
976 // get tokens on `coordinator_receive` which will
977 // get managed in the main loop below.
978 let coordinator_send2 = coordinator_send.clone();
979 let helper = jobserver
980 .into_helper_thread(move |token| {
981 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
983 .expect("failed to spawn helper thread");
985 let mut each_linked_rlib_for_lto = Vec::new();
986 drop(link::each_linked_rlib(crate_info, &mut |cnum, path| {
987 if link::ignored_for_lto(sess, crate_info, cnum) {
990 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
993 let ol = if tcx.sess.opts.debugging_opts.no_codegen
994 || !tcx.sess.opts.output_types.should_codegen()
996 // If we know that we won’t be doing codegen, create target machines without optimisation.
999 tcx.backend_optimization_level(LOCAL_CRATE)
1001 let cgcx = CodegenContext::<B> {
1002 backend: backend.clone(),
1003 crate_types: sess.crate_types().to_vec(),
1004 each_linked_rlib_for_lto,
1006 no_landing_pads: sess.panic_strategy() == PanicStrategy::Abort,
1007 fewer_names: sess.fewer_names(),
1008 save_temps: sess.opts.cg.save_temps,
1009 opts: Arc::new(sess.opts.clone()),
1010 prof: sess.prof.clone(),
1012 remark: sess.opts.cg.remark.clone(),
1014 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1015 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1017 diag_emitter: shared_emitter.clone(),
1018 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1019 regular_module_config: regular_config,
1020 metadata_module_config: metadata_config,
1021 allocator_module_config: allocator_config,
1022 tm_factory: TargetMachineFactory(backend.target_machine_factory(tcx.sess, ol)),
1024 msvc_imps_needed: msvc_imps_needed(tcx),
1025 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1026 target_arch: tcx.sess.target.target.arch.clone(),
1027 debuginfo: tcx.sess.opts.debuginfo,
1030 // This is the "main loop" of parallel work happening for parallel codegen.
1031 // It's here that we manage parallelism, schedule work, and work with
1032 // messages coming from clients.
1034 // There are a few environmental pre-conditions that shape how the system
1037 // - Error reporting only can happen on the main thread because that's the
1038 // only place where we have access to the compiler `Session`.
1039 // - LLVM work can be done on any thread.
1040 // - Codegen can only happen on the main thread.
1041 // - Each thread doing substantial work most be in possession of a `Token`
1042 // from the `Jobserver`.
1043 // - The compiler process always holds one `Token`. Any additional `Tokens`
1044 // have to be requested from the `Jobserver`.
1048 // The error reporting restriction is handled separately from the rest: We
1049 // set up a `SharedEmitter` the holds an open channel to the main thread.
1050 // When an error occurs on any thread, the shared emitter will send the
1051 // error message to the receiver main thread (`SharedEmitterMain`). The
1052 // main thread will periodically query this error message queue and emit
1053 // any error messages it has received. It might even abort compilation if
1054 // has received a fatal error. In this case we rely on all other threads
1055 // being torn down automatically with the main thread.
1056 // Since the main thread will often be busy doing codegen work, error
1057 // reporting will be somewhat delayed, since the message queue can only be
1058 // checked in between to work packages.
1060 // Work Processing Infrastructure
1061 // ==============================
1062 // The work processing infrastructure knows three major actors:
1064 // - the coordinator thread,
1065 // - the main thread, and
1066 // - LLVM worker threads
1068 // The coordinator thread is running a message loop. It instructs the main
1069 // thread about what work to do when, and it will spawn off LLVM worker
1070 // threads as open LLVM WorkItems become available.
1072 // The job of the main thread is to codegen CGUs into LLVM work package
1073 // (since the main thread is the only thread that can do this). The main
1074 // thread will block until it receives a message from the coordinator, upon
1075 // which it will codegen one CGU, send it to the coordinator and block
1076 // again. This way the coordinator can control what the main thread is
1079 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1080 // available, it will spawn off a new LLVM worker thread and let it process
1081 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1082 // it will just shut down, which also frees all resources associated with
1083 // the given LLVM module, and sends a message to the coordinator that the
1084 // has been completed.
1088 // The scheduler's goal is to minimize the time it takes to complete all
1089 // work there is, however, we also want to keep memory consumption low
1090 // if possible. These two goals are at odds with each other: If memory
1091 // consumption were not an issue, we could just let the main thread produce
1092 // LLVM WorkItems at full speed, assuring maximal utilization of
1093 // Tokens/LLVM worker threads. However, since codegen usual is faster
1094 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1095 // WorkItem potentially holds on to a substantial amount of memory.
1097 // So the actual goal is to always produce just enough LLVM WorkItems as
1098 // not to starve our LLVM worker threads. That means, once we have enough
1099 // WorkItems in our queue, we can block the main thread, so it does not
1100 // produce more until we need them.
1102 // Doing LLVM Work on the Main Thread
1103 // ----------------------------------
1104 // Since the main thread owns the compiler processes implicit `Token`, it is
1105 // wasteful to keep it blocked without doing any work. Therefore, what we do
1106 // in this case is: We spawn off an additional LLVM worker thread that helps
1107 // reduce the queue. The work it is doing corresponds to the implicit
1108 // `Token`. The coordinator will mark the main thread as being busy with
1109 // LLVM work. (The actual work happens on another OS thread but we just care
1110 // about `Tokens`, not actual threads).
1112 // When any LLVM worker thread finishes while the main thread is marked as
1113 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1114 // of the just finished thread to the LLVM worker thread that is working on
1115 // behalf of the main thread's implicit Token, thus freeing up the main
1116 // thread again. The coordinator can then again decide what the main thread
1117 // should do. This allows the coordinator to make decisions at more points
1120 // Striking a Balance between Throughput and Memory Consumption
1121 // ------------------------------------------------------------
1122 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1123 // memory consumption as low as possible, are in conflict with each other,
1124 // we have to find a trade off between them. Right now, the goal is to keep
1125 // all workers busy, which means that no worker should find the queue empty
1126 // when it is ready to start.
1127 // How do we do achieve this? Good question :) We actually never know how
1128 // many `Tokens` are potentially available so it's hard to say how much to
1129 // fill up the queue before switching the main thread to LLVM work. Also we
1130 // currently don't have a means to estimate how long a running LLVM worker
1131 // will still be busy with it's current WorkItem. However, we know the
1132 // maximal count of available Tokens that makes sense (=the number of CPU
1133 // cores), so we can take a conservative guess. The heuristic we use here
1134 // is implemented in the `queue_full_enough()` function.
1136 // Some Background on Jobservers
1137 // -----------------------------
1138 // It's worth also touching on the management of parallelism here. We don't
1139 // want to just spawn a thread per work item because while that's optimal
1140 // parallelism it may overload a system with too many threads or violate our
1141 // configuration for the maximum amount of cpu to use for this process. To
1142 // manage this we use the `jobserver` crate.
1144 // Job servers are an artifact of GNU make and are used to manage
1145 // parallelism between processes. A jobserver is a glorified IPC semaphore
1146 // basically. Whenever we want to run some work we acquire the semaphore,
1147 // and whenever we're done with that work we release the semaphore. In this
1148 // manner we can ensure that the maximum number of parallel workers is
1149 // capped at any one point in time.
1151 // LTO and the coordinator thread
1152 // ------------------------------
1154 // The final job the coordinator thread is responsible for is managing LTO
1155 // and how that works. When LTO is requested what we'll to is collect all
1156 // optimized LLVM modules into a local vector on the coordinator. Once all
1157 // modules have been codegened and optimized we hand this to the `lto`
1158 // module for further optimization. The `lto` module will return back a list
1159 // of more modules to work on, which the coordinator will continue to spawn
1162 // Each LLVM module is automatically sent back to the coordinator for LTO if
1163 // necessary. There's already optimizations in place to avoid sending work
1164 // back to the coordinator if LTO isn't requested.
1165 return thread::spawn(move || {
1166 let max_workers = num_cpus::get();
1167 let mut worker_id_counter = 0;
1168 let mut free_worker_ids = Vec::new();
1169 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1170 if let Some(id) = free_worker_ids.pop() {
1173 let id = worker_id_counter;
1174 worker_id_counter += 1;
1179 // This is where we collect codegen units that have gone all the way
1180 // through codegen and LLVM.
1181 let mut compiled_modules = vec![];
1182 let mut compiled_metadata_module = None;
1183 let mut compiled_allocator_module = None;
1184 let mut needs_link = Vec::new();
1185 let mut needs_fat_lto = Vec::new();
1186 let mut needs_thin_lto = Vec::new();
1187 let mut lto_import_only_modules = Vec::new();
1188 let mut started_lto = false;
1189 let mut codegen_aborted = false;
1191 // This flag tracks whether all items have gone through codegens
1192 let mut codegen_done = false;
1194 // This is the queue of LLVM work items that still need processing.
1195 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1197 // This are the Jobserver Tokens we currently hold. Does not include
1198 // the implicit Token the compiler process owns no matter what.
1199 let mut tokens = Vec::new();
1201 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1202 let mut running = 0;
1204 let prof = &cgcx.prof;
1205 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1207 // Run the message loop while there's still anything that needs message
1208 // processing. Note that as soon as codegen is aborted we simply want to
1209 // wait for all existing work to finish, so many of the conditions here
1210 // only apply if codegen hasn't been aborted as they represent pending
1214 || (!codegen_aborted
1215 && !(work_items.is_empty()
1216 && needs_fat_lto.is_empty()
1217 && needs_thin_lto.is_empty()
1218 && lto_import_only_modules.is_empty()
1219 && main_thread_worker_state == MainThreadWorkerState::Idle))
1221 // While there are still CGUs to be codegened, the coordinator has
1222 // to decide how to utilize the compiler processes implicit Token:
1223 // For codegenning more CGU or for running them through LLVM.
1225 if main_thread_worker_state == MainThreadWorkerState::Idle {
1226 if !queue_full_enough(work_items.len(), running, max_workers) {
1227 // The queue is not full enough, codegen more items:
1228 if codegen_worker_send.send(Message::CodegenItem).is_err() {
1229 panic!("Could not send Message::CodegenItem to main thread")
1231 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1233 // The queue is full enough to not let the worker
1234 // threads starve. Use the implicit Token to do some
1237 work_items.pop().expect("queue empty - queue_full_enough() broken?");
1238 let cgcx = CodegenContext {
1239 worker: get_worker_id(&mut free_worker_ids),
1242 maybe_start_llvm_timer(
1244 cgcx.config(item.module_kind()),
1245 &mut llvm_start_time,
1247 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1248 spawn_work(cgcx, item);
1251 } else if codegen_aborted {
1252 // don't queue up any more work if codegen was aborted, we're
1253 // just waiting for our existing children to finish
1255 // If we've finished everything related to normal codegen
1256 // then it must be the case that we've got some LTO work to do.
1257 // Perform the serial work here of figuring out what we're
1258 // going to LTO and then push a bunch of work items onto our
1260 if work_items.is_empty()
1262 && main_thread_worker_state == MainThreadWorkerState::Idle
1264 assert!(!started_lto);
1267 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1268 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1269 let import_only_modules = mem::take(&mut lto_import_only_modules);
1272 generate_lto_work(&cgcx, needs_fat_lto, needs_thin_lto, import_only_modules)
1274 let insertion_index = work_items
1275 .binary_search_by_key(&cost, |&(_, cost)| cost)
1276 .unwrap_or_else(|e| e);
1277 work_items.insert(insertion_index, (work, cost));
1278 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1279 helper.request_token();
1284 // In this branch, we know that everything has been codegened,
1285 // so it's just a matter of determining whether the implicit
1286 // Token is free to use for LLVM work.
1287 match main_thread_worker_state {
1288 MainThreadWorkerState::Idle => {
1289 if let Some((item, _)) = work_items.pop() {
1290 let cgcx = CodegenContext {
1291 worker: get_worker_id(&mut free_worker_ids),
1294 maybe_start_llvm_timer(
1296 cgcx.config(item.module_kind()),
1297 &mut llvm_start_time,
1299 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1300 spawn_work(cgcx, item);
1302 // There is no unstarted work, so let the main thread
1303 // take over for a running worker. Otherwise the
1304 // implicit token would just go to waste.
1305 // We reduce the `running` counter by one. The
1306 // `tokens.truncate()` below will take care of
1307 // giving the Token back.
1308 debug_assert!(running > 0);
1310 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1313 MainThreadWorkerState::Codegenning => bug!(
1314 "codegen worker should not be codegenning after \
1315 codegen was already completed"
1317 MainThreadWorkerState::LLVMing => {
1318 // Already making good use of that token
1323 // Spin up what work we can, only doing this while we've got available
1324 // parallelism slots and work left to spawn.
1325 while !codegen_aborted && !work_items.is_empty() && running < tokens.len() {
1326 let (item, _) = work_items.pop().unwrap();
1328 maybe_start_llvm_timer(prof, cgcx.config(item.module_kind()), &mut llvm_start_time);
1331 CodegenContext { worker: get_worker_id(&mut free_worker_ids), ..cgcx.clone() };
1333 spawn_work(cgcx, item);
1337 // Relinquish accidentally acquired extra tokens
1338 tokens.truncate(running);
1340 // If a thread exits successfully then we drop a token associated
1341 // with that worker and update our `running` count. We may later
1342 // re-acquire a token to continue running more work. We may also not
1343 // actually drop a token here if the worker was running with an
1344 // "ephemeral token"
1345 let mut free_worker = |worker_id| {
1346 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1347 main_thread_worker_state = MainThreadWorkerState::Idle;
1352 free_worker_ids.push(worker_id);
1355 let msg = coordinator_receive.recv().unwrap();
1356 match *msg.downcast::<Message<B>>().ok().unwrap() {
1357 // Save the token locally and the next turn of the loop will use
1358 // this to spawn a new unit of work, or it may get dropped
1359 // immediately if we have no more work to spawn.
1360 Message::Token(token) => {
1365 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1366 // If the main thread token is used for LLVM work
1367 // at the moment, we turn that thread into a regular
1368 // LLVM worker thread, so the main thread is free
1369 // to react to codegen demand.
1370 main_thread_worker_state = MainThreadWorkerState::Idle;
1375 let msg = &format!("failed to acquire jobserver token: {}", e);
1376 shared_emitter.fatal(msg);
1377 // Exit the coordinator thread
1383 Message::CodegenDone { llvm_work_item, cost } => {
1384 // We keep the queue sorted by estimated processing cost,
1385 // so that more expensive items are processed earlier. This
1386 // is good for throughput as it gives the main thread more
1387 // time to fill up the queue and it avoids scheduling
1388 // expensive items to the end.
1389 // Note, however, that this is not ideal for memory
1390 // consumption, as LLVM module sizes are not evenly
1392 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1393 let insertion_index = match insertion_index {
1394 Ok(idx) | Err(idx) => idx,
1396 work_items.insert(insertion_index, (llvm_work_item, cost));
1398 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1399 helper.request_token();
1401 assert!(!codegen_aborted);
1402 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1403 main_thread_worker_state = MainThreadWorkerState::Idle;
1406 Message::CodegenComplete => {
1407 codegen_done = true;
1408 assert!(!codegen_aborted);
1409 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1410 main_thread_worker_state = MainThreadWorkerState::Idle;
1413 // If codegen is aborted that means translation was aborted due
1414 // to some normal-ish compiler error. In this situation we want
1415 // to exit as soon as possible, but we want to make sure all
1416 // existing work has finished. Flag codegen as being done, and
1417 // then conditions above will ensure no more work is spawned but
1418 // we'll keep executing this loop until `running` hits 0.
1419 Message::CodegenAborted => {
1420 assert!(!codegen_aborted);
1421 codegen_done = true;
1422 codegen_aborted = true;
1423 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1425 Message::Done { result: Ok(compiled_module), worker_id } => {
1426 free_worker(worker_id);
1427 match compiled_module.kind {
1428 ModuleKind::Regular => {
1429 compiled_modules.push(compiled_module);
1431 ModuleKind::Metadata => {
1432 assert!(compiled_metadata_module.is_none());
1433 compiled_metadata_module = Some(compiled_module);
1435 ModuleKind::Allocator => {
1436 assert!(compiled_allocator_module.is_none());
1437 compiled_allocator_module = Some(compiled_module);
1441 Message::NeedsLink { module, worker_id } => {
1442 free_worker(worker_id);
1443 needs_link.push(module);
1445 Message::NeedsFatLTO { result, worker_id } => {
1446 assert!(!started_lto);
1447 free_worker(worker_id);
1448 needs_fat_lto.push(result);
1450 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1451 assert!(!started_lto);
1452 free_worker(worker_id);
1453 needs_thin_lto.push((name, thin_buffer));
1455 Message::AddImportOnlyModule { module_data, work_product } => {
1456 assert!(!started_lto);
1457 assert!(!codegen_done);
1458 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1459 lto_import_only_modules.push((module_data, work_product));
1460 main_thread_worker_state = MainThreadWorkerState::Idle;
1462 // If the thread failed that means it panicked, so we abort immediately.
1463 Message::Done { result: Err(None), worker_id: _ } => {
1464 bug!("worker thread panicked");
1466 Message::Done { result: Err(Some(WorkerFatalError)), worker_id: _ } => {
1469 Message::CodegenItem => bug!("the coordinator should not receive codegen requests"),
1473 let needs_link = mem::take(&mut needs_link);
1474 if !needs_link.is_empty() {
1475 assert!(compiled_modules.is_empty());
1476 let diag_handler = cgcx.create_diag_handler();
1477 let module = B::run_link(&cgcx, &diag_handler, needs_link).map_err(|_| ())?;
1478 let module = unsafe {
1479 B::codegen(&cgcx, &diag_handler, module, cgcx.config(ModuleKind::Regular))
1482 compiled_modules.push(module);
1485 // Drop to print timings
1486 drop(llvm_start_time);
1488 // Regardless of what order these modules completed in, report them to
1489 // the backend in the same order every time to ensure that we're handing
1490 // out deterministic results.
1491 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1493 Ok(CompiledModules {
1494 modules: compiled_modules,
1495 metadata_module: compiled_metadata_module,
1496 allocator_module: compiled_allocator_module,
1500 // A heuristic that determines if we have enough LLVM WorkItems in the
1501 // queue so that the main thread can do LLVM work instead of codegen
1502 fn queue_full_enough(
1503 items_in_queue: usize,
1504 workers_running: usize,
1508 items_in_queue > 0 && items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1511 fn maybe_start_llvm_timer<'a>(
1512 prof: &'a SelfProfilerRef,
1513 config: &ModuleConfig,
1514 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1516 if config.time_module && llvm_start_time.is_none() {
1517 *llvm_start_time = Some(prof.extra_verbose_generic_activity("LLVM_passes", "crate"));
1522 /// `FatalError` is explicitly not `Send`.
1524 pub struct WorkerFatalError;
1526 fn spawn_work<B: ExtraBackendMethods>(cgcx: CodegenContext<B>, work: WorkItem<B>) {
1527 thread::spawn(move || {
1528 // Set up a destructor which will fire off a message that we're done as
1530 struct Bomb<B: ExtraBackendMethods> {
1531 coordinator_send: Sender<Box<dyn Any + Send>>,
1532 result: Option<Result<WorkItemResult<B>, FatalError>>,
1535 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1536 fn drop(&mut self) {
1537 let worker_id = self.worker_id;
1538 let msg = match self.result.take() {
1539 Some(Ok(WorkItemResult::Compiled(m))) => {
1540 Message::Done::<B> { result: Ok(m), worker_id }
1542 Some(Ok(WorkItemResult::NeedsLink(m))) => {
1543 Message::NeedsLink::<B> { module: m, worker_id }
1545 Some(Ok(WorkItemResult::NeedsFatLTO(m))) => {
1546 Message::NeedsFatLTO::<B> { result: m, worker_id }
1548 Some(Ok(WorkItemResult::NeedsThinLTO(name, thin_buffer))) => {
1549 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1551 Some(Err(FatalError)) => {
1552 Message::Done::<B> { result: Err(Some(WorkerFatalError)), worker_id }
1554 None => Message::Done::<B> { result: Err(None), worker_id },
1556 drop(self.coordinator_send.send(Box::new(msg)));
1560 let mut bomb = Bomb::<B> {
1561 coordinator_send: cgcx.coordinator_send.clone(),
1563 worker_id: cgcx.worker,
1566 // Execute the work itself, and if it finishes successfully then flag
1567 // ourselves as a success as well.
1569 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1570 // as a diagnostic was already sent off to the main thread - just
1571 // surface that there was an error in this worker.
1573 let _prof_timer = work.start_profiling(&cgcx);
1574 Some(execute_work_item(&cgcx, work))
1579 enum SharedEmitterMessage {
1580 Diagnostic(Diagnostic),
1581 InlineAsmError(u32, String, Level, Option<(String, Vec<InnerSpan>)>),
1587 pub struct SharedEmitter {
1588 sender: Sender<SharedEmitterMessage>,
1591 pub struct SharedEmitterMain {
1592 receiver: Receiver<SharedEmitterMessage>,
1595 impl SharedEmitter {
1596 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1597 let (sender, receiver) = channel();
1599 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1602 pub fn inline_asm_error(
1607 source: Option<(String, Vec<InnerSpan>)>,
1609 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)));
1612 pub fn fatal(&self, msg: &str) {
1613 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1617 impl Emitter for SharedEmitter {
1618 fn emit_diagnostic(&mut self, diag: &rustc_errors::Diagnostic) {
1619 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1620 msg: diag.message(),
1621 code: diag.code.clone(),
1624 for child in &diag.children {
1625 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1626 msg: child.message(),
1631 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1633 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
1638 impl SharedEmitterMain {
1639 pub fn check(&self, sess: &Session, blocking: bool) {
1641 let message = if blocking {
1642 match self.receiver.recv() {
1643 Ok(message) => Ok(message),
1647 match self.receiver.try_recv() {
1648 Ok(message) => Ok(message),
1654 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1655 let handler = sess.diagnostic();
1656 let mut d = rustc_errors::Diagnostic::new(diag.lvl, &diag.msg);
1657 if let Some(code) = diag.code {
1660 handler.emit_diagnostic(&d);
1662 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => {
1663 let msg = msg.strip_prefix("error: ").unwrap_or(&msg);
1665 let mut err = match level {
1666 Level::Error => sess.struct_err(&msg),
1667 Level::Warning => sess.struct_warn(&msg),
1668 Level::Note => sess.struct_note_without_error(&msg),
1669 _ => bug!("Invalid inline asm diagnostic level"),
1672 // If the cookie is 0 then we don't have span information.
1674 let pos = BytePos::from_u32(cookie);
1675 let span = Span::with_root_ctxt(pos, pos);
1679 // Point to the generated assembly if it is available.
1680 if let Some((buffer, spans)) = source {
1683 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
1684 let source_span = Span::with_root_ctxt(source.start_pos, source.end_pos);
1686 spans.iter().map(|sp| source_span.from_inner(*sp)).collect();
1687 err.span_note(spans, "instantiated into assembly here");
1692 Ok(SharedEmitterMessage::AbortIfErrors) => {
1693 sess.abort_if_errors();
1695 Ok(SharedEmitterMessage::Fatal(msg)) => {
1706 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1708 pub crate_name: Symbol,
1709 pub metadata: EncodedMetadata,
1710 pub windows_subsystem: Option<String>,
1711 pub linker_info: LinkerInfo,
1712 pub crate_info: CrateInfo,
1713 pub coordinator_send: Sender<Box<dyn Any + Send>>,
1714 pub codegen_worker_receive: Receiver<Message<B>>,
1715 pub shared_emitter_main: SharedEmitterMain,
1716 pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1717 pub output_filenames: Arc<OutputFilenames>,
1720 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1721 pub fn join(self, sess: &Session) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1722 let _timer = sess.timer("finish_ongoing_codegen");
1724 self.shared_emitter_main.check(sess, true);
1725 let future = self.future;
1726 let compiled_modules = sess.time("join_worker_thread", || match future.join() {
1727 Ok(Ok(compiled_modules)) => compiled_modules,
1729 sess.abort_if_errors();
1730 panic!("expected abort due to worker thread errors")
1733 bug!("panic during codegen/LLVM phase");
1737 sess.cgu_reuse_tracker.check_expected_reuse(sess.diagnostic());
1739 sess.abort_if_errors();
1742 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
1743 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
1745 // FIXME: time_llvm_passes support - does this use a global context or
1747 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1748 self.backend.print_pass_timings()
1753 crate_name: self.crate_name,
1754 metadata: self.metadata,
1755 windows_subsystem: self.windows_subsystem,
1756 linker_info: self.linker_info,
1757 crate_info: self.crate_info,
1759 modules: compiled_modules.modules,
1760 allocator_module: compiled_modules.allocator_module,
1761 metadata_module: compiled_modules.metadata_module,
1767 pub fn submit_pre_codegened_module_to_llvm(
1770 module: ModuleCodegen<B::Module>,
1772 self.wait_for_signal_to_codegen_item();
1773 self.check_for_errors(tcx.sess);
1775 // These are generally cheap and won't throw off scheduling.
1777 submit_codegened_module_to_llvm(&self.backend, &self.coordinator_send, module, cost);
1780 pub fn codegen_finished(&self, tcx: TyCtxt<'_>) {
1781 self.wait_for_signal_to_codegen_item();
1782 self.check_for_errors(tcx.sess);
1783 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1786 /// Consumes this context indicating that codegen was entirely aborted, and
1787 /// we need to exit as quickly as possible.
1789 /// This method blocks the current thread until all worker threads have
1790 /// finished, and all worker threads should have exited or be real close to
1791 /// exiting at this point.
1792 pub fn codegen_aborted(self) {
1793 // Signal to the coordinator it should spawn no more work and start
1795 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1796 drop(self.future.join());
1799 pub fn check_for_errors(&self, sess: &Session) {
1800 self.shared_emitter_main.check(sess, false);
1803 pub fn wait_for_signal_to_codegen_item(&self) {
1804 match self.codegen_worker_receive.recv() {
1805 Ok(Message::CodegenItem) => {
1808 Ok(_) => panic!("unexpected message"),
1810 // One of the LLVM threads must have panicked, fall through so
1811 // error handling can be reached.
1817 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1819 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1820 module: ModuleCodegen<B::Module>,
1823 let llvm_work_item = WorkItem::Optimize(module);
1824 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost })));
1827 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1829 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1830 module: CachedModuleCodegen,
1832 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1833 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost: 0 })));
1836 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1839 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1840 module: CachedModuleCodegen,
1842 let filename = pre_lto_bitcode_filename(&module.name);
1843 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1844 let file = fs::File::open(&bc_path)
1845 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
1848 memmap::Mmap::map(&file).unwrap_or_else(|e| {
1849 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1852 // Schedule the module to be loaded
1853 drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule::<B> {
1854 module_data: SerializedModule::FromUncompressedFile(mmap),
1855 work_product: module.source,
1859 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1860 format!("{}.{}", module_name, PRE_LTO_BC_EXT)
1863 fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
1864 // This should never be true (because it's not supported). If it is true,
1865 // something is wrong with commandline arg validation.
1867 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
1868 && tcx.sess.target.target.options.is_like_windows
1869 && tcx.sess.opts.cg.prefer_dynamic)
1872 tcx.sess.target.target.options.is_like_windows &&
1873 tcx.sess.crate_types().iter().any(|ct| *ct == CrateType::Rlib) &&
1874 // ThinLTO can't handle this workaround in all cases, so we don't
1875 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
1876 // dynamic linking when linker plugin LTO is enabled.
1877 !tcx.sess.opts.cg.linker_plugin_lto.enabled()