1 use super::command::Command;
2 use super::link::{self, get_linker, remove};
3 use super::linker::LinkerInfo;
4 use super::lto::{self, SerializedModule};
5 use super::symbol_export::ExportedSymbols;
7 CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
8 RLIB_BYTECODE_EXTENSION,
12 use jobserver::{Acquired, Client};
13 use rustc::dep_graph::{WorkProduct, WorkProductFileKind, WorkProductId};
14 use rustc::middle::cstore::EncodedMetadata;
15 use rustc::session::config::{
16 self, Lto, OutputFilenames, OutputType, Passes, Sanitizer, SwitchWithOptPath,
18 use rustc::session::Session;
19 use rustc::ty::TyCtxt;
20 use rustc_data_structures::fx::FxHashMap;
21 use rustc_data_structures::profiling::SelfProfilerRef;
22 use rustc_data_structures::profiling::VerboseTimingGuard;
23 use rustc_data_structures::svh::Svh;
24 use rustc_data_structures::sync::Lrc;
25 use rustc_errors::emitter::Emitter;
26 use rustc_errors::{DiagnosticId, FatalError, Handler, Level};
27 use rustc_fs_util::link_or_copy;
28 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
29 use rustc_incremental::{
30 copy_cgu_workproducts_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
32 use rustc_session::cgu_reuse_tracker::CguReuseTracker;
33 use rustc_span::hygiene::ExpnId;
34 use rustc_span::source_map::SourceMap;
35 use rustc_span::symbol::{sym, Symbol};
36 use rustc_target::spec::MergeFunctions;
43 use std::path::{Path, PathBuf};
45 use std::sync::mpsc::{channel, Receiver, Sender};
49 const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
51 /// Module-specific configuration for `optimize_and_codegen`.
52 pub struct ModuleConfig {
53 /// Names of additional optimization passes to run.
54 pub passes: Vec<String>,
55 /// Some(level) to optimize at a certain level, or None to run
56 /// absolutely no optimizations (used for the metadata module).
57 pub opt_level: Option<config::OptLevel>,
59 /// Some(level) to optimize binary size, or None to not affect program size.
60 pub opt_size: Option<config::OptLevel>,
62 pub pgo_gen: SwitchWithOptPath,
63 pub pgo_use: Option<PathBuf>,
65 pub sanitizer: Option<Sanitizer>,
66 pub sanitizer_recover: Vec<Sanitizer>,
67 pub sanitizer_memory_track_origins: usize,
69 // Flags indicating which outputs to produce.
70 pub emit_pre_lto_bc: bool,
71 pub emit_no_opt_bc: bool,
73 pub emit_bc_compressed: bool,
74 pub emit_lto_bc: bool,
78 // Miscellaneous flags. These are mostly copied from command-line
80 pub verify_llvm_ir: bool,
81 pub no_prepopulate_passes: bool,
82 pub no_builtins: bool,
83 pub time_module: bool,
84 pub vectorize_loop: bool,
85 pub vectorize_slp: bool,
86 pub merge_functions: bool,
87 pub inline_threshold: Option<usize>,
88 // Instead of creating an object file by doing LLVM codegen, just
89 // make the object file bitcode. Provides easy compatibility with
90 // emscripten's ecc compiler, when used as the linker.
91 pub obj_is_bitcode: bool,
92 pub no_integrated_as: bool,
93 pub embed_bitcode: bool,
94 pub embed_bitcode_marker: bool,
98 fn new(passes: Vec<String>) -> ModuleConfig {
104 pgo_gen: SwitchWithOptPath::Disabled,
108 sanitizer_recover: Default::default(),
109 sanitizer_memory_track_origins: 0,
111 emit_no_opt_bc: false,
112 emit_pre_lto_bc: false,
114 emit_bc_compressed: false,
119 obj_is_bitcode: false,
120 embed_bitcode: false,
121 embed_bitcode_marker: false,
122 no_integrated_as: false,
124 verify_llvm_ir: false,
125 no_prepopulate_passes: false,
128 vectorize_loop: false,
129 vectorize_slp: false,
130 merge_functions: false,
131 inline_threshold: None,
135 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
136 self.verify_llvm_ir = sess.verify_llvm_ir();
137 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
138 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
139 self.inline_threshold = sess.opts.cg.inline_threshold;
140 self.obj_is_bitcode =
141 sess.target.target.options.obj_is_bitcode || sess.opts.cg.linker_plugin_lto.enabled();
143 sess.target.target.options.embed_bitcode || sess.opts.debugging_opts.embed_bitcode;
145 match sess.opts.optimize {
146 config::OptLevel::No | config::OptLevel::Less => {
147 self.embed_bitcode_marker = embed_bitcode;
149 _ => self.embed_bitcode = embed_bitcode,
153 // Copy what clang does by turning on loop vectorization at O2 and
154 // slp vectorization at O3. Otherwise configure other optimization aspects
155 // of this pass manager builder.
156 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops
157 && (sess.opts.optimize == config::OptLevel::Default
158 || sess.opts.optimize == config::OptLevel::Aggressive);
161 !sess.opts.cg.no_vectorize_slp && sess.opts.optimize == config::OptLevel::Aggressive;
163 // Some targets (namely, NVPTX) interact badly with the MergeFunctions
164 // pass. This is because MergeFunctions can generate new function calls
165 // which may interfere with the target calling convention; e.g. for the
166 // NVPTX target, PTX kernels should not call other PTX kernels.
167 // MergeFunctions can also be configured to generate aliases instead,
168 // but aliases are not supported by some backends (again, NVPTX).
169 // Therefore, allow targets to opt out of the MergeFunctions pass,
170 // but otherwise keep the pass enabled (at O2 and O3) since it can be
171 // useful for reducing code size.
172 self.merge_functions = match sess
176 .unwrap_or(sess.target.target.options.merge_functions)
178 MergeFunctions::Disabled => false,
179 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
180 sess.opts.optimize == config::OptLevel::Default
181 || sess.opts.optimize == config::OptLevel::Aggressive
186 pub fn bitcode_needed(&self) -> bool {
187 self.emit_bc || self.obj_is_bitcode || self.emit_bc_compressed || self.embed_bitcode
191 /// Assembler name and command used by codegen when no_integrated_as is enabled
192 pub struct AssemblerCommand {
197 // HACK(eddyb) work around `#[derive]` producing wrong bounds for `Clone`.
198 pub struct TargetMachineFactory<B: WriteBackendMethods>(
199 pub Arc<dyn Fn() -> Result<B::TargetMachine, String> + Send + Sync>,
202 impl<B: WriteBackendMethods> Clone for TargetMachineFactory<B> {
203 fn clone(&self) -> Self {
204 TargetMachineFactory(self.0.clone())
208 /// Additional resources used by optimize_and_codegen (not module specific)
210 pub struct CodegenContext<B: WriteBackendMethods> {
211 // Resources needed when running LTO
213 pub prof: SelfProfilerRef,
215 pub no_landing_pads: bool,
216 pub save_temps: bool,
217 pub fewer_names: bool,
218 pub exported_symbols: Option<Arc<ExportedSymbols>>,
219 pub opts: Arc<config::Options>,
220 pub crate_types: Vec<config::CrateType>,
221 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
222 pub output_filenames: Arc<OutputFilenames>,
223 pub regular_module_config: Arc<ModuleConfig>,
224 pub metadata_module_config: Arc<ModuleConfig>,
225 pub allocator_module_config: Arc<ModuleConfig>,
226 pub tm_factory: TargetMachineFactory<B>,
227 pub msvc_imps_needed: bool,
228 pub target_pointer_width: String,
229 pub target_arch: String,
230 pub debuginfo: config::DebugInfo,
232 // Number of cgus excluding the allocator/metadata modules
233 pub total_cgus: usize,
234 // Handler to use for diagnostics produced during codegen.
235 pub diag_emitter: SharedEmitter,
236 // LLVM optimizations for which we want to print remarks.
238 // Worker thread number
240 // The incremental compilation session directory, or None if we are not
241 // compiling incrementally
242 pub incr_comp_session_dir: Option<PathBuf>,
243 // Used to update CGU re-use information during the thinlto phase.
244 pub cgu_reuse_tracker: CguReuseTracker,
245 // Channel back to the main control thread to send messages to
246 pub coordinator_send: Sender<Box<dyn Any + Send>>,
247 // The assembler command if no_integrated_as option is enabled, None otherwise
248 pub assembler_cmd: Option<Arc<AssemblerCommand>>,
251 impl<B: WriteBackendMethods> CodegenContext<B> {
252 pub fn create_diag_handler(&self) -> Handler {
253 Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
256 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
258 ModuleKind::Regular => &self.regular_module_config,
259 ModuleKind::Metadata => &self.metadata_module_config,
260 ModuleKind::Allocator => &self.allocator_module_config,
265 fn generate_lto_work<B: ExtraBackendMethods>(
266 cgcx: &CodegenContext<B>,
267 needs_fat_lto: Vec<FatLTOInput<B>>,
268 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
269 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
270 ) -> Vec<(WorkItem<B>, u64)> {
271 let _prof_timer = cgcx.prof.generic_activity("codegen_generate_lto_work");
273 let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
274 assert!(needs_thin_lto.is_empty());
276 B::run_fat_lto(cgcx, needs_fat_lto, import_only_modules).unwrap_or_else(|e| e.raise());
277 (vec![lto_module], vec![])
279 assert!(needs_fat_lto.is_empty());
280 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules).unwrap_or_else(|e| e.raise())
283 let result = lto_modules
286 let cost = module.cost();
287 (WorkItem::LTO(module), cost)
289 .chain(copy_jobs.into_iter().map(|wp| {
291 WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
292 name: wp.cgu_name.clone(),
303 pub struct CompiledModules {
304 pub modules: Vec<CompiledModule>,
305 pub metadata_module: Option<CompiledModule>,
306 pub allocator_module: Option<CompiledModule>,
309 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
310 sess.crate_types.borrow().contains(&config::CrateType::Rlib)
311 && sess.opts.output_types.contains_key(&OutputType::Exe)
314 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
315 if sess.opts.incremental.is_none() {
321 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
325 pub fn start_async_codegen<B: ExtraBackendMethods>(
328 metadata: EncodedMetadata,
330 ) -> OngoingCodegen<B> {
331 let (coordinator_send, coordinator_receive) = channel();
334 let crate_name = tcx.crate_name(LOCAL_CRATE);
335 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
336 let no_builtins = attr::contains_name(&tcx.hir().krate().attrs, sym::no_builtins);
338 attr::first_attr_value_str_by_name(&tcx.hir().krate().attrs, sym::windows_subsystem);
339 let windows_subsystem = subsystem.map(|subsystem| {
340 if subsystem != sym::windows && subsystem != sym::console {
341 tcx.sess.fatal(&format!(
342 "invalid windows subsystem `{}`, only \
343 `windows` and `console` are allowed",
347 subsystem.to_string()
350 let linker_info = LinkerInfo::new(tcx);
351 let crate_info = CrateInfo::new(tcx);
353 // Figure out what we actually need to build.
354 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
355 let mut metadata_config = ModuleConfig::new(vec![]);
356 let mut allocator_config = ModuleConfig::new(vec![]);
358 if sess.opts.debugging_opts.profile {
359 modules_config.passes.push("insert-gcov-profiling".to_owned())
362 modules_config.pgo_gen = sess.opts.cg.profile_generate.clone();
363 modules_config.pgo_use = sess.opts.cg.profile_use.clone();
364 modules_config.sanitizer = sess.opts.debugging_opts.sanitizer.clone();
365 modules_config.sanitizer_recover = sess.opts.debugging_opts.sanitizer_recover.clone();
366 modules_config.sanitizer_memory_track_origins =
367 sess.opts.debugging_opts.sanitizer_memory_track_origins;
368 modules_config.opt_level = Some(sess.opts.optimize);
369 modules_config.opt_size = Some(sess.opts.optimize);
371 // Save all versions of the bytecode if we're saving our temporaries.
372 if sess.opts.cg.save_temps {
373 modules_config.emit_no_opt_bc = true;
374 modules_config.emit_pre_lto_bc = true;
375 modules_config.emit_bc = true;
376 modules_config.emit_lto_bc = true;
377 metadata_config.emit_bc = true;
378 allocator_config.emit_bc = true;
381 // Emit compressed bitcode files for the crate if we're emitting an rlib.
382 // Whenever an rlib is created, the bitcode is inserted into the archive in
383 // order to allow LTO against it.
384 if need_crate_bitcode_for_rlib(sess) {
385 modules_config.emit_bc_compressed = true;
386 allocator_config.emit_bc_compressed = true;
389 modules_config.emit_pre_lto_bc = need_pre_lto_bitcode_for_incr_comp(sess);
391 modules_config.no_integrated_as =
392 tcx.sess.opts.cg.no_integrated_as || tcx.sess.target.target.options.no_integrated_as;
394 for output_type in sess.opts.output_types.keys() {
396 OutputType::Bitcode => {
397 modules_config.emit_bc = true;
399 OutputType::LlvmAssembly => {
400 modules_config.emit_ir = true;
402 OutputType::Assembly => {
403 modules_config.emit_asm = true;
404 // If we're not using the LLVM assembler, this function
405 // could be invoked specially with output_type_assembly, so
406 // in this case we still want the metadata object file.
407 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
408 metadata_config.emit_obj = true;
409 allocator_config.emit_obj = true;
412 OutputType::Object => {
413 modules_config.emit_obj = true;
415 OutputType::Metadata => {
416 metadata_config.emit_obj = true;
419 modules_config.emit_obj = true;
420 metadata_config.emit_obj = true;
421 allocator_config.emit_obj = true;
423 OutputType::Mir => {}
424 OutputType::DepInfo => {}
428 modules_config.set_flags(sess, no_builtins);
429 metadata_config.set_flags(sess, no_builtins);
430 allocator_config.set_flags(sess, no_builtins);
432 // Exclude metadata and allocator modules from time_passes output, since
433 // they throw off the "LLVM passes" measurement.
434 metadata_config.time_module = false;
435 allocator_config.time_module = false;
437 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
438 let (codegen_worker_send, codegen_worker_receive) = channel();
440 let coordinator_thread = start_executing_work(
448 sess.jobserver.clone(),
449 Arc::new(modules_config),
450 Arc::new(metadata_config),
451 Arc::new(allocator_config),
452 coordinator_send.clone(),
465 codegen_worker_receive,
467 future: coordinator_thread,
468 output_filenames: tcx.output_filenames(LOCAL_CRATE),
472 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
474 compiled_modules: &CompiledModules,
475 ) -> FxHashMap<WorkProductId, WorkProduct> {
476 let mut work_products = FxHashMap::default();
478 if sess.opts.incremental.is_none() {
479 return work_products;
482 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
483 let mut files = vec![];
485 if let Some(ref path) = module.object {
486 files.push((WorkProductFileKind::Object, path.clone()));
488 if let Some(ref path) = module.bytecode {
489 files.push((WorkProductFileKind::Bytecode, path.clone()));
491 if let Some(ref path) = module.bytecode_compressed {
492 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
495 if let Some((id, product)) =
496 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files)
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 profiling_event_id(&self) -> &'static str {
690 WorkItem::Optimize(_) => "codegen_module_optimize",
691 WorkItem::CopyPostLtoArtifacts(_) => "codegen_copy_artifacts_from_incr_cache",
692 WorkItem::LTO(_) => "codegen_module_perform_lto",
697 enum WorkItemResult<B: WriteBackendMethods> {
698 Compiled(CompiledModule),
699 NeedsFatLTO(FatLTOInput<B>),
700 NeedsThinLTO(String, B::ThinBuffer),
703 pub enum FatLTOInput<B: WriteBackendMethods> {
704 Serialized { name: String, buffer: B::ModuleBuffer },
705 InMemory(ModuleCodegen<B::Module>),
708 fn execute_work_item<B: ExtraBackendMethods>(
709 cgcx: &CodegenContext<B>,
710 work_item: WorkItem<B>,
711 ) -> Result<WorkItemResult<B>, FatalError> {
712 let module_config = cgcx.config(work_item.module_kind());
715 WorkItem::Optimize(module) => execute_optimize_work_item(cgcx, module, module_config),
716 WorkItem::CopyPostLtoArtifacts(module) => {
717 execute_copy_from_cache_work_item(cgcx, module, module_config)
719 WorkItem::LTO(module) => execute_lto_work_item(cgcx, module, module_config),
723 // Actual LTO type we end up chosing based on multiple factors.
724 enum ComputedLtoType {
730 fn execute_optimize_work_item<B: ExtraBackendMethods>(
731 cgcx: &CodegenContext<B>,
732 module: ModuleCodegen<B::Module>,
733 module_config: &ModuleConfig,
734 ) -> Result<WorkItemResult<B>, FatalError> {
735 let diag_handler = cgcx.create_diag_handler();
738 B::optimize(cgcx, &diag_handler, &module, module_config)?;
741 // After we've done the initial round of optimizations we need to
742 // decide whether to synchronously codegen this module or ship it
743 // back to the coordinator thread for further LTO processing (which
744 // has to wait for all the initial modules to be optimized).
746 // If the linker does LTO, we don't have to do it. Note that we
747 // keep doing full LTO, if it is requested, as not to break the
748 // assumption that the output will be a single module.
749 let linker_does_lto = cgcx.opts.cg.linker_plugin_lto.enabled();
751 // When we're automatically doing ThinLTO for multi-codegen-unit
752 // builds we don't actually want to LTO the allocator modules if
753 // it shows up. This is due to various linker shenanigans that
754 // we'll encounter later.
755 let is_allocator = module.kind == ModuleKind::Allocator;
757 // We ignore a request for full crate grath LTO if the cate type
758 // is only an rlib, as there is no full crate graph to process,
759 // that'll happen later.
761 // This use case currently comes up primarily for targets that
762 // require LTO so the request for LTO is always unconditionally
763 // passed down to the backend, but we don't actually want to do
764 // anything about it yet until we've got a final product.
765 let is_rlib = cgcx.crate_types.len() == 1 && cgcx.crate_types[0] == config::CrateType::Rlib;
767 // Metadata modules never participate in LTO regardless of the lto
769 let lto_type = if module.kind == ModuleKind::Metadata {
773 Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
774 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
775 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
776 _ => ComputedLtoType::No,
780 // If we're doing some form of incremental LTO then we need to be sure to
781 // save our module to disk first.
782 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
783 let filename = pre_lto_bitcode_filename(&module.name);
784 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
790 ComputedLtoType::No => {
791 let module = unsafe { B::codegen(cgcx, &diag_handler, module, module_config)? };
792 WorkItemResult::Compiled(module)
794 ComputedLtoType::Thin => {
795 let (name, thin_buffer) = B::prepare_thin(module);
796 if let Some(path) = bitcode {
797 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
798 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
801 WorkItemResult::NeedsThinLTO(name, thin_buffer)
803 ComputedLtoType::Fat => match bitcode {
805 let (name, buffer) = B::serialize_module(module);
806 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
807 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
809 WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer })
811 None => WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module)),
816 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
817 cgcx: &CodegenContext<B>,
818 module: CachedModuleCodegen,
819 module_config: &ModuleConfig,
820 ) -> Result<WorkItemResult<B>, FatalError> {
821 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
822 let mut object = None;
823 let mut bytecode = None;
824 let mut bytecode_compressed = None;
825 for (kind, saved_file) in &module.source.saved_files {
826 let obj_out = match kind {
827 WorkProductFileKind::Object => {
828 let path = cgcx.output_filenames.temp_path(OutputType::Object, Some(&module.name));
829 object = Some(path.clone());
832 WorkProductFileKind::Bytecode => {
833 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(&module.name));
834 bytecode = Some(path.clone());
837 WorkProductFileKind::BytecodeCompressed => {
840 .temp_path(OutputType::Bitcode, Some(&module.name))
841 .with_extension(RLIB_BYTECODE_EXTENSION);
842 bytecode_compressed = Some(path.clone());
846 let source_file = in_incr_comp_dir(&incr_comp_session_dir, &saved_file);
848 "copying pre-existing module `{}` from {:?} to {}",
853 if let Err(err) = link_or_copy(&source_file, &obj_out) {
854 let diag_handler = cgcx.create_diag_handler();
855 diag_handler.err(&format!(
856 "unable to copy {} to {}: {}",
857 source_file.display(),
864 assert_eq!(object.is_some(), module_config.emit_obj);
865 assert_eq!(bytecode.is_some(), module_config.emit_bc);
866 assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
868 Ok(WorkItemResult::Compiled(CompiledModule {
870 kind: ModuleKind::Regular,
877 fn execute_lto_work_item<B: ExtraBackendMethods>(
878 cgcx: &CodegenContext<B>,
879 mut module: lto::LtoModuleCodegen<B>,
880 module_config: &ModuleConfig,
881 ) -> Result<WorkItemResult<B>, FatalError> {
882 let diag_handler = cgcx.create_diag_handler();
885 let module = module.optimize(cgcx)?;
886 let module = B::codegen(cgcx, &diag_handler, module, module_config)?;
887 Ok(WorkItemResult::Compiled(module))
891 pub enum Message<B: WriteBackendMethods> {
892 Token(io::Result<Acquired>),
894 result: FatLTOInput<B>,
899 thin_buffer: B::ThinBuffer,
903 result: Result<CompiledModule, ()>,
907 llvm_work_item: WorkItem<B>,
910 AddImportOnlyModule {
911 module_data: SerializedModule<B::ModuleBuffer>,
912 work_product: WorkProduct,
921 code: Option<DiagnosticId>,
925 #[derive(PartialEq, Clone, Copy, Debug)]
926 enum MainThreadWorkerState {
932 fn start_executing_work<B: ExtraBackendMethods>(
935 crate_info: &CrateInfo,
936 shared_emitter: SharedEmitter,
937 codegen_worker_send: Sender<Message<B>>,
938 coordinator_receive: Receiver<Box<dyn Any + Send>>,
941 modules_config: Arc<ModuleConfig>,
942 metadata_config: Arc<ModuleConfig>,
943 allocator_config: Arc<ModuleConfig>,
944 tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
945 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
946 let coordinator_send = tx_to_llvm_workers;
949 // Compute the set of symbols we need to retain when doing LTO (if we need to)
950 let exported_symbols = {
951 let mut exported_symbols = FxHashMap::default();
953 let copy_symbols = |cnum| {
955 .exported_symbols(cnum)
957 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
965 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
966 Some(Arc::new(exported_symbols))
968 Lto::Fat | Lto::Thin => {
969 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
970 for &cnum in tcx.crates().iter() {
971 exported_symbols.insert(cnum, copy_symbols(cnum));
973 Some(Arc::new(exported_symbols))
978 // First up, convert our jobserver into a helper thread so we can use normal
979 // mpsc channels to manage our messages and such.
980 // After we've requested tokens then we'll, when we can,
981 // get tokens on `coordinator_receive` which will
982 // get managed in the main loop below.
983 let coordinator_send2 = coordinator_send.clone();
984 let helper = jobserver
985 .into_helper_thread(move |token| {
986 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
988 .expect("failed to spawn helper thread");
990 let mut each_linked_rlib_for_lto = Vec::new();
991 drop(link::each_linked_rlib(crate_info, &mut |cnum, path| {
992 if link::ignored_for_lto(sess, crate_info, cnum) {
995 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
998 let assembler_cmd = if modules_config.no_integrated_as {
999 // HACK: currently we use linker (gcc) as our assembler
1000 let (linker, flavor) = link::linker_and_flavor(sess);
1002 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1003 cmd.args(&sess.target.target.options.asm_args);
1004 Some(Arc::new(AssemblerCommand { name, cmd }))
1009 let ol = if tcx.sess.opts.debugging_opts.no_codegen
1010 || !tcx.sess.opts.output_types.should_codegen()
1012 // If we know that we won’t be doing codegen, create target machines without optimisation.
1013 config::OptLevel::No
1015 tcx.backend_optimization_level(LOCAL_CRATE)
1017 let cgcx = CodegenContext::<B> {
1018 backend: backend.clone(),
1019 crate_types: sess.crate_types.borrow().clone(),
1020 each_linked_rlib_for_lto,
1022 no_landing_pads: sess.no_landing_pads(),
1023 fewer_names: sess.fewer_names(),
1024 save_temps: sess.opts.cg.save_temps,
1025 opts: Arc::new(sess.opts.clone()),
1026 prof: sess.prof.clone(),
1028 remark: sess.opts.cg.remark.clone(),
1030 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1031 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1033 diag_emitter: shared_emitter.clone(),
1034 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1035 regular_module_config: modules_config,
1036 metadata_module_config: metadata_config,
1037 allocator_module_config: allocator_config,
1038 tm_factory: TargetMachineFactory(backend.target_machine_factory(tcx.sess, ol, false)),
1040 msvc_imps_needed: msvc_imps_needed(tcx),
1041 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1042 target_arch: tcx.sess.target.target.arch.clone(),
1043 debuginfo: tcx.sess.opts.debuginfo,
1047 // This is the "main loop" of parallel work happening for parallel codegen.
1048 // It's here that we manage parallelism, schedule work, and work with
1049 // messages coming from clients.
1051 // There are a few environmental pre-conditions that shape how the system
1054 // - Error reporting only can happen on the main thread because that's the
1055 // only place where we have access to the compiler `Session`.
1056 // - LLVM work can be done on any thread.
1057 // - Codegen can only happen on the main thread.
1058 // - Each thread doing substantial work most be in possession of a `Token`
1059 // from the `Jobserver`.
1060 // - The compiler process always holds one `Token`. Any additional `Tokens`
1061 // have to be requested from the `Jobserver`.
1065 // The error reporting restriction is handled separately from the rest: We
1066 // set up a `SharedEmitter` the holds an open channel to the main thread.
1067 // When an error occurs on any thread, the shared emitter will send the
1068 // error message to the receiver main thread (`SharedEmitterMain`). The
1069 // main thread will periodically query this error message queue and emit
1070 // any error messages it has received. It might even abort compilation if
1071 // has received a fatal error. In this case we rely on all other threads
1072 // being torn down automatically with the main thread.
1073 // Since the main thread will often be busy doing codegen work, error
1074 // reporting will be somewhat delayed, since the message queue can only be
1075 // checked in between to work packages.
1077 // Work Processing Infrastructure
1078 // ==============================
1079 // The work processing infrastructure knows three major actors:
1081 // - the coordinator thread,
1082 // - the main thread, and
1083 // - LLVM worker threads
1085 // The coordinator thread is running a message loop. It instructs the main
1086 // thread about what work to do when, and it will spawn off LLVM worker
1087 // threads as open LLVM WorkItems become available.
1089 // The job of the main thread is to codegen CGUs into LLVM work package
1090 // (since the main thread is the only thread that can do this). The main
1091 // thread will block until it receives a message from the coordinator, upon
1092 // which it will codegen one CGU, send it to the coordinator and block
1093 // again. This way the coordinator can control what the main thread is
1096 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1097 // available, it will spawn off a new LLVM worker thread and let it process
1098 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1099 // it will just shut down, which also frees all resources associated with
1100 // the given LLVM module, and sends a message to the coordinator that the
1101 // has been completed.
1105 // The scheduler's goal is to minimize the time it takes to complete all
1106 // work there is, however, we also want to keep memory consumption low
1107 // if possible. These two goals are at odds with each other: If memory
1108 // consumption were not an issue, we could just let the main thread produce
1109 // LLVM WorkItems at full speed, assuring maximal utilization of
1110 // Tokens/LLVM worker threads. However, since codegen usual is faster
1111 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1112 // WorkItem potentially holds on to a substantial amount of memory.
1114 // So the actual goal is to always produce just enough LLVM WorkItems as
1115 // not to starve our LLVM worker threads. That means, once we have enough
1116 // WorkItems in our queue, we can block the main thread, so it does not
1117 // produce more until we need them.
1119 // Doing LLVM Work on the Main Thread
1120 // ----------------------------------
1121 // Since the main thread owns the compiler processes implicit `Token`, it is
1122 // wasteful to keep it blocked without doing any work. Therefore, what we do
1123 // in this case is: We spawn off an additional LLVM worker thread that helps
1124 // reduce the queue. The work it is doing corresponds to the implicit
1125 // `Token`. The coordinator will mark the main thread as being busy with
1126 // LLVM work. (The actual work happens on another OS thread but we just care
1127 // about `Tokens`, not actual threads).
1129 // When any LLVM worker thread finishes while the main thread is marked as
1130 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1131 // of the just finished thread to the LLVM worker thread that is working on
1132 // behalf of the main thread's implicit Token, thus freeing up the main
1133 // thread again. The coordinator can then again decide what the main thread
1134 // should do. This allows the coordinator to make decisions at more points
1137 // Striking a Balance between Throughput and Memory Consumption
1138 // ------------------------------------------------------------
1139 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1140 // memory consumption as low as possible, are in conflict with each other,
1141 // we have to find a trade off between them. Right now, the goal is to keep
1142 // all workers busy, which means that no worker should find the queue empty
1143 // when it is ready to start.
1144 // How do we do achieve this? Good question :) We actually never know how
1145 // many `Tokens` are potentially available so it's hard to say how much to
1146 // fill up the queue before switching the main thread to LLVM work. Also we
1147 // currently don't have a means to estimate how long a running LLVM worker
1148 // will still be busy with it's current WorkItem. However, we know the
1149 // maximal count of available Tokens that makes sense (=the number of CPU
1150 // cores), so we can take a conservative guess. The heuristic we use here
1151 // is implemented in the `queue_full_enough()` function.
1153 // Some Background on Jobservers
1154 // -----------------------------
1155 // It's worth also touching on the management of parallelism here. We don't
1156 // want to just spawn a thread per work item because while that's optimal
1157 // parallelism it may overload a system with too many threads or violate our
1158 // configuration for the maximum amount of cpu to use for this process. To
1159 // manage this we use the `jobserver` crate.
1161 // Job servers are an artifact of GNU make and are used to manage
1162 // parallelism between processes. A jobserver is a glorified IPC semaphore
1163 // basically. Whenever we want to run some work we acquire the semaphore,
1164 // and whenever we're done with that work we release the semaphore. In this
1165 // manner we can ensure that the maximum number of parallel workers is
1166 // capped at any one point in time.
1168 // LTO and the coordinator thread
1169 // ------------------------------
1171 // The final job the coordinator thread is responsible for is managing LTO
1172 // and how that works. When LTO is requested what we'll to is collect all
1173 // optimized LLVM modules into a local vector on the coordinator. Once all
1174 // modules have been codegened and optimized we hand this to the `lto`
1175 // module for further optimization. The `lto` module will return back a list
1176 // of more modules to work on, which the coordinator will continue to spawn
1179 // Each LLVM module is automatically sent back to the coordinator for LTO if
1180 // necessary. There's already optimizations in place to avoid sending work
1181 // back to the coordinator if LTO isn't requested.
1182 return thread::spawn(move || {
1183 let max_workers = ::num_cpus::get();
1184 let mut worker_id_counter = 0;
1185 let mut free_worker_ids = Vec::new();
1186 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1187 if let Some(id) = free_worker_ids.pop() {
1190 let id = worker_id_counter;
1191 worker_id_counter += 1;
1196 // This is where we collect codegen units that have gone all the way
1197 // through codegen and LLVM.
1198 let mut compiled_modules = vec![];
1199 let mut compiled_metadata_module = None;
1200 let mut compiled_allocator_module = None;
1201 let mut needs_fat_lto = Vec::new();
1202 let mut needs_thin_lto = Vec::new();
1203 let mut lto_import_only_modules = Vec::new();
1204 let mut started_lto = false;
1205 let mut codegen_aborted = false;
1207 // This flag tracks whether all items have gone through codegens
1208 let mut codegen_done = false;
1210 // This is the queue of LLVM work items that still need processing.
1211 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1213 // This are the Jobserver Tokens we currently hold. Does not include
1214 // the implicit Token the compiler process owns no matter what.
1215 let mut tokens = Vec::new();
1217 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1218 let mut running = 0;
1220 let prof = &cgcx.prof;
1221 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1223 // Run the message loop while there's still anything that needs message
1224 // processing. Note that as soon as codegen is aborted we simply want to
1225 // wait for all existing work to finish, so many of the conditions here
1226 // only apply if codegen hasn't been aborted as they represent pending
1230 || (!codegen_aborted
1231 && (work_items.len() > 0
1232 || needs_fat_lto.len() > 0
1233 || needs_thin_lto.len() > 0
1234 || lto_import_only_modules.len() > 0
1235 || main_thread_worker_state != MainThreadWorkerState::Idle))
1237 // While there are still CGUs to be codegened, the coordinator has
1238 // to decide how to utilize the compiler processes implicit Token:
1239 // For codegenning more CGU or for running them through LLVM.
1241 if main_thread_worker_state == MainThreadWorkerState::Idle {
1242 if !queue_full_enough(work_items.len(), running, max_workers) {
1243 // The queue is not full enough, codegen more items:
1244 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1245 panic!("Could not send Message::CodegenItem to main thread")
1247 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1249 // The queue is full enough to not let the worker
1250 // threads starve. Use the implicit Token to do some
1253 work_items.pop().expect("queue empty - queue_full_enough() broken?");
1254 let cgcx = CodegenContext {
1255 worker: get_worker_id(&mut free_worker_ids),
1258 maybe_start_llvm_timer(
1260 cgcx.config(item.module_kind()),
1261 &mut llvm_start_time,
1263 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1264 spawn_work(cgcx, item);
1267 } else if codegen_aborted {
1268 // don't queue up any more work if codegen was aborted, we're
1269 // just waiting for our existing children to finish
1271 // If we've finished everything related to normal codegen
1272 // then it must be the case that we've got some LTO work to do.
1273 // Perform the serial work here of figuring out what we're
1274 // going to LTO and then push a bunch of work items onto our
1276 if work_items.len() == 0
1278 && main_thread_worker_state == MainThreadWorkerState::Idle
1280 assert!(!started_lto);
1283 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1284 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1285 let import_only_modules = mem::take(&mut lto_import_only_modules);
1288 generate_lto_work(&cgcx, needs_fat_lto, needs_thin_lto, import_only_modules)
1290 let insertion_index = work_items
1291 .binary_search_by_key(&cost, |&(_, cost)| cost)
1292 .unwrap_or_else(|e| e);
1293 work_items.insert(insertion_index, (work, cost));
1294 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1295 helper.request_token();
1300 // In this branch, we know that everything has been codegened,
1301 // so it's just a matter of determining whether the implicit
1302 // Token is free to use for LLVM work.
1303 match main_thread_worker_state {
1304 MainThreadWorkerState::Idle => {
1305 if let Some((item, _)) = work_items.pop() {
1306 let cgcx = CodegenContext {
1307 worker: get_worker_id(&mut free_worker_ids),
1310 maybe_start_llvm_timer(
1312 cgcx.config(item.module_kind()),
1313 &mut llvm_start_time,
1315 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1316 spawn_work(cgcx, item);
1318 // There is no unstarted work, so let the main thread
1319 // take over for a running worker. Otherwise the
1320 // implicit token would just go to waste.
1321 // We reduce the `running` counter by one. The
1322 // `tokens.truncate()` below will take care of
1323 // giving the Token back.
1324 debug_assert!(running > 0);
1326 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1329 MainThreadWorkerState::Codegenning => bug!(
1330 "codegen worker should not be codegenning after \
1331 codegen was already completed"
1333 MainThreadWorkerState::LLVMing => {
1334 // Already making good use of that token
1339 // Spin up what work we can, only doing this while we've got available
1340 // parallelism slots and work left to spawn.
1341 while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1342 let (item, _) = work_items.pop().unwrap();
1344 maybe_start_llvm_timer(prof, cgcx.config(item.module_kind()), &mut llvm_start_time);
1347 CodegenContext { worker: get_worker_id(&mut free_worker_ids), ..cgcx.clone() };
1349 spawn_work(cgcx, item);
1353 // Relinquish accidentally acquired extra tokens
1354 tokens.truncate(running);
1356 // If a thread exits successfully then we drop a token associated
1357 // with that worker and update our `running` count. We may later
1358 // re-acquire a token to continue running more work. We may also not
1359 // actually drop a token here if the worker was running with an
1360 // "ephemeral token"
1361 let mut free_worker = |worker_id| {
1362 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1363 main_thread_worker_state = MainThreadWorkerState::Idle;
1368 free_worker_ids.push(worker_id);
1371 let msg = coordinator_receive.recv().unwrap();
1372 match *msg.downcast::<Message<B>>().ok().unwrap() {
1373 // Save the token locally and the next turn of the loop will use
1374 // this to spawn a new unit of work, or it may get dropped
1375 // immediately if we have no more work to spawn.
1376 Message::Token(token) => {
1381 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1382 // If the main thread token is used for LLVM work
1383 // at the moment, we turn that thread into a regular
1384 // LLVM worker thread, so the main thread is free
1385 // to react to codegen demand.
1386 main_thread_worker_state = MainThreadWorkerState::Idle;
1391 let msg = &format!("failed to acquire jobserver token: {}", e);
1392 shared_emitter.fatal(msg);
1393 // Exit the coordinator thread
1399 Message::CodegenDone { llvm_work_item, cost } => {
1400 // We keep the queue sorted by estimated processing cost,
1401 // so that more expensive items are processed earlier. This
1402 // is good for throughput as it gives the main thread more
1403 // time to fill up the queue and it avoids scheduling
1404 // expensive items to the end.
1405 // Note, however, that this is not ideal for memory
1406 // consumption, as LLVM module sizes are not evenly
1408 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1409 let insertion_index = match insertion_index {
1410 Ok(idx) | Err(idx) => idx,
1412 work_items.insert(insertion_index, (llvm_work_item, cost));
1414 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1415 helper.request_token();
1417 assert!(!codegen_aborted);
1418 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1419 main_thread_worker_state = MainThreadWorkerState::Idle;
1422 Message::CodegenComplete => {
1423 codegen_done = true;
1424 assert!(!codegen_aborted);
1425 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1426 main_thread_worker_state = MainThreadWorkerState::Idle;
1429 // If codegen is aborted that means translation was aborted due
1430 // to some normal-ish compiler error. In this situation we want
1431 // to exit as soon as possible, but we want to make sure all
1432 // existing work has finished. Flag codegen as being done, and
1433 // then conditions above will ensure no more work is spawned but
1434 // we'll keep executing this loop until `running` hits 0.
1435 Message::CodegenAborted => {
1436 assert!(!codegen_aborted);
1437 codegen_done = true;
1438 codegen_aborted = true;
1439 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1441 Message::Done { result: Ok(compiled_module), worker_id } => {
1442 free_worker(worker_id);
1443 match compiled_module.kind {
1444 ModuleKind::Regular => {
1445 compiled_modules.push(compiled_module);
1447 ModuleKind::Metadata => {
1448 assert!(compiled_metadata_module.is_none());
1449 compiled_metadata_module = Some(compiled_module);
1451 ModuleKind::Allocator => {
1452 assert!(compiled_allocator_module.is_none());
1453 compiled_allocator_module = Some(compiled_module);
1457 Message::NeedsFatLTO { result, worker_id } => {
1458 assert!(!started_lto);
1459 free_worker(worker_id);
1460 needs_fat_lto.push(result);
1462 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1463 assert!(!started_lto);
1464 free_worker(worker_id);
1465 needs_thin_lto.push((name, thin_buffer));
1467 Message::AddImportOnlyModule { module_data, work_product } => {
1468 assert!(!started_lto);
1469 assert!(!codegen_done);
1470 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1471 lto_import_only_modules.push((module_data, work_product));
1472 main_thread_worker_state = MainThreadWorkerState::Idle;
1474 // If the thread failed that means it panicked, so we abort immediately.
1475 Message::Done { result: Err(()), worker_id: _ } => {
1476 bug!("worker thread panicked");
1478 Message::CodegenItem => bug!("the coordinator should not receive codegen requests"),
1482 // Drop to print timings
1483 drop(llvm_start_time);
1485 // Regardless of what order these modules completed in, report them to
1486 // the backend in the same order every time to ensure that we're handing
1487 // out deterministic results.
1488 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1490 Ok(CompiledModules {
1491 modules: compiled_modules,
1492 metadata_module: compiled_metadata_module,
1493 allocator_module: compiled_allocator_module,
1497 // A heuristic that determines if we have enough LLVM WorkItems in the
1498 // queue so that the main thread can do LLVM work instead of codegen
1499 fn queue_full_enough(
1500 items_in_queue: usize,
1501 workers_running: usize,
1505 items_in_queue > 0 && items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1508 fn maybe_start_llvm_timer<'a>(
1509 prof: &'a SelfProfilerRef,
1510 config: &ModuleConfig,
1511 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1513 if config.time_module && llvm_start_time.is_none() {
1514 *llvm_start_time = Some(prof.generic_pass("LLVM passes"));
1519 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1521 fn spawn_work<B: ExtraBackendMethods>(cgcx: CodegenContext<B>, work: WorkItem<B>) {
1522 thread::spawn(move || {
1523 // Set up a destructor which will fire off a message that we're done as
1525 struct Bomb<B: ExtraBackendMethods> {
1526 coordinator_send: Sender<Box<dyn Any + Send>>,
1527 result: Option<WorkItemResult<B>>,
1530 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1531 fn drop(&mut self) {
1532 let worker_id = self.worker_id;
1533 let msg = match self.result.take() {
1534 Some(WorkItemResult::Compiled(m)) => {
1535 Message::Done::<B> { result: Ok(m), worker_id }
1537 Some(WorkItemResult::NeedsFatLTO(m)) => {
1538 Message::NeedsFatLTO::<B> { result: m, worker_id }
1540 Some(WorkItemResult::NeedsThinLTO(name, thin_buffer)) => {
1541 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1543 None => Message::Done::<B> { result: Err(()), worker_id },
1545 drop(self.coordinator_send.send(Box::new(msg)));
1549 let mut bomb = Bomb::<B> {
1550 coordinator_send: cgcx.coordinator_send.clone(),
1552 worker_id: cgcx.worker,
1555 // Execute the work itself, and if it finishes successfully then flag
1556 // ourselves as a success as well.
1558 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1559 // as a diagnostic was already sent off to the main thread - just
1560 // surface that there was an error in this worker.
1562 let _prof_timer = cgcx.prof.generic_activity(work.profiling_event_id());
1563 execute_work_item(&cgcx, work).ok()
1568 pub fn run_assembler<B: ExtraBackendMethods>(
1569 cgcx: &CodegenContext<B>,
1574 let assembler = cgcx.assembler_cmd.as_ref().expect("cgcx.assembler_cmd is missing?");
1576 let pname = &assembler.name;
1577 let mut cmd = assembler.cmd.clone();
1578 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
1579 debug!("{:?}", cmd);
1581 match cmd.output() {
1583 if !prog.status.success() {
1584 let mut note = prog.stderr.clone();
1585 note.extend_from_slice(&prog.stdout);
1588 .struct_err(&format!(
1589 "linking with `{}` failed: {}",
1593 .note(&format!("{:?}", &cmd))
1594 .note(str::from_utf8(¬e[..]).unwrap())
1596 handler.abort_if_errors();
1600 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
1601 handler.abort_if_errors();
1606 enum SharedEmitterMessage {
1607 Diagnostic(Diagnostic),
1608 InlineAsmError(u32, String),
1614 pub struct SharedEmitter {
1615 sender: Sender<SharedEmitterMessage>,
1618 pub struct SharedEmitterMain {
1619 receiver: Receiver<SharedEmitterMessage>,
1622 impl SharedEmitter {
1623 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1624 let (sender, receiver) = channel();
1626 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1629 pub fn inline_asm_error(&self, cookie: u32, msg: String) {
1630 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
1633 pub fn fatal(&self, msg: &str) {
1634 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1638 impl Emitter for SharedEmitter {
1639 fn emit_diagnostic(&mut self, diag: &rustc_errors::Diagnostic) {
1640 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1641 msg: diag.message(),
1642 code: diag.code.clone(),
1645 for child in &diag.children {
1646 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1647 msg: child.message(),
1652 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1654 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
1659 impl SharedEmitterMain {
1660 pub fn check(&self, sess: &Session, blocking: bool) {
1662 let message = if blocking {
1663 match self.receiver.recv() {
1664 Ok(message) => Ok(message),
1668 match self.receiver.try_recv() {
1669 Ok(message) => Ok(message),
1675 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1676 let handler = sess.diagnostic();
1677 let mut d = rustc_errors::Diagnostic::new(diag.lvl, &diag.msg);
1678 if let Some(code) = diag.code {
1681 handler.emit_diagnostic(&d);
1682 handler.abort_if_errors_and_should_abort();
1684 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
1685 sess.span_err(ExpnId::from_u32(cookie).expn_data().call_site, &msg)
1687 Ok(SharedEmitterMessage::AbortIfErrors) => {
1688 sess.abort_if_errors();
1690 Ok(SharedEmitterMessage::Fatal(msg)) => {
1701 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1703 pub crate_name: Symbol,
1704 pub crate_hash: Svh,
1705 pub metadata: EncodedMetadata,
1706 pub windows_subsystem: Option<String>,
1707 pub linker_info: LinkerInfo,
1708 pub crate_info: CrateInfo,
1709 pub coordinator_send: Sender<Box<dyn Any + Send>>,
1710 pub codegen_worker_receive: Receiver<Message<B>>,
1711 pub shared_emitter_main: SharedEmitterMain,
1712 pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1713 pub output_filenames: Arc<OutputFilenames>,
1716 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1717 pub fn join(self, sess: &Session) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1718 self.shared_emitter_main.check(sess, true);
1719 let compiled_modules = match self.future.join() {
1720 Ok(Ok(compiled_modules)) => compiled_modules,
1722 sess.abort_if_errors();
1723 panic!("expected abort due to worker thread errors")
1726 bug!("panic during codegen/LLVM phase");
1730 sess.cgu_reuse_tracker.check_expected_reuse(sess.diagnostic());
1732 sess.abort_if_errors();
1735 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
1736 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
1738 // FIXME: time_llvm_passes support - does this use a global context or
1740 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1741 self.backend.print_pass_timings()
1746 crate_name: self.crate_name,
1747 crate_hash: self.crate_hash,
1748 metadata: self.metadata,
1749 windows_subsystem: self.windows_subsystem,
1750 linker_info: self.linker_info,
1751 crate_info: self.crate_info,
1753 modules: compiled_modules.modules,
1754 allocator_module: compiled_modules.allocator_module,
1755 metadata_module: compiled_modules.metadata_module,
1761 pub fn submit_pre_codegened_module_to_llvm(
1764 module: ModuleCodegen<B::Module>,
1766 self.wait_for_signal_to_codegen_item();
1767 self.check_for_errors(tcx.sess);
1769 // These are generally cheap and won't throw off scheduling.
1771 submit_codegened_module_to_llvm(&self.backend, &self.coordinator_send, module, cost);
1774 pub fn codegen_finished(&self, tcx: TyCtxt<'_>) {
1775 self.wait_for_signal_to_codegen_item();
1776 self.check_for_errors(tcx.sess);
1777 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1780 /// Consumes this context indicating that codegen was entirely aborted, and
1781 /// we need to exit as quickly as possible.
1783 /// This method blocks the current thread until all worker threads have
1784 /// finished, and all worker threads should have exited or be real close to
1785 /// exiting at this point.
1786 pub fn codegen_aborted(self) {
1787 // Signal to the coordinator it should spawn no more work and start
1789 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1790 drop(self.future.join());
1793 pub fn check_for_errors(&self, sess: &Session) {
1794 self.shared_emitter_main.check(sess, false);
1797 pub fn wait_for_signal_to_codegen_item(&self) {
1798 match self.codegen_worker_receive.recv() {
1799 Ok(Message::CodegenItem) => {
1802 Ok(_) => panic!("unexpected message"),
1804 // One of the LLVM threads must have panicked, fall through so
1805 // error handling can be reached.
1811 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1813 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1814 module: ModuleCodegen<B::Module>,
1817 let llvm_work_item = WorkItem::Optimize(module);
1818 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost })));
1821 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1823 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1824 module: CachedModuleCodegen,
1826 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1827 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost: 0 })));
1830 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1833 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1834 module: CachedModuleCodegen,
1836 let filename = pre_lto_bitcode_filename(&module.name);
1837 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1838 let file = fs::File::open(&bc_path)
1839 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
1842 memmap::Mmap::map(&file).unwrap_or_else(|e| {
1843 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1846 // Schedule the module to be loaded
1847 drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule::<B> {
1848 module_data: SerializedModule::FromUncompressedFile(mmap),
1849 work_product: module.source,
1853 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1854 format!("{}.{}", module_name, PRE_LTO_BC_EXT)
1857 fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
1858 // This should never be true (because it's not supported). If it is true,
1859 // something is wrong with commandline arg validation.
1861 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
1862 && tcx.sess.target.target.options.is_like_msvc
1863 && tcx.sess.opts.cg.prefer_dynamic)
1866 tcx.sess.target.target.options.is_like_msvc &&
1867 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
1868 // ThinLTO can't handle this workaround in all cases, so we don't
1869 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
1870 // dynamic linking when linker plugin LTO is enabled.
1871 !tcx.sess.opts.cg.linker_plugin_lto.enabled()