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::svh::Svh;
17 use rustc_data_structures::sync::Lrc;
18 use rustc_errors::emitter::Emitter;
19 use rustc_errors::{DiagnosticId, FatalError, Handler, Level};
20 use rustc_fs_util::link_or_copy;
21 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
22 use rustc_incremental::{
23 copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
25 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
26 use rustc_middle::middle::cstore::EncodedMetadata;
27 use rustc_middle::middle::exported_symbols::SymbolExportLevel;
28 use rustc_middle::ty::TyCtxt;
29 use rustc_session::cgu_reuse_tracker::CguReuseTracker;
30 use rustc_session::config::{self, CrateType, Lto, OutputFilenames, OutputType};
31 use rustc_session::config::{Passes, SanitizerSet, SwitchWithOptPath};
32 use rustc_session::Session;
33 use rustc_span::source_map::SourceMap;
34 use rustc_span::symbol::{sym, Symbol};
35 use rustc_span::{BytePos, FileName, InnerSpan, Pos, Span};
36 use rustc_target::spec::{MergeFunctions, PanicStrategy};
42 use std::path::{Path, PathBuf};
44 use std::sync::mpsc::{channel, Receiver, Sender};
48 const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
50 /// What kind of object file to emit.
51 #[derive(Clone, Copy, PartialEq)]
56 // Just uncompressed llvm bitcode. Provides easy compatibility with
57 // emscripten's ecc compiler, when used as the linker.
60 // Object code, possibly augmented with a bitcode section.
61 ObjectCode(BitcodeSection),
64 /// What kind of llvm bitcode section to embed in an object file.
65 #[derive(Clone, Copy, PartialEq)]
66 pub enum BitcodeSection {
67 // No bitcode section.
70 // A full, uncompressed bitcode section.
74 /// Module-specific configuration for `optimize_and_codegen`.
75 pub struct ModuleConfig {
76 /// Names of additional optimization passes to run.
77 pub passes: Vec<String>,
78 /// Some(level) to optimize at a certain level, or None to run
79 /// absolutely no optimizations (used for the metadata module).
80 pub opt_level: Option<config::OptLevel>,
82 /// Some(level) to optimize binary size, or None to not affect program size.
83 pub opt_size: Option<config::OptLevel>,
85 pub pgo_gen: SwitchWithOptPath,
86 pub pgo_use: Option<PathBuf>,
88 pub sanitizer: SanitizerSet,
89 pub sanitizer_recover: SanitizerSet,
90 pub sanitizer_memory_track_origins: usize,
92 // Flags indicating which outputs to produce.
93 pub emit_pre_lto_bc: bool,
94 pub emit_no_opt_bc: bool,
98 pub emit_obj: EmitObj,
99 pub bc_cmdline: String,
101 // Miscellaneous flags. These are mostly copied from command-line
103 pub verify_llvm_ir: bool,
104 pub no_prepopulate_passes: bool,
105 pub no_builtins: bool,
106 pub time_module: bool,
107 pub vectorize_loop: bool,
108 pub vectorize_slp: bool,
109 pub merge_functions: bool,
110 pub inline_threshold: Option<usize>,
111 pub new_llvm_pass_manager: bool,
112 pub emit_lifetime_markers: bool,
120 is_compiler_builtins: bool,
122 // If it's a regular module, use `$regular`, otherwise use `$other`.
123 // `$regular` and `$other` are evaluated lazily.
124 macro_rules! if_regular {
125 ($regular: expr, $other: expr) => {
126 if let ModuleKind::Regular = kind { $regular } else { $other }
130 let opt_level_and_size = if_regular!(Some(sess.opts.optimize), None);
132 let save_temps = sess.opts.cg.save_temps;
134 let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
136 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
137 ModuleKind::Allocator => false,
138 ModuleKind::Metadata => sess.opts.output_types.contains_key(&OutputType::Metadata),
141 let emit_obj = if !should_emit_obj {
143 } else if sess.target.target.options.obj_is_bitcode
144 || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
146 // This case is selected if the target uses objects as bitcode, or
147 // if linker plugin LTO is enabled. In the linker plugin LTO case
148 // the assumption is that the final link-step will read the bitcode
149 // and convert it to object code. This may be done by either the
150 // native linker or rustc itself.
152 // Note, however, that the linker-plugin-lto requested here is
153 // explicitly ignored for `#![no_builtins]` crates. These crates are
154 // specifically ignored by rustc's LTO passes and wouldn't work if
155 // loaded into the linker. These crates define symbols that LLVM
156 // lowers intrinsics to, and these symbol dependencies aren't known
157 // until after codegen. As a result any crate marked
158 // `#![no_builtins]` is assumed to not participate in LTO and
159 // instead goes on to generate object code.
161 } else if need_bitcode_in_object(sess) {
162 EmitObj::ObjectCode(BitcodeSection::Full)
164 EmitObj::ObjectCode(BitcodeSection::None)
170 let mut passes = sess.opts.cg.passes.clone();
171 // compiler_builtins overrides the codegen-units settings,
172 // which is incompatible with -Zprofile which requires that
173 // only a single codegen unit is used per crate.
174 if sess.opts.debugging_opts.profile && !is_compiler_builtins {
175 passes.push("insert-gcov-profiling".to_owned());
178 // The rustc option `-Zinstrument_coverage` injects intrinsic calls to
179 // `llvm.instrprof.increment()`, which requires the LLVM `instrprof` pass.
180 if sess.opts.debugging_opts.instrument_coverage {
181 passes.push("instrprof".to_owned());
188 opt_level: opt_level_and_size,
189 opt_size: opt_level_and_size,
191 pgo_gen: if_regular!(
192 sess.opts.cg.profile_generate.clone(),
193 SwitchWithOptPath::Disabled
195 pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
197 sanitizer: if_regular!(sess.opts.debugging_opts.sanitizer, SanitizerSet::empty()),
198 sanitizer_recover: if_regular!(
199 sess.opts.debugging_opts.sanitizer_recover,
200 SanitizerSet::empty()
202 sanitizer_memory_track_origins: if_regular!(
203 sess.opts.debugging_opts.sanitizer_memory_track_origins,
207 emit_pre_lto_bc: if_regular!(
208 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
211 emit_no_opt_bc: if_regular!(save_temps, false),
212 emit_bc: if_regular!(
213 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
216 emit_ir: if_regular!(
217 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
220 emit_asm: if_regular!(
221 sess.opts.output_types.contains_key(&OutputType::Assembly),
225 bc_cmdline: sess.target.target.options.bitcode_llvm_cmdline.clone(),
227 verify_llvm_ir: sess.verify_llvm_ir(),
228 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
229 no_builtins: no_builtins || sess.target.target.options.no_builtins,
231 // Exclude metadata and allocator modules from time_passes output,
232 // since they throw off the "LLVM passes" measurement.
233 time_module: if_regular!(true, false),
235 // Copy what clang does by turning on loop vectorization at O2 and
236 // slp vectorization at O3.
237 vectorize_loop: !sess.opts.cg.no_vectorize_loops
238 && (sess.opts.optimize == config::OptLevel::Default
239 || sess.opts.optimize == config::OptLevel::Aggressive),
240 vectorize_slp: !sess.opts.cg.no_vectorize_slp
241 && sess.opts.optimize == config::OptLevel::Aggressive,
243 // Some targets (namely, NVPTX) interact badly with the
244 // MergeFunctions pass. This is because MergeFunctions can generate
245 // new function calls which may interfere with the target calling
246 // convention; e.g. for the NVPTX target, PTX kernels should not
247 // call other PTX kernels. MergeFunctions can also be configured to
248 // generate aliases instead, but aliases are not supported by some
249 // backends (again, NVPTX). Therefore, allow targets to opt out of
250 // the MergeFunctions pass, but otherwise keep the pass enabled (at
251 // O2 and O3) since it can be useful for reducing code size.
252 merge_functions: match sess
256 .unwrap_or(sess.target.target.options.merge_functions)
258 MergeFunctions::Disabled => false,
259 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
260 sess.opts.optimize == config::OptLevel::Default
261 || sess.opts.optimize == config::OptLevel::Aggressive
265 inline_threshold: sess.opts.cg.inline_threshold,
266 new_llvm_pass_manager: sess.opts.debugging_opts.new_llvm_pass_manager,
267 emit_lifetime_markers: sess.emit_lifetime_markers(),
271 pub fn bitcode_needed(&self) -> bool {
273 || self.emit_obj == EmitObj::Bitcode
274 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
278 // HACK(eddyb) work around `#[derive]` producing wrong bounds for `Clone`.
279 pub struct TargetMachineFactory<B: WriteBackendMethods>(
280 pub Arc<dyn Fn() -> Result<B::TargetMachine, String> + Send + Sync>,
283 impl<B: WriteBackendMethods> Clone for TargetMachineFactory<B> {
284 fn clone(&self) -> Self {
285 TargetMachineFactory(self.0.clone())
289 pub type ExportedSymbols = FxHashMap<CrateNum, Arc<Vec<(String, SymbolExportLevel)>>>;
291 /// Additional resources used by optimize_and_codegen (not module specific)
293 pub struct CodegenContext<B: WriteBackendMethods> {
294 // Resources needed when running LTO
296 pub prof: SelfProfilerRef,
298 pub no_landing_pads: bool,
299 pub save_temps: bool,
300 pub fewer_names: bool,
301 pub exported_symbols: Option<Arc<ExportedSymbols>>,
302 pub opts: Arc<config::Options>,
303 pub crate_types: Vec<CrateType>,
304 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
305 pub output_filenames: Arc<OutputFilenames>,
306 pub regular_module_config: Arc<ModuleConfig>,
307 pub metadata_module_config: Arc<ModuleConfig>,
308 pub allocator_module_config: Arc<ModuleConfig>,
309 pub tm_factory: TargetMachineFactory<B>,
310 pub msvc_imps_needed: bool,
311 pub target_pointer_width: String,
312 pub target_arch: String,
313 pub debuginfo: config::DebugInfo,
315 // Number of cgus excluding the allocator/metadata modules
316 pub total_cgus: usize,
317 // Handler to use for diagnostics produced during codegen.
318 pub diag_emitter: SharedEmitter,
319 // LLVM optimizations for which we want to print remarks.
321 // Worker thread number
323 // The incremental compilation session directory, or None if we are not
324 // compiling incrementally
325 pub incr_comp_session_dir: Option<PathBuf>,
326 // Used to update CGU re-use information during the thinlto phase.
327 pub cgu_reuse_tracker: CguReuseTracker,
328 // Channel back to the main control thread to send messages to
329 pub coordinator_send: Sender<Box<dyn Any + Send>>,
332 impl<B: WriteBackendMethods> CodegenContext<B> {
333 pub fn create_diag_handler(&self) -> Handler {
334 Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
337 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
339 ModuleKind::Regular => &self.regular_module_config,
340 ModuleKind::Metadata => &self.metadata_module_config,
341 ModuleKind::Allocator => &self.allocator_module_config,
346 fn generate_lto_work<B: ExtraBackendMethods>(
347 cgcx: &CodegenContext<B>,
348 needs_fat_lto: Vec<FatLTOInput<B>>,
349 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
350 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
351 ) -> Vec<(WorkItem<B>, u64)> {
352 let _prof_timer = cgcx.prof.generic_activity("codegen_generate_lto_work");
354 let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
355 assert!(needs_thin_lto.is_empty());
357 B::run_fat_lto(cgcx, needs_fat_lto, import_only_modules).unwrap_or_else(|e| e.raise());
358 (vec![lto_module], vec![])
360 assert!(needs_fat_lto.is_empty());
361 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules).unwrap_or_else(|e| e.raise())
367 let cost = module.cost();
368 (WorkItem::LTO(module), cost)
370 .chain(copy_jobs.into_iter().map(|wp| {
372 WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
373 name: wp.cgu_name.clone(),
382 pub struct CompiledModules {
383 pub modules: Vec<CompiledModule>,
384 pub metadata_module: Option<CompiledModule>,
385 pub allocator_module: Option<CompiledModule>,
388 fn need_bitcode_in_object(sess: &Session) -> bool {
389 let requested_for_rlib = sess.opts.cg.embed_bitcode
390 && sess.crate_types().contains(&CrateType::Rlib)
391 && sess.opts.output_types.contains_key(&OutputType::Exe);
392 let forced_by_target = sess.target.target.options.forces_embed_bitcode;
393 requested_for_rlib || forced_by_target
396 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
397 if sess.opts.incremental.is_none() {
403 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
407 pub fn start_async_codegen<B: ExtraBackendMethods>(
410 metadata: EncodedMetadata,
412 ) -> OngoingCodegen<B> {
413 let (coordinator_send, coordinator_receive) = channel();
416 let crate_name = tcx.crate_name(LOCAL_CRATE);
417 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
418 let no_builtins = tcx.sess.contains_name(&tcx.hir().krate().item.attrs, sym::no_builtins);
419 let is_compiler_builtins =
420 tcx.sess.contains_name(&tcx.hir().krate().item.attrs, sym::compiler_builtins);
423 .first_attr_value_str_by_name(&tcx.hir().krate().item.attrs, sym::windows_subsystem);
424 let windows_subsystem = subsystem.map(|subsystem| {
425 if subsystem != sym::windows && subsystem != sym::console {
426 tcx.sess.fatal(&format!(
427 "invalid windows subsystem `{}`, only \
428 `windows` and `console` are allowed",
432 subsystem.to_string()
435 let linker_info = LinkerInfo::new(tcx);
436 let crate_info = CrateInfo::new(tcx);
439 ModuleConfig::new(ModuleKind::Regular, sess, no_builtins, is_compiler_builtins);
440 let metadata_config =
441 ModuleConfig::new(ModuleKind::Metadata, sess, no_builtins, is_compiler_builtins);
442 let allocator_config =
443 ModuleConfig::new(ModuleKind::Allocator, sess, no_builtins, is_compiler_builtins);
445 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
446 let (codegen_worker_send, codegen_worker_receive) = channel();
448 let coordinator_thread = start_executing_work(
456 sess.jobserver.clone(),
457 Arc::new(regular_config),
458 Arc::new(metadata_config),
459 Arc::new(allocator_config),
460 coordinator_send.clone(),
473 codegen_worker_receive,
475 future: coordinator_thread,
476 output_filenames: tcx.output_filenames(LOCAL_CRATE),
480 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
482 compiled_modules: &CompiledModules,
483 ) -> FxHashMap<WorkProductId, WorkProduct> {
484 let mut work_products = FxHashMap::default();
486 if sess.opts.incremental.is_none() {
487 return work_products;
490 let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
492 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
493 let path = module.object.as_ref().cloned();
495 if let Some((id, product)) =
496 copy_cgu_workproduct_to_incr_comp_cache_dir(sess, &module.name, &path)
498 work_products.insert(id, product);
505 fn produce_final_output_artifacts(
507 compiled_modules: &CompiledModules,
508 crate_output: &OutputFilenames,
510 let mut user_wants_bitcode = false;
511 let mut user_wants_objects = false;
513 // Produce final compile outputs.
514 let copy_gracefully = |from: &Path, to: &Path| {
515 if let Err(e) = fs::copy(from, to) {
516 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
520 let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
521 if compiled_modules.modules.len() == 1 {
522 // 1) Only one codegen unit. In this case it's no difficulty
523 // to copy `foo.0.x` to `foo.x`.
524 let module_name = Some(&compiled_modules.modules[0].name[..]);
525 let path = crate_output.temp_path(output_type, module_name);
526 copy_gracefully(&path, &crate_output.path(output_type));
527 if !sess.opts.cg.save_temps && !keep_numbered {
528 // The user just wants `foo.x`, not `foo.#module-name#.x`.
532 let ext = crate_output
533 .temp_path(output_type, None)
540 if crate_output.outputs.contains_key(&output_type) {
541 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
542 // no good solution for this case, so warn the user.
544 "ignoring emit path because multiple .{} files \
548 } else if crate_output.single_output_file.is_some() {
549 // 3) Multiple codegen units, with `-o some_name`. We have
550 // no good solution for this case, so warn the user.
552 "ignoring -o because multiple .{} files \
557 // 4) Multiple codegen units, but no explicit name. We
558 // just leave the `foo.0.x` files in place.
559 // (We don't have to do any work in this case.)
564 // Flag to indicate whether the user explicitly requested bitcode.
565 // Otherwise, we produced it only as a temporary output, and will need
567 for output_type in crate_output.outputs.keys() {
569 OutputType::Bitcode => {
570 user_wants_bitcode = true;
571 // Copy to .bc, but always keep the .0.bc. There is a later
572 // check to figure out if we should delete .0.bc files, or keep
573 // them for making an rlib.
574 copy_if_one_unit(OutputType::Bitcode, true);
576 OutputType::LlvmAssembly => {
577 copy_if_one_unit(OutputType::LlvmAssembly, false);
579 OutputType::Assembly => {
580 copy_if_one_unit(OutputType::Assembly, false);
582 OutputType::Object => {
583 user_wants_objects = true;
584 copy_if_one_unit(OutputType::Object, true);
586 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
590 // Clean up unwanted temporary files.
592 // We create the following files by default:
593 // - #crate#.#module-name#.bc
594 // - #crate#.#module-name#.o
595 // - #crate#.crate.metadata.bc
596 // - #crate#.crate.metadata.o
597 // - #crate#.o (linked from crate.##.o)
598 // - #crate#.bc (copied from crate.##.bc)
599 // We may create additional files if requested by the user (through
600 // `-C save-temps` or `--emit=` flags).
602 if !sess.opts.cg.save_temps {
603 // Remove the temporary .#module-name#.o objects. If the user didn't
604 // explicitly request bitcode (with --emit=bc), and the bitcode is not
605 // needed for building an rlib, then we must remove .#module-name#.bc as
608 // Specific rules for keeping .#module-name#.bc:
609 // - If the user requested bitcode (`user_wants_bitcode`), and
610 // codegen_units > 1, then keep it.
611 // - If the user requested bitcode but codegen_units == 1, then we
612 // can toss .#module-name#.bc because we copied it to .bc earlier.
613 // - If we're not building an rlib and the user didn't request
614 // bitcode, then delete .#module-name#.bc.
615 // If you change how this works, also update back::link::link_rlib,
616 // where .#module-name#.bc files are (maybe) deleted after making an
618 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
620 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
622 let keep_numbered_objects =
623 needs_crate_object || (user_wants_objects && sess.codegen_units() > 1);
625 for module in compiled_modules.modules.iter() {
626 if let Some(ref path) = module.object {
627 if !keep_numbered_objects {
632 if let Some(ref path) = module.bytecode {
633 if !keep_numbered_bitcode {
639 if !user_wants_bitcode {
640 if let Some(ref metadata_module) = compiled_modules.metadata_module {
641 if let Some(ref path) = metadata_module.bytecode {
646 if let Some(ref allocator_module) = compiled_modules.allocator_module {
647 if let Some(ref path) = allocator_module.bytecode {
654 // We leave the following files around by default:
656 // - #crate#.crate.metadata.o
658 // These are used in linking steps and will be cleaned up afterward.
661 pub fn dump_incremental_data(_codegen_results: &CodegenResults) {
662 // FIXME(mw): This does not work at the moment because the situation has
663 // become more complicated due to incremental LTO. Now a CGU
664 // can have more than two caching states.
665 // println!("[incremental] Re-using {} out of {} modules",
666 // codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
667 // codegen_results.modules.len());
670 pub enum WorkItem<B: WriteBackendMethods> {
671 /// Optimize a newly codegened, totally unoptimized module.
672 Optimize(ModuleCodegen<B::Module>),
673 /// Copy the post-LTO artifacts from the incremental cache to the output
675 CopyPostLtoArtifacts(CachedModuleCodegen),
676 /// Performs (Thin)LTO on the given module.
677 LTO(lto::LtoModuleCodegen<B>),
680 impl<B: WriteBackendMethods> WorkItem<B> {
681 pub fn module_kind(&self) -> ModuleKind {
683 WorkItem::Optimize(ref m) => m.kind,
684 WorkItem::CopyPostLtoArtifacts(_) | WorkItem::LTO(_) => ModuleKind::Regular,
688 fn start_profiling<'a>(&self, cgcx: &'a CodegenContext<B>) -> TimingGuard<'a> {
690 WorkItem::Optimize(ref m) => {
691 cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &m.name[..])
693 WorkItem::CopyPostLtoArtifacts(ref m) => cgcx
695 .generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &m.name[..]),
696 WorkItem::LTO(ref m) => {
697 cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name())
703 enum WorkItemResult<B: WriteBackendMethods> {
704 Compiled(CompiledModule),
705 NeedsFatLTO(FatLTOInput<B>),
706 NeedsThinLTO(String, B::ThinBuffer),
709 pub enum FatLTOInput<B: WriteBackendMethods> {
710 Serialized { name: String, buffer: B::ModuleBuffer },
711 InMemory(ModuleCodegen<B::Module>),
714 fn execute_work_item<B: ExtraBackendMethods>(
715 cgcx: &CodegenContext<B>,
716 work_item: WorkItem<B>,
717 ) -> Result<WorkItemResult<B>, FatalError> {
718 let module_config = cgcx.config(work_item.module_kind());
721 WorkItem::Optimize(module) => execute_optimize_work_item(cgcx, module, module_config),
722 WorkItem::CopyPostLtoArtifacts(module) => {
723 execute_copy_from_cache_work_item(cgcx, module, module_config)
725 WorkItem::LTO(module) => execute_lto_work_item(cgcx, module, module_config),
729 // Actual LTO type we end up choosing based on multiple factors.
730 pub enum ComputedLtoType {
736 pub fn compute_per_cgu_lto_type(
738 opts: &config::Options,
739 sess_crate_types: &[CrateType],
740 module_kind: ModuleKind,
741 ) -> ComputedLtoType {
742 // Metadata modules never participate in LTO regardless of the lto
744 if module_kind == ModuleKind::Metadata {
745 return ComputedLtoType::No;
748 // If the linker does LTO, we don't have to do it. Note that we
749 // keep doing full LTO, if it is requested, as not to break the
750 // assumption that the output will be a single module.
751 let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
753 // When we're automatically doing ThinLTO for multi-codegen-unit
754 // builds we don't actually want to LTO the allocator modules if
755 // it shows up. This is due to various linker shenanigans that
756 // we'll encounter later.
757 let is_allocator = module_kind == ModuleKind::Allocator;
759 // We ignore a request for full crate grath LTO if the cate type
760 // is only an rlib, as there is no full crate graph to process,
761 // that'll happen later.
763 // This use case currently comes up primarily for targets that
764 // require LTO so the request for LTO is always unconditionally
765 // passed down to the backend, but we don't actually want to do
766 // anything about it yet until we've got a final product.
767 let is_rlib = sess_crate_types.len() == 1 && sess_crate_types[0] == CrateType::Rlib;
770 Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
771 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
772 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
773 _ => ComputedLtoType::No,
777 fn execute_optimize_work_item<B: ExtraBackendMethods>(
778 cgcx: &CodegenContext<B>,
779 module: ModuleCodegen<B::Module>,
780 module_config: &ModuleConfig,
781 ) -> Result<WorkItemResult<B>, FatalError> {
782 let diag_handler = cgcx.create_diag_handler();
785 B::optimize(cgcx, &diag_handler, &module, module_config)?;
788 // After we've done the initial round of optimizations we need to
789 // decide whether to synchronously codegen this module or ship it
790 // back to the coordinator thread for further LTO processing (which
791 // has to wait for all the initial modules to be optimized).
793 let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
795 // If we're doing some form of incremental LTO then we need to be sure to
796 // save our module to disk first.
797 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
798 let filename = pre_lto_bitcode_filename(&module.name);
799 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
805 ComputedLtoType::No => {
806 let module = unsafe { B::codegen(cgcx, &diag_handler, module, module_config)? };
807 WorkItemResult::Compiled(module)
809 ComputedLtoType::Thin => {
810 let (name, thin_buffer) = B::prepare_thin(module);
811 if let Some(path) = bitcode {
812 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
813 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
816 WorkItemResult::NeedsThinLTO(name, thin_buffer)
818 ComputedLtoType::Fat => match bitcode {
820 let (name, buffer) = B::serialize_module(module);
821 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
822 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
824 WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer })
826 None => WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module)),
831 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
832 cgcx: &CodegenContext<B>,
833 module: CachedModuleCodegen,
834 module_config: &ModuleConfig,
835 ) -> Result<WorkItemResult<B>, FatalError> {
836 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
837 let mut object = None;
838 if let Some(saved_file) = module.source.saved_file {
839 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, Some(&module.name));
840 object = Some(obj_out.clone());
841 let source_file = in_incr_comp_dir(&incr_comp_session_dir, &saved_file);
843 "copying pre-existing module `{}` from {:?} to {}",
848 if let Err(err) = link_or_copy(&source_file, &obj_out) {
849 let diag_handler = cgcx.create_diag_handler();
850 diag_handler.err(&format!(
851 "unable to copy {} to {}: {}",
852 source_file.display(),
859 assert_eq!(object.is_some(), module_config.emit_obj != EmitObj::None);
861 Ok(WorkItemResult::Compiled(CompiledModule {
863 kind: ModuleKind::Regular,
869 fn execute_lto_work_item<B: ExtraBackendMethods>(
870 cgcx: &CodegenContext<B>,
871 mut module: lto::LtoModuleCodegen<B>,
872 module_config: &ModuleConfig,
873 ) -> Result<WorkItemResult<B>, FatalError> {
874 let diag_handler = cgcx.create_diag_handler();
877 let module = module.optimize(cgcx)?;
878 let module = B::codegen(cgcx, &diag_handler, module, module_config)?;
879 Ok(WorkItemResult::Compiled(module))
883 pub enum Message<B: WriteBackendMethods> {
884 Token(io::Result<Acquired>),
886 result: FatLTOInput<B>,
891 thin_buffer: B::ThinBuffer,
895 result: Result<CompiledModule, Option<WorkerFatalError>>,
899 llvm_work_item: WorkItem<B>,
902 AddImportOnlyModule {
903 module_data: SerializedModule<B::ModuleBuffer>,
904 work_product: WorkProduct,
913 code: Option<DiagnosticId>,
917 #[derive(PartialEq, Clone, Copy, Debug)]
918 enum MainThreadWorkerState {
924 fn start_executing_work<B: ExtraBackendMethods>(
927 crate_info: &CrateInfo,
928 shared_emitter: SharedEmitter,
929 codegen_worker_send: Sender<Message<B>>,
930 coordinator_receive: Receiver<Box<dyn Any + Send>>,
933 regular_config: Arc<ModuleConfig>,
934 metadata_config: Arc<ModuleConfig>,
935 allocator_config: Arc<ModuleConfig>,
936 tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
937 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
938 let coordinator_send = tx_to_llvm_workers;
941 // Compute the set of symbols we need to retain when doing LTO (if we need to)
942 let exported_symbols = {
943 let mut exported_symbols = FxHashMap::default();
945 let copy_symbols = |cnum| {
947 .exported_symbols(cnum)
949 .map(|&(s, lvl)| (symbol_name_for_instance_in_crate(tcx, s, cnum), lvl))
957 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
958 Some(Arc::new(exported_symbols))
960 Lto::Fat | Lto::Thin => {
961 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
962 for &cnum in tcx.crates().iter() {
963 exported_symbols.insert(cnum, copy_symbols(cnum));
965 Some(Arc::new(exported_symbols))
970 // First up, convert our jobserver into a helper thread so we can use normal
971 // mpsc channels to manage our messages and such.
972 // After we've requested tokens then we'll, when we can,
973 // get tokens on `coordinator_receive` which will
974 // get managed in the main loop below.
975 let coordinator_send2 = coordinator_send.clone();
976 let helper = jobserver
977 .into_helper_thread(move |token| {
978 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
980 .expect("failed to spawn helper thread");
982 let mut each_linked_rlib_for_lto = Vec::new();
983 drop(link::each_linked_rlib(crate_info, &mut |cnum, path| {
984 if link::ignored_for_lto(sess, crate_info, cnum) {
987 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
990 let ol = if tcx.sess.opts.debugging_opts.no_codegen
991 || !tcx.sess.opts.output_types.should_codegen()
993 // If we know that we won’t be doing codegen, create target machines without optimisation.
996 tcx.backend_optimization_level(LOCAL_CRATE)
998 let cgcx = CodegenContext::<B> {
999 backend: backend.clone(),
1000 crate_types: sess.crate_types().to_vec(),
1001 each_linked_rlib_for_lto,
1003 no_landing_pads: sess.panic_strategy() == PanicStrategy::Abort,
1004 fewer_names: sess.fewer_names(),
1005 save_temps: sess.opts.cg.save_temps,
1006 opts: Arc::new(sess.opts.clone()),
1007 prof: sess.prof.clone(),
1009 remark: sess.opts.cg.remark.clone(),
1011 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1012 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1014 diag_emitter: shared_emitter.clone(),
1015 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1016 regular_module_config: regular_config,
1017 metadata_module_config: metadata_config,
1018 allocator_module_config: allocator_config,
1019 tm_factory: TargetMachineFactory(backend.target_machine_factory(tcx.sess, ol)),
1021 msvc_imps_needed: msvc_imps_needed(tcx),
1022 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1023 target_arch: tcx.sess.target.target.arch.clone(),
1024 debuginfo: tcx.sess.opts.debuginfo,
1027 // This is the "main loop" of parallel work happening for parallel codegen.
1028 // It's here that we manage parallelism, schedule work, and work with
1029 // messages coming from clients.
1031 // There are a few environmental pre-conditions that shape how the system
1034 // - Error reporting only can happen on the main thread because that's the
1035 // only place where we have access to the compiler `Session`.
1036 // - LLVM work can be done on any thread.
1037 // - Codegen can only happen on the main thread.
1038 // - Each thread doing substantial work most be in possession of a `Token`
1039 // from the `Jobserver`.
1040 // - The compiler process always holds one `Token`. Any additional `Tokens`
1041 // have to be requested from the `Jobserver`.
1045 // The error reporting restriction is handled separately from the rest: We
1046 // set up a `SharedEmitter` the holds an open channel to the main thread.
1047 // When an error occurs on any thread, the shared emitter will send the
1048 // error message to the receiver main thread (`SharedEmitterMain`). The
1049 // main thread will periodically query this error message queue and emit
1050 // any error messages it has received. It might even abort compilation if
1051 // has received a fatal error. In this case we rely on all other threads
1052 // being torn down automatically with the main thread.
1053 // Since the main thread will often be busy doing codegen work, error
1054 // reporting will be somewhat delayed, since the message queue can only be
1055 // checked in between to work packages.
1057 // Work Processing Infrastructure
1058 // ==============================
1059 // The work processing infrastructure knows three major actors:
1061 // - the coordinator thread,
1062 // - the main thread, and
1063 // - LLVM worker threads
1065 // The coordinator thread is running a message loop. It instructs the main
1066 // thread about what work to do when, and it will spawn off LLVM worker
1067 // threads as open LLVM WorkItems become available.
1069 // The job of the main thread is to codegen CGUs into LLVM work package
1070 // (since the main thread is the only thread that can do this). The main
1071 // thread will block until it receives a message from the coordinator, upon
1072 // which it will codegen one CGU, send it to the coordinator and block
1073 // again. This way the coordinator can control what the main thread is
1076 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1077 // available, it will spawn off a new LLVM worker thread and let it process
1078 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1079 // it will just shut down, which also frees all resources associated with
1080 // the given LLVM module, and sends a message to the coordinator that the
1081 // has been completed.
1085 // The scheduler's goal is to minimize the time it takes to complete all
1086 // work there is, however, we also want to keep memory consumption low
1087 // if possible. These two goals are at odds with each other: If memory
1088 // consumption were not an issue, we could just let the main thread produce
1089 // LLVM WorkItems at full speed, assuring maximal utilization of
1090 // Tokens/LLVM worker threads. However, since codegen usual is faster
1091 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1092 // WorkItem potentially holds on to a substantial amount of memory.
1094 // So the actual goal is to always produce just enough LLVM WorkItems as
1095 // not to starve our LLVM worker threads. That means, once we have enough
1096 // WorkItems in our queue, we can block the main thread, so it does not
1097 // produce more until we need them.
1099 // Doing LLVM Work on the Main Thread
1100 // ----------------------------------
1101 // Since the main thread owns the compiler processes implicit `Token`, it is
1102 // wasteful to keep it blocked without doing any work. Therefore, what we do
1103 // in this case is: We spawn off an additional LLVM worker thread that helps
1104 // reduce the queue. The work it is doing corresponds to the implicit
1105 // `Token`. The coordinator will mark the main thread as being busy with
1106 // LLVM work. (The actual work happens on another OS thread but we just care
1107 // about `Tokens`, not actual threads).
1109 // When any LLVM worker thread finishes while the main thread is marked as
1110 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1111 // of the just finished thread to the LLVM worker thread that is working on
1112 // behalf of the main thread's implicit Token, thus freeing up the main
1113 // thread again. The coordinator can then again decide what the main thread
1114 // should do. This allows the coordinator to make decisions at more points
1117 // Striking a Balance between Throughput and Memory Consumption
1118 // ------------------------------------------------------------
1119 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1120 // memory consumption as low as possible, are in conflict with each other,
1121 // we have to find a trade off between them. Right now, the goal is to keep
1122 // all workers busy, which means that no worker should find the queue empty
1123 // when it is ready to start.
1124 // How do we do achieve this? Good question :) We actually never know how
1125 // many `Tokens` are potentially available so it's hard to say how much to
1126 // fill up the queue before switching the main thread to LLVM work. Also we
1127 // currently don't have a means to estimate how long a running LLVM worker
1128 // will still be busy with it's current WorkItem. However, we know the
1129 // maximal count of available Tokens that makes sense (=the number of CPU
1130 // cores), so we can take a conservative guess. The heuristic we use here
1131 // is implemented in the `queue_full_enough()` function.
1133 // Some Background on Jobservers
1134 // -----------------------------
1135 // It's worth also touching on the management of parallelism here. We don't
1136 // want to just spawn a thread per work item because while that's optimal
1137 // parallelism it may overload a system with too many threads or violate our
1138 // configuration for the maximum amount of cpu to use for this process. To
1139 // manage this we use the `jobserver` crate.
1141 // Job servers are an artifact of GNU make and are used to manage
1142 // parallelism between processes. A jobserver is a glorified IPC semaphore
1143 // basically. Whenever we want to run some work we acquire the semaphore,
1144 // and whenever we're done with that work we release the semaphore. In this
1145 // manner we can ensure that the maximum number of parallel workers is
1146 // capped at any one point in time.
1148 // LTO and the coordinator thread
1149 // ------------------------------
1151 // The final job the coordinator thread is responsible for is managing LTO
1152 // and how that works. When LTO is requested what we'll to is collect all
1153 // optimized LLVM modules into a local vector on the coordinator. Once all
1154 // modules have been codegened and optimized we hand this to the `lto`
1155 // module for further optimization. The `lto` module will return back a list
1156 // of more modules to work on, which the coordinator will continue to spawn
1159 // Each LLVM module is automatically sent back to the coordinator for LTO if
1160 // necessary. There's already optimizations in place to avoid sending work
1161 // back to the coordinator if LTO isn't requested.
1162 return thread::spawn(move || {
1163 let max_workers = ::num_cpus::get();
1164 let mut worker_id_counter = 0;
1165 let mut free_worker_ids = Vec::new();
1166 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1167 if let Some(id) = free_worker_ids.pop() {
1170 let id = worker_id_counter;
1171 worker_id_counter += 1;
1176 // This is where we collect codegen units that have gone all the way
1177 // through codegen and LLVM.
1178 let mut compiled_modules = vec![];
1179 let mut compiled_metadata_module = None;
1180 let mut compiled_allocator_module = None;
1181 let mut needs_fat_lto = Vec::new();
1182 let mut needs_thin_lto = Vec::new();
1183 let mut lto_import_only_modules = Vec::new();
1184 let mut started_lto = false;
1185 let mut codegen_aborted = false;
1187 // This flag tracks whether all items have gone through codegens
1188 let mut codegen_done = false;
1190 // This is the queue of LLVM work items that still need processing.
1191 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1193 // This are the Jobserver Tokens we currently hold. Does not include
1194 // the implicit Token the compiler process owns no matter what.
1195 let mut tokens = Vec::new();
1197 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1198 let mut running = 0;
1200 let prof = &cgcx.prof;
1201 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1203 // Run the message loop while there's still anything that needs message
1204 // processing. Note that as soon as codegen is aborted we simply want to
1205 // wait for all existing work to finish, so many of the conditions here
1206 // only apply if codegen hasn't been aborted as they represent pending
1210 || (!codegen_aborted
1211 && !(work_items.is_empty()
1212 && needs_fat_lto.is_empty()
1213 && needs_thin_lto.is_empty()
1214 && lto_import_only_modules.is_empty()
1215 && main_thread_worker_state == MainThreadWorkerState::Idle))
1217 // While there are still CGUs to be codegened, the coordinator has
1218 // to decide how to utilize the compiler processes implicit Token:
1219 // For codegenning more CGU or for running them through LLVM.
1221 if main_thread_worker_state == MainThreadWorkerState::Idle {
1222 if !queue_full_enough(work_items.len(), running, max_workers) {
1223 // The queue is not full enough, codegen more items:
1224 if codegen_worker_send.send(Message::CodegenItem).is_err() {
1225 panic!("Could not send Message::CodegenItem to main thread")
1227 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1229 // The queue is full enough to not let the worker
1230 // threads starve. Use the implicit Token to do some
1233 work_items.pop().expect("queue empty - queue_full_enough() broken?");
1234 let cgcx = CodegenContext {
1235 worker: get_worker_id(&mut free_worker_ids),
1238 maybe_start_llvm_timer(
1240 cgcx.config(item.module_kind()),
1241 &mut llvm_start_time,
1243 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1244 spawn_work(cgcx, item);
1247 } else if codegen_aborted {
1248 // don't queue up any more work if codegen was aborted, we're
1249 // just waiting for our existing children to finish
1251 // If we've finished everything related to normal codegen
1252 // then it must be the case that we've got some LTO work to do.
1253 // Perform the serial work here of figuring out what we're
1254 // going to LTO and then push a bunch of work items onto our
1256 if work_items.is_empty()
1258 && main_thread_worker_state == MainThreadWorkerState::Idle
1260 assert!(!started_lto);
1263 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1264 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1265 let import_only_modules = mem::take(&mut lto_import_only_modules);
1268 generate_lto_work(&cgcx, needs_fat_lto, needs_thin_lto, import_only_modules)
1270 let insertion_index = work_items
1271 .binary_search_by_key(&cost, |&(_, cost)| cost)
1272 .unwrap_or_else(|e| e);
1273 work_items.insert(insertion_index, (work, cost));
1274 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1275 helper.request_token();
1280 // In this branch, we know that everything has been codegened,
1281 // so it's just a matter of determining whether the implicit
1282 // Token is free to use for LLVM work.
1283 match main_thread_worker_state {
1284 MainThreadWorkerState::Idle => {
1285 if let Some((item, _)) = work_items.pop() {
1286 let cgcx = CodegenContext {
1287 worker: get_worker_id(&mut free_worker_ids),
1290 maybe_start_llvm_timer(
1292 cgcx.config(item.module_kind()),
1293 &mut llvm_start_time,
1295 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1296 spawn_work(cgcx, item);
1298 // There is no unstarted work, so let the main thread
1299 // take over for a running worker. Otherwise the
1300 // implicit token would just go to waste.
1301 // We reduce the `running` counter by one. The
1302 // `tokens.truncate()` below will take care of
1303 // giving the Token back.
1304 debug_assert!(running > 0);
1306 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1309 MainThreadWorkerState::Codegenning => bug!(
1310 "codegen worker should not be codegenning after \
1311 codegen was already completed"
1313 MainThreadWorkerState::LLVMing => {
1314 // Already making good use of that token
1319 // Spin up what work we can, only doing this while we've got available
1320 // parallelism slots and work left to spawn.
1321 while !codegen_aborted && !work_items.is_empty() && running < tokens.len() {
1322 let (item, _) = work_items.pop().unwrap();
1324 maybe_start_llvm_timer(prof, cgcx.config(item.module_kind()), &mut llvm_start_time);
1327 CodegenContext { worker: get_worker_id(&mut free_worker_ids), ..cgcx.clone() };
1329 spawn_work(cgcx, item);
1333 // Relinquish accidentally acquired extra tokens
1334 tokens.truncate(running);
1336 // If a thread exits successfully then we drop a token associated
1337 // with that worker and update our `running` count. We may later
1338 // re-acquire a token to continue running more work. We may also not
1339 // actually drop a token here if the worker was running with an
1340 // "ephemeral token"
1341 let mut free_worker = |worker_id| {
1342 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1343 main_thread_worker_state = MainThreadWorkerState::Idle;
1348 free_worker_ids.push(worker_id);
1351 let msg = coordinator_receive.recv().unwrap();
1352 match *msg.downcast::<Message<B>>().ok().unwrap() {
1353 // Save the token locally and the next turn of the loop will use
1354 // this to spawn a new unit of work, or it may get dropped
1355 // immediately if we have no more work to spawn.
1356 Message::Token(token) => {
1361 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1362 // If the main thread token is used for LLVM work
1363 // at the moment, we turn that thread into a regular
1364 // LLVM worker thread, so the main thread is free
1365 // to react to codegen demand.
1366 main_thread_worker_state = MainThreadWorkerState::Idle;
1371 let msg = &format!("failed to acquire jobserver token: {}", e);
1372 shared_emitter.fatal(msg);
1373 // Exit the coordinator thread
1379 Message::CodegenDone { llvm_work_item, cost } => {
1380 // We keep the queue sorted by estimated processing cost,
1381 // so that more expensive items are processed earlier. This
1382 // is good for throughput as it gives the main thread more
1383 // time to fill up the queue and it avoids scheduling
1384 // expensive items to the end.
1385 // Note, however, that this is not ideal for memory
1386 // consumption, as LLVM module sizes are not evenly
1388 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1389 let insertion_index = match insertion_index {
1390 Ok(idx) | Err(idx) => idx,
1392 work_items.insert(insertion_index, (llvm_work_item, cost));
1394 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1395 helper.request_token();
1397 assert!(!codegen_aborted);
1398 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1399 main_thread_worker_state = MainThreadWorkerState::Idle;
1402 Message::CodegenComplete => {
1403 codegen_done = true;
1404 assert!(!codegen_aborted);
1405 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1406 main_thread_worker_state = MainThreadWorkerState::Idle;
1409 // If codegen is aborted that means translation was aborted due
1410 // to some normal-ish compiler error. In this situation we want
1411 // to exit as soon as possible, but we want to make sure all
1412 // existing work has finished. Flag codegen as being done, and
1413 // then conditions above will ensure no more work is spawned but
1414 // we'll keep executing this loop until `running` hits 0.
1415 Message::CodegenAborted => {
1416 assert!(!codegen_aborted);
1417 codegen_done = true;
1418 codegen_aborted = true;
1419 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1421 Message::Done { result: Ok(compiled_module), worker_id } => {
1422 free_worker(worker_id);
1423 match compiled_module.kind {
1424 ModuleKind::Regular => {
1425 compiled_modules.push(compiled_module);
1427 ModuleKind::Metadata => {
1428 assert!(compiled_metadata_module.is_none());
1429 compiled_metadata_module = Some(compiled_module);
1431 ModuleKind::Allocator => {
1432 assert!(compiled_allocator_module.is_none());
1433 compiled_allocator_module = Some(compiled_module);
1437 Message::NeedsFatLTO { result, worker_id } => {
1438 assert!(!started_lto);
1439 free_worker(worker_id);
1440 needs_fat_lto.push(result);
1442 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1443 assert!(!started_lto);
1444 free_worker(worker_id);
1445 needs_thin_lto.push((name, thin_buffer));
1447 Message::AddImportOnlyModule { module_data, work_product } => {
1448 assert!(!started_lto);
1449 assert!(!codegen_done);
1450 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1451 lto_import_only_modules.push((module_data, work_product));
1452 main_thread_worker_state = MainThreadWorkerState::Idle;
1454 // If the thread failed that means it panicked, so we abort immediately.
1455 Message::Done { result: Err(None), worker_id: _ } => {
1456 bug!("worker thread panicked");
1458 Message::Done { result: Err(Some(WorkerFatalError)), worker_id: _ } => {
1461 Message::CodegenItem => bug!("the coordinator should not receive codegen requests"),
1465 // Drop to print timings
1466 drop(llvm_start_time);
1468 // Regardless of what order these modules completed in, report them to
1469 // the backend in the same order every time to ensure that we're handing
1470 // out deterministic results.
1471 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1473 Ok(CompiledModules {
1474 modules: compiled_modules,
1475 metadata_module: compiled_metadata_module,
1476 allocator_module: compiled_allocator_module,
1480 // A heuristic that determines if we have enough LLVM WorkItems in the
1481 // queue so that the main thread can do LLVM work instead of codegen
1482 fn queue_full_enough(
1483 items_in_queue: usize,
1484 workers_running: usize,
1488 items_in_queue > 0 && items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1491 fn maybe_start_llvm_timer<'a>(
1492 prof: &'a SelfProfilerRef,
1493 config: &ModuleConfig,
1494 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1496 if config.time_module && llvm_start_time.is_none() {
1497 *llvm_start_time = Some(prof.extra_verbose_generic_activity("LLVM_passes", "crate"));
1502 pub const CODEGEN_WORKER_ID: usize = usize::MAX;
1504 /// `FatalError` is explicitly not `Send`.
1506 pub struct WorkerFatalError;
1508 fn spawn_work<B: ExtraBackendMethods>(cgcx: CodegenContext<B>, work: WorkItem<B>) {
1509 thread::spawn(move || {
1510 // Set up a destructor which will fire off a message that we're done as
1512 struct Bomb<B: ExtraBackendMethods> {
1513 coordinator_send: Sender<Box<dyn Any + Send>>,
1514 result: Option<Result<WorkItemResult<B>, FatalError>>,
1517 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1518 fn drop(&mut self) {
1519 let worker_id = self.worker_id;
1520 let msg = match self.result.take() {
1521 Some(Ok(WorkItemResult::Compiled(m))) => {
1522 Message::Done::<B> { result: Ok(m), worker_id }
1524 Some(Ok(WorkItemResult::NeedsFatLTO(m))) => {
1525 Message::NeedsFatLTO::<B> { result: m, worker_id }
1527 Some(Ok(WorkItemResult::NeedsThinLTO(name, thin_buffer))) => {
1528 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1530 Some(Err(FatalError)) => {
1531 Message::Done::<B> { result: Err(Some(WorkerFatalError)), worker_id }
1533 None => Message::Done::<B> { result: Err(None), worker_id },
1535 drop(self.coordinator_send.send(Box::new(msg)));
1539 let mut bomb = Bomb::<B> {
1540 coordinator_send: cgcx.coordinator_send.clone(),
1542 worker_id: cgcx.worker,
1545 // Execute the work itself, and if it finishes successfully then flag
1546 // ourselves as a success as well.
1548 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1549 // as a diagnostic was already sent off to the main thread - just
1550 // surface that there was an error in this worker.
1552 let _prof_timer = work.start_profiling(&cgcx);
1553 Some(execute_work_item(&cgcx, work))
1558 enum SharedEmitterMessage {
1559 Diagnostic(Diagnostic),
1560 InlineAsmError(u32, String, Level, Option<(String, Vec<InnerSpan>)>),
1566 pub struct SharedEmitter {
1567 sender: Sender<SharedEmitterMessage>,
1570 pub struct SharedEmitterMain {
1571 receiver: Receiver<SharedEmitterMessage>,
1574 impl SharedEmitter {
1575 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1576 let (sender, receiver) = channel();
1578 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1581 pub fn inline_asm_error(
1586 source: Option<(String, Vec<InnerSpan>)>,
1588 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)));
1591 pub fn fatal(&self, msg: &str) {
1592 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1596 impl Emitter for SharedEmitter {
1597 fn emit_diagnostic(&mut self, diag: &rustc_errors::Diagnostic) {
1598 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1599 msg: diag.message(),
1600 code: diag.code.clone(),
1603 for child in &diag.children {
1604 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1605 msg: child.message(),
1610 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1612 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
1617 impl SharedEmitterMain {
1618 pub fn check(&self, sess: &Session, blocking: bool) {
1620 let message = if blocking {
1621 match self.receiver.recv() {
1622 Ok(message) => Ok(message),
1626 match self.receiver.try_recv() {
1627 Ok(message) => Ok(message),
1633 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1634 let handler = sess.diagnostic();
1635 let mut d = rustc_errors::Diagnostic::new(diag.lvl, &diag.msg);
1636 if let Some(code) = diag.code {
1639 handler.emit_diagnostic(&d);
1641 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => {
1642 let msg = msg.strip_prefix("error: ").unwrap_or(&msg);
1644 let mut err = match level {
1645 Level::Error => sess.struct_err(&msg),
1646 Level::Warning => sess.struct_warn(&msg),
1647 Level::Note => sess.struct_note_without_error(&msg),
1648 _ => bug!("Invalid inline asm diagnostic level"),
1651 // If the cookie is 0 then we don't have span information.
1653 let pos = BytePos::from_u32(cookie);
1654 let span = Span::with_root_ctxt(pos, pos);
1658 // Point to the generated assembly if it is available.
1659 if let Some((buffer, spans)) = source {
1662 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
1663 let source_span = Span::with_root_ctxt(source.start_pos, source.end_pos);
1665 spans.iter().map(|sp| source_span.from_inner(*sp)).collect();
1666 err.span_note(spans, "instantiated into assembly here");
1671 Ok(SharedEmitterMessage::AbortIfErrors) => {
1672 sess.abort_if_errors();
1674 Ok(SharedEmitterMessage::Fatal(msg)) => {
1685 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1687 pub crate_name: Symbol,
1688 pub crate_hash: Svh,
1689 pub metadata: EncodedMetadata,
1690 pub windows_subsystem: Option<String>,
1691 pub linker_info: LinkerInfo,
1692 pub crate_info: CrateInfo,
1693 pub coordinator_send: Sender<Box<dyn Any + Send>>,
1694 pub codegen_worker_receive: Receiver<Message<B>>,
1695 pub shared_emitter_main: SharedEmitterMain,
1696 pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1697 pub output_filenames: Arc<OutputFilenames>,
1700 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1701 pub fn join(self, sess: &Session) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1702 let _timer = sess.timer("finish_ongoing_codegen");
1704 self.shared_emitter_main.check(sess, true);
1705 let future = self.future;
1706 let compiled_modules = sess.time("join_worker_thread", || match future.join() {
1707 Ok(Ok(compiled_modules)) => compiled_modules,
1709 sess.abort_if_errors();
1710 panic!("expected abort due to worker thread errors")
1713 bug!("panic during codegen/LLVM phase");
1717 sess.cgu_reuse_tracker.check_expected_reuse(sess.diagnostic());
1719 sess.abort_if_errors();
1722 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
1723 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
1725 // FIXME: time_llvm_passes support - does this use a global context or
1727 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1728 self.backend.print_pass_timings()
1733 crate_name: self.crate_name,
1734 crate_hash: self.crate_hash,
1735 metadata: self.metadata,
1736 windows_subsystem: self.windows_subsystem,
1737 linker_info: self.linker_info,
1738 crate_info: self.crate_info,
1740 modules: compiled_modules.modules,
1741 allocator_module: compiled_modules.allocator_module,
1742 metadata_module: compiled_modules.metadata_module,
1748 pub fn submit_pre_codegened_module_to_llvm(
1751 module: ModuleCodegen<B::Module>,
1753 self.wait_for_signal_to_codegen_item();
1754 self.check_for_errors(tcx.sess);
1756 // These are generally cheap and won't throw off scheduling.
1758 submit_codegened_module_to_llvm(&self.backend, &self.coordinator_send, module, cost);
1761 pub fn codegen_finished(&self, tcx: TyCtxt<'_>) {
1762 self.wait_for_signal_to_codegen_item();
1763 self.check_for_errors(tcx.sess);
1764 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1767 /// Consumes this context indicating that codegen was entirely aborted, and
1768 /// we need to exit as quickly as possible.
1770 /// This method blocks the current thread until all worker threads have
1771 /// finished, and all worker threads should have exited or be real close to
1772 /// exiting at this point.
1773 pub fn codegen_aborted(self) {
1774 // Signal to the coordinator it should spawn no more work and start
1776 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1777 drop(self.future.join());
1780 pub fn check_for_errors(&self, sess: &Session) {
1781 self.shared_emitter_main.check(sess, false);
1784 pub fn wait_for_signal_to_codegen_item(&self) {
1785 match self.codegen_worker_receive.recv() {
1786 Ok(Message::CodegenItem) => {
1789 Ok(_) => panic!("unexpected message"),
1791 // One of the LLVM threads must have panicked, fall through so
1792 // error handling can be reached.
1798 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1800 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1801 module: ModuleCodegen<B::Module>,
1804 let llvm_work_item = WorkItem::Optimize(module);
1805 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost })));
1808 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1810 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1811 module: CachedModuleCodegen,
1813 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1814 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost: 0 })));
1817 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1820 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1821 module: CachedModuleCodegen,
1823 let filename = pre_lto_bitcode_filename(&module.name);
1824 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1825 let file = fs::File::open(&bc_path)
1826 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
1829 memmap::Mmap::map(&file).unwrap_or_else(|e| {
1830 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1833 // Schedule the module to be loaded
1834 drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule::<B> {
1835 module_data: SerializedModule::FromUncompressedFile(mmap),
1836 work_product: module.source,
1840 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1841 format!("{}.{}", module_name, PRE_LTO_BC_EXT)
1844 fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
1845 // This should never be true (because it's not supported). If it is true,
1846 // something is wrong with commandline arg validation.
1848 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
1849 && tcx.sess.target.target.options.is_like_windows
1850 && tcx.sess.opts.cg.prefer_dynamic)
1853 tcx.sess.target.target.options.is_like_windows &&
1854 tcx.sess.crate_types().iter().any(|ct| *ct == CrateType::Rlib) &&
1855 // ThinLTO can't handle this workaround in all cases, so we don't
1856 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
1857 // dynamic linking when linker plugin LTO is enabled.
1858 !tcx.sess.opts.cg.linker_plugin_lto.enabled()