1 use crate::{ModuleCodegen, ModuleKind, CachedModuleCodegen, CompiledModule, CrateInfo,
2 CodegenResults, RLIB_BYTECODE_EXTENSION};
3 use super::linker::LinkerInfo;
4 use super::lto::{self, SerializedModule};
5 use super::link::{self, remove, get_linker};
6 use super::command::Command;
7 use super::symbol_export::ExportedSymbols;
10 use rustc_incremental::{copy_cgu_workproducts_to_incr_comp_cache_dir,
11 in_incr_comp_dir, in_incr_comp_dir_sess};
12 use rustc::dep_graph::{WorkProduct, WorkProductId, WorkProductFileKind};
13 use rustc::dep_graph::cgu_reuse_tracker::CguReuseTracker;
14 use rustc::middle::cstore::EncodedMetadata;
15 use rustc::session::config::{self, OutputFilenames, OutputType, Passes, Lto,
16 Sanitizer, SwitchWithOptPath};
17 use rustc::session::Session;
18 use rustc::util::nodemap::FxHashMap;
19 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
20 use rustc::ty::TyCtxt;
21 use rustc::util::common::{time_depth, set_time_depth, print_time_passes_entry};
22 use rustc::util::profiling::SelfProfilerRef;
23 use rustc_fs_util::link_or_copy;
24 use rustc_data_structures::svh::Svh;
25 use rustc_data_structures::sync::Lrc;
26 use rustc_errors::{Handler, Level, FatalError, DiagnosticId, SourceMapperDyn};
27 use rustc_errors::emitter::{Emitter};
28 use rustc_target::spec::MergeFunctions;
30 use syntax_expand::hygiene::ExpnId;
31 use syntax_pos::symbol::{Symbol, sym};
32 use jobserver::{Client, Acquired};
38 use std::path::{Path, PathBuf};
41 use std::sync::mpsc::{channel, Sender, Receiver};
42 use std::time::Instant;
45 const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
47 /// Module-specific configuration for `optimize_and_codegen`.
48 pub struct ModuleConfig {
49 /// Names of additional optimization passes to run.
50 pub passes: Vec<String>,
51 /// Some(level) to optimize at a certain level, or None to run
52 /// absolutely no optimizations (used for the metadata module).
53 pub opt_level: Option<config::OptLevel>,
55 /// Some(level) to optimize binary size, or None to not affect program size.
56 pub opt_size: Option<config::OptLevel>,
58 pub pgo_gen: SwitchWithOptPath,
59 pub pgo_use: Option<PathBuf>,
61 // Flags indicating which outputs to produce.
62 pub emit_pre_lto_bc: bool,
63 pub emit_no_opt_bc: bool,
65 pub emit_bc_compressed: bool,
66 pub emit_lto_bc: bool,
70 // Miscellaneous flags. These are mostly copied from command-line
72 pub verify_llvm_ir: bool,
73 pub no_prepopulate_passes: bool,
74 pub no_builtins: bool,
75 pub time_passes: bool,
76 pub vectorize_loop: bool,
77 pub vectorize_slp: bool,
78 pub merge_functions: bool,
79 pub inline_threshold: Option<usize>,
80 // Instead of creating an object file by doing LLVM codegen, just
81 // make the object file bitcode. Provides easy compatibility with
82 // emscripten's ecc compiler, when used as the linker.
83 pub obj_is_bitcode: bool,
84 pub no_integrated_as: bool,
85 pub embed_bitcode: bool,
86 pub embed_bitcode_marker: bool,
90 fn new(passes: Vec<String>) -> ModuleConfig {
96 pgo_gen: SwitchWithOptPath::Disabled,
99 emit_no_opt_bc: false,
100 emit_pre_lto_bc: false,
102 emit_bc_compressed: false,
107 obj_is_bitcode: false,
108 embed_bitcode: false,
109 embed_bitcode_marker: false,
110 no_integrated_as: false,
112 verify_llvm_ir: false,
113 no_prepopulate_passes: false,
116 vectorize_loop: false,
117 vectorize_slp: false,
118 merge_functions: false,
119 inline_threshold: None
123 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
124 self.verify_llvm_ir = sess.verify_llvm_ir();
125 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
126 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
127 self.time_passes = sess.time_extended();
128 self.inline_threshold = sess.opts.cg.inline_threshold;
129 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
130 sess.opts.cg.linker_plugin_lto.enabled();
131 let embed_bitcode = sess.target.target.options.embed_bitcode ||
132 sess.opts.debugging_opts.embed_bitcode;
134 match sess.opts.optimize {
135 config::OptLevel::No |
136 config::OptLevel::Less => {
137 self.embed_bitcode_marker = embed_bitcode;
139 _ => self.embed_bitcode = embed_bitcode,
143 // Copy what clang does by turning on loop vectorization at O2 and
144 // slp vectorization at O3. Otherwise configure other optimization aspects
145 // of this pass manager builder.
146 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
147 (sess.opts.optimize == config::OptLevel::Default ||
148 sess.opts.optimize == config::OptLevel::Aggressive);
150 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
151 sess.opts.optimize == config::OptLevel::Aggressive;
153 // Some targets (namely, NVPTX) interact badly with the MergeFunctions
154 // pass. This is because MergeFunctions can generate new function calls
155 // which may interfere with the target calling convention; e.g. for the
156 // NVPTX target, PTX kernels should not call other PTX kernels.
157 // MergeFunctions can also be configured to generate aliases instead,
158 // but aliases are not supported by some backends (again, NVPTX).
159 // Therefore, allow targets to opt out of the MergeFunctions pass,
160 // but otherwise keep the pass enabled (at O2 and O3) since it can be
161 // useful for reducing code size.
162 self.merge_functions = match sess.opts.debugging_opts.merge_functions
163 .unwrap_or(sess.target.target.options.merge_functions) {
164 MergeFunctions::Disabled => false,
165 MergeFunctions::Trampolines |
166 MergeFunctions::Aliases => {
167 sess.opts.optimize == config::OptLevel::Default ||
168 sess.opts.optimize == config::OptLevel::Aggressive
173 pub fn bitcode_needed(&self) -> bool {
174 self.emit_bc || self.obj_is_bitcode
175 || self.emit_bc_compressed || self.embed_bitcode
179 /// Assembler name and command used by codegen when no_integrated_as is enabled
180 pub struct AssemblerCommand {
185 // HACK(eddyb) work around `#[derive]` producing wrong bounds for `Clone`.
186 pub struct TargetMachineFactory<B: WriteBackendMethods>(
187 pub Arc<dyn Fn() -> Result<B::TargetMachine, String> + Send + Sync>,
190 impl<B: WriteBackendMethods> Clone for TargetMachineFactory<B> {
191 fn clone(&self) -> Self {
192 TargetMachineFactory(self.0.clone())
196 /// Additional resources used by optimize_and_codegen (not module specific)
198 pub struct CodegenContext<B: WriteBackendMethods> {
199 // Resources needed when running LTO
201 pub time_passes: bool,
202 pub prof: SelfProfilerRef,
204 pub no_landing_pads: bool,
205 pub save_temps: bool,
206 pub fewer_names: bool,
207 pub exported_symbols: Option<Arc<ExportedSymbols>>,
208 pub opts: Arc<config::Options>,
209 pub crate_types: Vec<config::CrateType>,
210 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
211 pub output_filenames: Arc<OutputFilenames>,
212 pub regular_module_config: Arc<ModuleConfig>,
213 pub metadata_module_config: Arc<ModuleConfig>,
214 pub allocator_module_config: Arc<ModuleConfig>,
215 pub tm_factory: TargetMachineFactory<B>,
216 pub msvc_imps_needed: bool,
217 pub target_pointer_width: String,
218 pub target_arch: String,
219 pub debuginfo: config::DebugInfo,
221 // Number of cgus excluding the allocator/metadata modules
222 pub total_cgus: usize,
223 // Handler to use for diagnostics produced during codegen.
224 pub diag_emitter: SharedEmitter,
225 // LLVM passes added by plugins.
226 pub plugin_passes: Vec<String>,
227 // LLVM optimizations for which we want to print remarks.
229 // Worker thread number
231 // The incremental compilation session directory, or None if we are not
232 // compiling incrementally
233 pub incr_comp_session_dir: Option<PathBuf>,
234 // Used to update CGU re-use information during the thinlto phase.
235 pub cgu_reuse_tracker: CguReuseTracker,
236 // Channel back to the main control thread to send messages to
237 pub coordinator_send: Sender<Box<dyn Any + Send>>,
238 // The assembler command if no_integrated_as option is enabled, None otherwise
239 pub assembler_cmd: Option<Arc<AssemblerCommand>>
242 impl<B: WriteBackendMethods> CodegenContext<B> {
243 pub fn create_diag_handler(&self) -> Handler {
244 Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
247 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
249 ModuleKind::Regular => &self.regular_module_config,
250 ModuleKind::Metadata => &self.metadata_module_config,
251 ModuleKind::Allocator => &self.allocator_module_config,
256 fn generate_lto_work<B: ExtraBackendMethods>(
257 cgcx: &CodegenContext<B>,
258 needs_fat_lto: Vec<FatLTOInput<B>>,
259 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
260 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>
261 ) -> Vec<(WorkItem<B>, u64)> {
262 let _prof_timer = cgcx.prof.generic_activity("codegen_run_lto");
264 let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
265 assert!(needs_thin_lto.is_empty());
266 let lto_module = B::run_fat_lto(
271 .unwrap_or_else(|e| e.raise());
272 (vec![lto_module], vec![])
274 assert!(needs_fat_lto.is_empty());
275 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules)
276 .unwrap_or_else(|e| e.raise())
279 let result = lto_modules.into_iter().map(|module| {
280 let cost = module.cost();
281 (WorkItem::LTO(module), cost)
282 }).chain(copy_jobs.into_iter().map(|wp| {
283 (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
284 name: wp.cgu_name.clone(),
292 pub struct CompiledModules {
293 pub modules: Vec<CompiledModule>,
294 pub metadata_module: Option<CompiledModule>,
295 pub allocator_module: Option<CompiledModule>,
298 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
299 sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
300 sess.opts.output_types.contains_key(&OutputType::Exe)
303 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
304 if sess.opts.incremental.is_none() {
312 Lto::ThinLocal => true,
316 pub fn start_async_codegen<B: ExtraBackendMethods>(
319 metadata: EncodedMetadata,
321 ) -> OngoingCodegen<B> {
322 let (coordinator_send, coordinator_receive) = channel();
325 let crate_name = tcx.crate_name(LOCAL_CRATE);
326 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
327 let no_builtins = attr::contains_name(&tcx.hir().krate().attrs, sym::no_builtins);
328 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir().krate().attrs,
329 sym::windows_subsystem);
330 let windows_subsystem = subsystem.map(|subsystem| {
331 if subsystem != sym::windows && subsystem != sym::console {
332 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
333 `windows` and `console` are allowed",
336 subsystem.to_string()
339 let linker_info = LinkerInfo::new(tcx);
340 let crate_info = CrateInfo::new(tcx);
342 // Figure out what we actually need to build.
343 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
344 let mut metadata_config = ModuleConfig::new(vec![]);
345 let mut allocator_config = ModuleConfig::new(vec![]);
347 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
349 Sanitizer::Address => {
350 modules_config.passes.push("asan".to_owned());
351 modules_config.passes.push("asan-module".to_owned());
353 Sanitizer::Memory => {
354 modules_config.passes.push("msan".to_owned())
356 Sanitizer::Thread => {
357 modules_config.passes.push("tsan".to_owned())
363 if sess.opts.debugging_opts.profile {
364 modules_config.passes.push("insert-gcov-profiling".to_owned())
367 modules_config.pgo_gen = sess.opts.cg.profile_generate.clone();
368 modules_config.pgo_use = sess.opts.cg.profile_use.clone();
370 modules_config.opt_level = Some(sess.opts.optimize);
371 modules_config.opt_size = Some(sess.opts.optimize);
373 // Save all versions of the bytecode if we're saving our temporaries.
374 if sess.opts.cg.save_temps {
375 modules_config.emit_no_opt_bc = true;
376 modules_config.emit_pre_lto_bc = true;
377 modules_config.emit_bc = true;
378 modules_config.emit_lto_bc = true;
379 metadata_config.emit_bc = true;
380 allocator_config.emit_bc = true;
383 // Emit compressed bitcode files for the crate if we're emitting an rlib.
384 // Whenever an rlib is created, the bitcode is inserted into the archive in
385 // order to allow LTO against it.
386 if need_crate_bitcode_for_rlib(sess) {
387 modules_config.emit_bc_compressed = true;
388 allocator_config.emit_bc_compressed = true;
391 modules_config.emit_pre_lto_bc =
392 need_pre_lto_bitcode_for_incr_comp(sess);
394 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
395 tcx.sess.target.target.options.no_integrated_as;
397 for output_type in sess.opts.output_types.keys() {
399 OutputType::Bitcode => { modules_config.emit_bc = true; }
400 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
401 OutputType::Assembly => {
402 modules_config.emit_asm = true;
403 // If we're not using the LLVM assembler, this function
404 // could be invoked specially with output_type_assembly, so
405 // in this case we still want the metadata object file.
406 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
407 metadata_config.emit_obj = true;
408 allocator_config.emit_obj = true;
411 OutputType::Object => { modules_config.emit_obj = true; }
412 OutputType::Metadata => { metadata_config.emit_obj = true; }
414 modules_config.emit_obj = true;
415 metadata_config.emit_obj = true;
416 allocator_config.emit_obj = true;
418 OutputType::Mir => {}
419 OutputType::DepInfo => {}
423 modules_config.set_flags(sess, no_builtins);
424 metadata_config.set_flags(sess, no_builtins);
425 allocator_config.set_flags(sess, no_builtins);
427 // Exclude metadata and allocator modules from time_passes output, since
428 // they throw off the "LLVM passes" measurement.
429 metadata_config.time_passes = false;
430 allocator_config.time_passes = false;
432 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
433 let (codegen_worker_send, codegen_worker_receive) = channel();
435 let coordinator_thread = start_executing_work(backend.clone(),
442 sess.jobserver.clone(),
443 Arc::new(modules_config),
444 Arc::new(metadata_config),
445 Arc::new(allocator_config),
446 coordinator_send.clone());
458 codegen_worker_receive,
460 future: coordinator_thread,
461 output_filenames: tcx.output_filenames(LOCAL_CRATE),
465 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
467 compiled_modules: &CompiledModules,
468 ) -> FxHashMap<WorkProductId, WorkProduct> {
469 let mut work_products = FxHashMap::default();
471 if sess.opts.incremental.is_none() {
472 return work_products;
475 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
476 let mut files = vec![];
478 if let Some(ref path) = module.object {
479 files.push((WorkProductFileKind::Object, path.clone()));
481 if let Some(ref path) = module.bytecode {
482 files.push((WorkProductFileKind::Bytecode, path.clone()));
484 if let Some(ref path) = module.bytecode_compressed {
485 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
488 if let Some((id, product)) =
489 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
490 work_products.insert(id, product);
497 fn produce_final_output_artifacts(sess: &Session,
498 compiled_modules: &CompiledModules,
499 crate_output: &OutputFilenames) {
500 let mut user_wants_bitcode = false;
501 let mut user_wants_objects = false;
503 // Produce final compile outputs.
504 let copy_gracefully = |from: &Path, to: &Path| {
505 if let Err(e) = fs::copy(from, to) {
506 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
510 let copy_if_one_unit = |output_type: OutputType,
511 keep_numbered: bool| {
512 if compiled_modules.modules.len() == 1 {
513 // 1) Only one codegen unit. In this case it's no difficulty
514 // to copy `foo.0.x` to `foo.x`.
515 let module_name = Some(&compiled_modules.modules[0].name[..]);
516 let path = crate_output.temp_path(output_type, module_name);
517 copy_gracefully(&path,
518 &crate_output.path(output_type));
519 if !sess.opts.cg.save_temps && !keep_numbered {
520 // The user just wants `foo.x`, not `foo.#module-name#.x`.
524 let ext = crate_output.temp_path(output_type, None)
531 if crate_output.outputs.contains_key(&output_type) {
532 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
533 // no good solution for this case, so warn the user.
534 sess.warn(&format!("ignoring emit path because multiple .{} files \
535 were produced", ext));
536 } else if crate_output.single_output_file.is_some() {
537 // 3) Multiple codegen units, with `-o some_name`. We have
538 // no good solution for this case, so warn the user.
539 sess.warn(&format!("ignoring -o because multiple .{} files \
540 were produced", ext));
542 // 4) Multiple codegen units, but no explicit name. We
543 // just leave the `foo.0.x` files in place.
544 // (We don't have to do any work in this case.)
549 // Flag to indicate whether the user explicitly requested bitcode.
550 // Otherwise, we produced it only as a temporary output, and will need
552 for output_type in crate_output.outputs.keys() {
554 OutputType::Bitcode => {
555 user_wants_bitcode = true;
556 // Copy to .bc, but always keep the .0.bc. There is a later
557 // check to figure out if we should delete .0.bc files, or keep
558 // them for making an rlib.
559 copy_if_one_unit(OutputType::Bitcode, true);
561 OutputType::LlvmAssembly => {
562 copy_if_one_unit(OutputType::LlvmAssembly, false);
564 OutputType::Assembly => {
565 copy_if_one_unit(OutputType::Assembly, false);
567 OutputType::Object => {
568 user_wants_objects = true;
569 copy_if_one_unit(OutputType::Object, true);
572 OutputType::Metadata |
574 OutputType::DepInfo => {}
578 // Clean up unwanted temporary files.
580 // We create the following files by default:
581 // - #crate#.#module-name#.bc
582 // - #crate#.#module-name#.o
583 // - #crate#.crate.metadata.bc
584 // - #crate#.crate.metadata.o
585 // - #crate#.o (linked from crate.##.o)
586 // - #crate#.bc (copied from crate.##.bc)
587 // We may create additional files if requested by the user (through
588 // `-C save-temps` or `--emit=` flags).
590 if !sess.opts.cg.save_temps {
591 // Remove the temporary .#module-name#.o objects. If the user didn't
592 // explicitly request bitcode (with --emit=bc), and the bitcode is not
593 // needed for building an rlib, then we must remove .#module-name#.bc as
596 // Specific rules for keeping .#module-name#.bc:
597 // - If the user requested bitcode (`user_wants_bitcode`), and
598 // codegen_units > 1, then keep it.
599 // - If the user requested bitcode but codegen_units == 1, then we
600 // can toss .#module-name#.bc because we copied it to .bc earlier.
601 // - If we're not building an rlib and the user didn't request
602 // bitcode, then delete .#module-name#.bc.
603 // If you change how this works, also update back::link::link_rlib,
604 // where .#module-name#.bc files are (maybe) deleted after making an
606 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
608 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
610 let keep_numbered_objects = needs_crate_object ||
611 (user_wants_objects && sess.codegen_units() > 1);
613 for module in compiled_modules.modules.iter() {
614 if let Some(ref path) = module.object {
615 if !keep_numbered_objects {
620 if let Some(ref path) = module.bytecode {
621 if !keep_numbered_bitcode {
627 if !user_wants_bitcode {
628 if let Some(ref metadata_module) = compiled_modules.metadata_module {
629 if let Some(ref path) = metadata_module.bytecode {
634 if let Some(ref allocator_module) = compiled_modules.allocator_module {
635 if let Some(ref path) = allocator_module.bytecode {
642 // We leave the following files around by default:
644 // - #crate#.crate.metadata.o
646 // These are used in linking steps and will be cleaned up afterward.
649 pub fn dump_incremental_data(_codegen_results: &CodegenResults) {
650 // FIXME(mw): This does not work at the moment because the situation has
651 // become more complicated due to incremental LTO. Now a CGU
652 // can have more than two caching states.
653 // println!("[incremental] Re-using {} out of {} modules",
654 // codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
655 // codegen_results.modules.len());
658 pub enum WorkItem<B: WriteBackendMethods> {
659 /// Optimize a newly codegened, totally unoptimized module.
660 Optimize(ModuleCodegen<B::Module>),
661 /// Copy the post-LTO artifacts from the incremental cache to the output
663 CopyPostLtoArtifacts(CachedModuleCodegen),
664 /// Performs (Thin)LTO on the given module.
665 LTO(lto::LtoModuleCodegen<B>),
668 impl<B: WriteBackendMethods> WorkItem<B> {
669 pub fn module_kind(&self) -> ModuleKind {
671 WorkItem::Optimize(ref m) => m.kind,
672 WorkItem::CopyPostLtoArtifacts(_) |
673 WorkItem::LTO(_) => ModuleKind::Regular,
677 pub fn name(&self) -> String {
679 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
680 WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
681 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
686 enum WorkItemResult<B: WriteBackendMethods> {
687 Compiled(CompiledModule),
688 NeedsFatLTO(FatLTOInput<B>),
689 NeedsThinLTO(String, B::ThinBuffer),
692 pub enum FatLTOInput<B: WriteBackendMethods> {
695 buffer: B::ModuleBuffer,
697 InMemory(ModuleCodegen<B::Module>),
700 fn execute_work_item<B: ExtraBackendMethods>(
701 cgcx: &CodegenContext<B>,
702 work_item: WorkItem<B>,
703 ) -> Result<WorkItemResult<B>, FatalError> {
704 let module_config = cgcx.config(work_item.module_kind());
707 WorkItem::Optimize(module) => {
708 execute_optimize_work_item(cgcx, module, module_config)
710 WorkItem::CopyPostLtoArtifacts(module) => {
711 execute_copy_from_cache_work_item(cgcx, module, module_config)
713 WorkItem::LTO(module) => {
714 execute_lto_work_item(cgcx, module, module_config)
719 // Actual LTO type we end up chosing based on multiple factors.
720 enum ComputedLtoType {
726 fn execute_optimize_work_item<B: ExtraBackendMethods>(
727 cgcx: &CodegenContext<B>,
728 module: ModuleCodegen<B::Module>,
729 module_config: &ModuleConfig,
730 ) -> Result<WorkItemResult<B>, FatalError> {
731 let diag_handler = cgcx.create_diag_handler();
734 B::optimize(cgcx, &diag_handler, &module, module_config)?;
737 // After we've done the initial round of optimizations we need to
738 // decide whether to synchronously codegen this module or ship it
739 // back to the coordinator thread for further LTO processing (which
740 // has to wait for all the initial modules to be optimized).
742 // If the linker does LTO, we don't have to do it. Note that we
743 // keep doing full LTO, if it is requested, as not to break the
744 // assumption that the output will be a single module.
745 let linker_does_lto = cgcx.opts.cg.linker_plugin_lto.enabled();
747 // When we're automatically doing ThinLTO for multi-codegen-unit
748 // builds we don't actually want to LTO the allocator modules if
749 // it shows up. This is due to various linker shenanigans that
750 // we'll encounter later.
751 let is_allocator = module.kind == ModuleKind::Allocator;
753 // We ignore a request for full crate grath LTO if the cate type
754 // is only an rlib, as there is no full crate graph to process,
755 // that'll happen later.
757 // This use case currently comes up primarily for targets that
758 // require LTO so the request for LTO is always unconditionally
759 // passed down to the backend, but we don't actually want to do
760 // anything about it yet until we've got a final product.
761 let is_rlib = cgcx.crate_types.len() == 1
762 && cgcx.crate_types[0] == config::CrateType::Rlib;
764 // Metadata modules never participate in LTO regardless of the lto
766 let lto_type = if module.kind == ModuleKind::Metadata {
770 Lto::ThinLocal if !linker_does_lto && !is_allocator
771 => ComputedLtoType::Thin,
772 Lto::Thin if !linker_does_lto && !is_rlib
773 => ComputedLtoType::Thin,
774 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
775 _ => ComputedLtoType::No,
779 // If we're doing some form of incremental LTO then we need to be sure to
780 // save our module to disk first.
781 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
782 let filename = pre_lto_bitcode_filename(&module.name);
783 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
789 ComputedLtoType::No => {
790 let module = unsafe {
791 B::codegen(cgcx, &diag_handler, module, module_config)?
793 WorkItemResult::Compiled(module)
795 ComputedLtoType::Thin => {
796 let (name, thin_buffer) = B::prepare_thin(module);
797 if let Some(path) = bitcode {
798 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
799 panic!("Error writing pre-lto-bitcode file `{}`: {}",
804 WorkItemResult::NeedsThinLTO(name, thin_buffer)
806 ComputedLtoType::Fat => {
809 let (name, buffer) = B::serialize_module(module);
810 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
811 panic!("Error writing pre-lto-bitcode file `{}`: {}",
815 WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer })
817 None => WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module)),
823 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
824 cgcx: &CodegenContext<B>,
825 module: CachedModuleCodegen,
826 module_config: &ModuleConfig,
827 ) -> Result<WorkItemResult<B>, FatalError> {
828 let incr_comp_session_dir = cgcx.incr_comp_session_dir
831 let mut object = None;
832 let mut bytecode = None;
833 let mut bytecode_compressed = None;
834 for (kind, saved_file) in &module.source.saved_files {
835 let obj_out = match kind {
836 WorkProductFileKind::Object => {
837 let path = cgcx.output_filenames.temp_path(OutputType::Object,
839 object = Some(path.clone());
842 WorkProductFileKind::Bytecode => {
843 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
845 bytecode = Some(path.clone());
848 WorkProductFileKind::BytecodeCompressed => {
849 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
851 .with_extension(RLIB_BYTECODE_EXTENSION);
852 bytecode_compressed = Some(path.clone());
856 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
858 debug!("copying pre-existing module `{}` from {:?} to {}",
862 if let Err(err) = link_or_copy(&source_file, &obj_out) {
863 let diag_handler = cgcx.create_diag_handler();
864 diag_handler.err(&format!("unable to copy {} to {}: {}",
865 source_file.display(),
871 assert_eq!(object.is_some(), module_config.emit_obj);
872 assert_eq!(bytecode.is_some(), module_config.emit_bc);
873 assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
875 Ok(WorkItemResult::Compiled(CompiledModule {
877 kind: ModuleKind::Regular,
884 fn execute_lto_work_item<B: ExtraBackendMethods>(
885 cgcx: &CodegenContext<B>,
886 mut module: lto::LtoModuleCodegen<B>,
887 module_config: &ModuleConfig,
888 ) -> Result<WorkItemResult<B>, FatalError> {
889 let diag_handler = cgcx.create_diag_handler();
892 let module = module.optimize(cgcx)?;
893 let module = B::codegen(cgcx, &diag_handler, module, module_config)?;
894 Ok(WorkItemResult::Compiled(module))
898 pub enum Message<B: WriteBackendMethods> {
899 Token(io::Result<Acquired>),
901 result: FatLTOInput<B>,
906 thin_buffer: B::ThinBuffer,
910 result: Result<CompiledModule, ()>,
914 llvm_work_item: WorkItem<B>,
917 AddImportOnlyModule {
918 module_data: SerializedModule<B::ModuleBuffer>,
919 work_product: WorkProduct,
928 code: Option<DiagnosticId>,
932 #[derive(PartialEq, Clone, Copy, Debug)]
933 enum MainThreadWorkerState {
939 fn start_executing_work<B: ExtraBackendMethods>(
942 crate_info: &CrateInfo,
943 shared_emitter: SharedEmitter,
944 codegen_worker_send: Sender<Message<B>>,
945 coordinator_receive: Receiver<Box<dyn Any + Send>>,
948 modules_config: Arc<ModuleConfig>,
949 metadata_config: Arc<ModuleConfig>,
950 allocator_config: Arc<ModuleConfig>,
951 tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
952 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
953 let coordinator_send = tx_to_llvm_workers;
956 // Compute the set of symbols we need to retain when doing LTO (if we need to)
957 let exported_symbols = {
958 let mut exported_symbols = FxHashMap::default();
960 let copy_symbols = |cnum| {
961 let symbols = tcx.exported_symbols(cnum)
963 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
971 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
972 Some(Arc::new(exported_symbols))
974 Lto::Fat | Lto::Thin => {
975 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
976 for &cnum in tcx.crates().iter() {
977 exported_symbols.insert(cnum, copy_symbols(cnum));
979 Some(Arc::new(exported_symbols))
984 // First up, convert our jobserver into a helper thread so we can use normal
985 // mpsc channels to manage our messages and such.
986 // After we've requested tokens then we'll, when we can,
987 // get tokens on `coordinator_receive` which will
988 // get managed in the main loop below.
989 let coordinator_send2 = coordinator_send.clone();
990 let helper = jobserver.into_helper_thread(move |token| {
991 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
992 }).expect("failed to spawn helper thread");
994 let mut each_linked_rlib_for_lto = Vec::new();
995 drop(link::each_linked_rlib(crate_info, &mut |cnum, path| {
996 if link::ignored_for_lto(sess, crate_info, cnum) {
999 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1002 let assembler_cmd = if modules_config.no_integrated_as {
1003 // HACK: currently we use linker (gcc) as our assembler
1004 let (linker, flavor) = link::linker_and_flavor(sess);
1006 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1007 cmd.args(&sess.target.target.options.asm_args);
1008 Some(Arc::new(AssemblerCommand {
1016 let ol = if tcx.sess.opts.debugging_opts.no_codegen
1017 || !tcx.sess.opts.output_types.should_codegen() {
1018 // If we know that we won’t be doing codegen, create target machines without optimisation.
1019 config::OptLevel::No
1021 tcx.backend_optimization_level(LOCAL_CRATE)
1023 let cgcx = CodegenContext::<B> {
1024 backend: backend.clone(),
1025 crate_types: sess.crate_types.borrow().clone(),
1026 each_linked_rlib_for_lto,
1028 no_landing_pads: sess.no_landing_pads(),
1029 fewer_names: sess.fewer_names(),
1030 save_temps: sess.opts.cg.save_temps,
1031 opts: Arc::new(sess.opts.clone()),
1032 time_passes: sess.time_extended(),
1033 prof: sess.prof.clone(),
1035 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1036 remark: sess.opts.cg.remark.clone(),
1038 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1039 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1041 diag_emitter: shared_emitter.clone(),
1042 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1043 regular_module_config: modules_config,
1044 metadata_module_config: metadata_config,
1045 allocator_module_config: allocator_config,
1046 tm_factory: TargetMachineFactory(backend.target_machine_factory(tcx.sess, ol, false)),
1048 msvc_imps_needed: msvc_imps_needed(tcx),
1049 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1050 target_arch: tcx.sess.target.target.arch.clone(),
1051 debuginfo: tcx.sess.opts.debuginfo,
1055 // This is the "main loop" of parallel work happening for parallel codegen.
1056 // It's here that we manage parallelism, schedule work, and work with
1057 // messages coming from clients.
1059 // There are a few environmental pre-conditions that shape how the system
1062 // - Error reporting only can happen on the main thread because that's the
1063 // only place where we have access to the compiler `Session`.
1064 // - LLVM work can be done on any thread.
1065 // - Codegen can only happen on the main thread.
1066 // - Each thread doing substantial work most be in possession of a `Token`
1067 // from the `Jobserver`.
1068 // - The compiler process always holds one `Token`. Any additional `Tokens`
1069 // have to be requested from the `Jobserver`.
1073 // The error reporting restriction is handled separately from the rest: We
1074 // set up a `SharedEmitter` the holds an open channel to the main thread.
1075 // When an error occurs on any thread, the shared emitter will send the
1076 // error message to the receiver main thread (`SharedEmitterMain`). The
1077 // main thread will periodically query this error message queue and emit
1078 // any error messages it has received. It might even abort compilation if
1079 // has received a fatal error. In this case we rely on all other threads
1080 // being torn down automatically with the main thread.
1081 // Since the main thread will often be busy doing codegen work, error
1082 // reporting will be somewhat delayed, since the message queue can only be
1083 // checked in between to work packages.
1085 // Work Processing Infrastructure
1086 // ==============================
1087 // The work processing infrastructure knows three major actors:
1089 // - the coordinator thread,
1090 // - the main thread, and
1091 // - LLVM worker threads
1093 // The coordinator thread is running a message loop. It instructs the main
1094 // thread about what work to do when, and it will spawn off LLVM worker
1095 // threads as open LLVM WorkItems become available.
1097 // The job of the main thread is to codegen CGUs into LLVM work package
1098 // (since the main thread is the only thread that can do this). The main
1099 // thread will block until it receives a message from the coordinator, upon
1100 // which it will codegen one CGU, send it to the coordinator and block
1101 // again. This way the coordinator can control what the main thread is
1104 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1105 // available, it will spawn off a new LLVM worker thread and let it process
1106 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1107 // it will just shut down, which also frees all resources associated with
1108 // the given LLVM module, and sends a message to the coordinator that the
1109 // has been completed.
1113 // The scheduler's goal is to minimize the time it takes to complete all
1114 // work there is, however, we also want to keep memory consumption low
1115 // if possible. These two goals are at odds with each other: If memory
1116 // consumption were not an issue, we could just let the main thread produce
1117 // LLVM WorkItems at full speed, assuring maximal utilization of
1118 // Tokens/LLVM worker threads. However, since codegen usual is faster
1119 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1120 // WorkItem potentially holds on to a substantial amount of memory.
1122 // So the actual goal is to always produce just enough LLVM WorkItems as
1123 // not to starve our LLVM worker threads. That means, once we have enough
1124 // WorkItems in our queue, we can block the main thread, so it does not
1125 // produce more until we need them.
1127 // Doing LLVM Work on the Main Thread
1128 // ----------------------------------
1129 // Since the main thread owns the compiler processes implicit `Token`, it is
1130 // wasteful to keep it blocked without doing any work. Therefore, what we do
1131 // in this case is: We spawn off an additional LLVM worker thread that helps
1132 // reduce the queue. The work it is doing corresponds to the implicit
1133 // `Token`. The coordinator will mark the main thread as being busy with
1134 // LLVM work. (The actual work happens on another OS thread but we just care
1135 // about `Tokens`, not actual threads).
1137 // When any LLVM worker thread finishes while the main thread is marked as
1138 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1139 // of the just finished thread to the LLVM worker thread that is working on
1140 // behalf of the main thread's implicit Token, thus freeing up the main
1141 // thread again. The coordinator can then again decide what the main thread
1142 // should do. This allows the coordinator to make decisions at more points
1145 // Striking a Balance between Throughput and Memory Consumption
1146 // ------------------------------------------------------------
1147 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1148 // memory consumption as low as possible, are in conflict with each other,
1149 // we have to find a trade off between them. Right now, the goal is to keep
1150 // all workers busy, which means that no worker should find the queue empty
1151 // when it is ready to start.
1152 // How do we do achieve this? Good question :) We actually never know how
1153 // many `Tokens` are potentially available so it's hard to say how much to
1154 // fill up the queue before switching the main thread to LLVM work. Also we
1155 // currently don't have a means to estimate how long a running LLVM worker
1156 // will still be busy with it's current WorkItem. However, we know the
1157 // maximal count of available Tokens that makes sense (=the number of CPU
1158 // cores), so we can take a conservative guess. The heuristic we use here
1159 // is implemented in the `queue_full_enough()` function.
1161 // Some Background on Jobservers
1162 // -----------------------------
1163 // It's worth also touching on the management of parallelism here. We don't
1164 // want to just spawn a thread per work item because while that's optimal
1165 // parallelism it may overload a system with too many threads or violate our
1166 // configuration for the maximum amount of cpu to use for this process. To
1167 // manage this we use the `jobserver` crate.
1169 // Job servers are an artifact of GNU make and are used to manage
1170 // parallelism between processes. A jobserver is a glorified IPC semaphore
1171 // basically. Whenever we want to run some work we acquire the semaphore,
1172 // and whenever we're done with that work we release the semaphore. In this
1173 // manner we can ensure that the maximum number of parallel workers is
1174 // capped at any one point in time.
1176 // LTO and the coordinator thread
1177 // ------------------------------
1179 // The final job the coordinator thread is responsible for is managing LTO
1180 // and how that works. When LTO is requested what we'll to is collect all
1181 // optimized LLVM modules into a local vector on the coordinator. Once all
1182 // modules have been codegened and optimized we hand this to the `lto`
1183 // module for further optimization. The `lto` module will return back a list
1184 // of more modules to work on, which the coordinator will continue to spawn
1187 // Each LLVM module is automatically sent back to the coordinator for LTO if
1188 // necessary. There's already optimizations in place to avoid sending work
1189 // back to the coordinator if LTO isn't requested.
1190 return thread::spawn(move || {
1191 // We pretend to be within the top-level LLVM time-passes task here:
1194 let max_workers = ::num_cpus::get();
1195 let mut worker_id_counter = 0;
1196 let mut free_worker_ids = Vec::new();
1197 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1198 if let Some(id) = free_worker_ids.pop() {
1201 let id = worker_id_counter;
1202 worker_id_counter += 1;
1207 // This is where we collect codegen units that have gone all the way
1208 // through codegen and LLVM.
1209 let mut compiled_modules = vec![];
1210 let mut compiled_metadata_module = None;
1211 let mut compiled_allocator_module = None;
1212 let mut needs_fat_lto = Vec::new();
1213 let mut needs_thin_lto = Vec::new();
1214 let mut lto_import_only_modules = Vec::new();
1215 let mut started_lto = false;
1216 let mut codegen_aborted = false;
1218 // This flag tracks whether all items have gone through codegens
1219 let mut codegen_done = false;
1221 // This is the queue of LLVM work items that still need processing.
1222 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1224 // This are the Jobserver Tokens we currently hold. Does not include
1225 // the implicit Token the compiler process owns no matter what.
1226 let mut tokens = Vec::new();
1228 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1229 let mut running = 0;
1231 let mut llvm_start_time = None;
1233 // Run the message loop while there's still anything that needs message
1234 // processing. Note that as soon as codegen is aborted we simply want to
1235 // wait for all existing work to finish, so many of the conditions here
1236 // only apply if codegen hasn't been aborted as they represent pending
1238 while !codegen_done ||
1240 (!codegen_aborted && (
1241 work_items.len() > 0 ||
1242 needs_fat_lto.len() > 0 ||
1243 needs_thin_lto.len() > 0 ||
1244 lto_import_only_modules.len() > 0 ||
1245 main_thread_worker_state != MainThreadWorkerState::Idle
1249 // While there are still CGUs to be codegened, the coordinator has
1250 // to decide how to utilize the compiler processes implicit Token:
1251 // For codegenning more CGU or for running them through LLVM.
1253 if main_thread_worker_state == MainThreadWorkerState::Idle {
1254 if !queue_full_enough(work_items.len(), running, max_workers) {
1255 // The queue is not full enough, codegen more items:
1256 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1257 panic!("Could not send Message::CodegenItem to main thread")
1259 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1261 // The queue is full enough to not let the worker
1262 // threads starve. Use the implicit Token to do some
1264 let (item, _) = work_items.pop()
1265 .expect("queue empty - queue_full_enough() broken?");
1266 let cgcx = CodegenContext {
1267 worker: get_worker_id(&mut free_worker_ids),
1270 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1271 &mut llvm_start_time);
1272 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1273 spawn_work(cgcx, item);
1276 } else if codegen_aborted {
1277 // don't queue up any more work if codegen was aborted, we're
1278 // just waiting for our existing children to finish
1280 // If we've finished everything related to normal codegen
1281 // then it must be the case that we've got some LTO work to do.
1282 // Perform the serial work here of figuring out what we're
1283 // going to LTO and then push a bunch of work items onto our
1285 if work_items.len() == 0 &&
1287 main_thread_worker_state == MainThreadWorkerState::Idle {
1288 assert!(!started_lto);
1291 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1292 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1293 let import_only_modules = mem::take(&mut lto_import_only_modules);
1295 for (work, cost) in generate_lto_work(&cgcx, needs_fat_lto,
1296 needs_thin_lto, import_only_modules) {
1297 let insertion_index = work_items
1298 .binary_search_by_key(&cost, |&(_, cost)| cost)
1299 .unwrap_or_else(|e| e);
1300 work_items.insert(insertion_index, (work, cost));
1301 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1302 helper.request_token();
1307 // In this branch, we know that everything has been codegened,
1308 // so it's just a matter of determining whether the implicit
1309 // Token is free to use for LLVM work.
1310 match main_thread_worker_state {
1311 MainThreadWorkerState::Idle => {
1312 if let Some((item, _)) = work_items.pop() {
1313 let cgcx = CodegenContext {
1314 worker: get_worker_id(&mut free_worker_ids),
1317 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1318 &mut llvm_start_time);
1319 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1320 spawn_work(cgcx, item);
1322 // There is no unstarted work, so let the main thread
1323 // take over for a running worker. Otherwise the
1324 // implicit token would just go to waste.
1325 // We reduce the `running` counter by one. The
1326 // `tokens.truncate()` below will take care of
1327 // giving the Token back.
1328 debug_assert!(running > 0);
1330 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1333 MainThreadWorkerState::Codegenning => {
1334 bug!("codegen worker should not be codegenning after \
1335 codegen was already completed")
1337 MainThreadWorkerState::LLVMing => {
1338 // Already making good use of that token
1343 // Spin up what work we can, only doing this while we've got available
1344 // parallelism slots and work left to spawn.
1345 while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1346 let (item, _) = work_items.pop().unwrap();
1348 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1349 &mut llvm_start_time);
1351 let cgcx = CodegenContext {
1352 worker: get_worker_id(&mut free_worker_ids),
1356 spawn_work(cgcx, item);
1360 // Relinquish accidentally acquired extra tokens
1361 tokens.truncate(running);
1363 // If a thread exits successfully then we drop a token associated
1364 // with that worker and update our `running` count. We may later
1365 // re-acquire a token to continue running more work. We may also not
1366 // actually drop a token here if the worker was running with an
1367 // "ephemeral token"
1368 let mut free_worker = |worker_id| {
1369 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1370 main_thread_worker_state = MainThreadWorkerState::Idle;
1375 free_worker_ids.push(worker_id);
1378 let msg = coordinator_receive.recv().unwrap();
1379 match *msg.downcast::<Message<B>>().ok().unwrap() {
1380 // Save the token locally and the next turn of the loop will use
1381 // this to spawn a new unit of work, or it may get dropped
1382 // immediately if we have no more work to spawn.
1383 Message::Token(token) => {
1388 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1389 // If the main thread token is used for LLVM work
1390 // at the moment, we turn that thread into a regular
1391 // LLVM worker thread, so the main thread is free
1392 // to react to codegen demand.
1393 main_thread_worker_state = MainThreadWorkerState::Idle;
1398 let msg = &format!("failed to acquire jobserver token: {}", e);
1399 shared_emitter.fatal(msg);
1400 // Exit the coordinator thread
1406 Message::CodegenDone { llvm_work_item, cost } => {
1407 // We keep the queue sorted by estimated processing cost,
1408 // so that more expensive items are processed earlier. This
1409 // is good for throughput as it gives the main thread more
1410 // time to fill up the queue and it avoids scheduling
1411 // expensive items to the end.
1412 // Note, however, that this is not ideal for memory
1413 // consumption, as LLVM module sizes are not evenly
1415 let insertion_index =
1416 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1417 let insertion_index = match insertion_index {
1418 Ok(idx) | Err(idx) => idx
1420 work_items.insert(insertion_index, (llvm_work_item, cost));
1422 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1423 helper.request_token();
1425 assert!(!codegen_aborted);
1426 assert_eq!(main_thread_worker_state,
1427 MainThreadWorkerState::Codegenning);
1428 main_thread_worker_state = MainThreadWorkerState::Idle;
1431 Message::CodegenComplete => {
1432 codegen_done = true;
1433 assert!(!codegen_aborted);
1434 assert_eq!(main_thread_worker_state,
1435 MainThreadWorkerState::Codegenning);
1436 main_thread_worker_state = MainThreadWorkerState::Idle;
1439 // If codegen is aborted that means translation was aborted due
1440 // to some normal-ish compiler error. In this situation we want
1441 // to exit as soon as possible, but we want to make sure all
1442 // existing work has finished. Flag codegen as being done, and
1443 // then conditions above will ensure no more work is spawned but
1444 // we'll keep executing this loop until `running` hits 0.
1445 Message::CodegenAborted => {
1446 assert!(!codegen_aborted);
1447 codegen_done = true;
1448 codegen_aborted = true;
1449 assert_eq!(main_thread_worker_state,
1450 MainThreadWorkerState::Codegenning);
1452 Message::Done { result: Ok(compiled_module), worker_id } => {
1453 free_worker(worker_id);
1454 match compiled_module.kind {
1455 ModuleKind::Regular => {
1456 compiled_modules.push(compiled_module);
1458 ModuleKind::Metadata => {
1459 assert!(compiled_metadata_module.is_none());
1460 compiled_metadata_module = Some(compiled_module);
1462 ModuleKind::Allocator => {
1463 assert!(compiled_allocator_module.is_none());
1464 compiled_allocator_module = Some(compiled_module);
1468 Message::NeedsFatLTO { result, worker_id } => {
1469 assert!(!started_lto);
1470 free_worker(worker_id);
1471 needs_fat_lto.push(result);
1473 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1474 assert!(!started_lto);
1475 free_worker(worker_id);
1476 needs_thin_lto.push((name, thin_buffer));
1478 Message::AddImportOnlyModule { module_data, work_product } => {
1479 assert!(!started_lto);
1480 assert!(!codegen_done);
1481 assert_eq!(main_thread_worker_state,
1482 MainThreadWorkerState::Codegenning);
1483 lto_import_only_modules.push((module_data, work_product));
1484 main_thread_worker_state = MainThreadWorkerState::Idle;
1486 // If the thread failed that means it panicked, so we abort immediately.
1487 Message::Done { result: Err(()), worker_id: _ } => {
1488 bug!("worker thread panicked");
1490 Message::CodegenItem => {
1491 bug!("the coordinator should not receive codegen requests")
1496 if let Some(llvm_start_time) = llvm_start_time {
1497 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
1498 // This is the top-level timing for all of LLVM, set the time-depth
1501 print_time_passes_entry(cgcx.time_passes,
1506 // Regardless of what order these modules completed in, report them to
1507 // the backend in the same order every time to ensure that we're handing
1508 // out deterministic results.
1509 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1511 Ok(CompiledModules {
1512 modules: compiled_modules,
1513 metadata_module: compiled_metadata_module,
1514 allocator_module: compiled_allocator_module,
1518 // A heuristic that determines if we have enough LLVM WorkItems in the
1519 // queue so that the main thread can do LLVM work instead of codegen
1520 fn queue_full_enough(items_in_queue: usize,
1521 workers_running: usize,
1522 max_workers: usize) -> bool {
1524 items_in_queue > 0 &&
1525 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1528 fn maybe_start_llvm_timer(config: &ModuleConfig,
1529 llvm_start_time: &mut Option<Instant>) {
1530 // We keep track of the -Ztime-passes output manually,
1531 // since the closure-based interface does not fit well here.
1532 if config.time_passes {
1533 if llvm_start_time.is_none() {
1534 *llvm_start_time = Some(Instant::now());
1540 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1542 fn spawn_work<B: ExtraBackendMethods>(
1543 cgcx: CodegenContext<B>,
1546 let depth = time_depth();
1548 thread::spawn(move || {
1549 set_time_depth(depth);
1551 // Set up a destructor which will fire off a message that we're done as
1553 struct Bomb<B: ExtraBackendMethods> {
1554 coordinator_send: Sender<Box<dyn Any + Send>>,
1555 result: Option<WorkItemResult<B>>,
1558 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1559 fn drop(&mut self) {
1560 let worker_id = self.worker_id;
1561 let msg = match self.result.take() {
1562 Some(WorkItemResult::Compiled(m)) => {
1563 Message::Done::<B> { result: Ok(m), worker_id }
1565 Some(WorkItemResult::NeedsFatLTO(m)) => {
1566 Message::NeedsFatLTO::<B> { result: m, worker_id }
1568 Some(WorkItemResult::NeedsThinLTO(name, thin_buffer)) => {
1569 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1571 None => Message::Done::<B> { result: Err(()), worker_id }
1573 drop(self.coordinator_send.send(Box::new(msg)));
1577 let mut bomb = Bomb::<B> {
1578 coordinator_send: cgcx.coordinator_send.clone(),
1580 worker_id: cgcx.worker,
1583 // Execute the work itself, and if it finishes successfully then flag
1584 // ourselves as a success as well.
1586 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1587 // as a diagnostic was already sent off to the main thread - just
1588 // surface that there was an error in this worker.
1590 let _prof_timer = cgcx.prof.generic_activity(&work.name());
1591 execute_work_item(&cgcx, work).ok()
1596 pub fn run_assembler<B: ExtraBackendMethods>(
1597 cgcx: &CodegenContext<B>,
1602 let assembler = cgcx.assembler_cmd
1604 .expect("cgcx.assembler_cmd is missing?");
1606 let pname = &assembler.name;
1607 let mut cmd = assembler.cmd.clone();
1608 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
1609 debug!("{:?}", cmd);
1611 match cmd.output() {
1613 if !prog.status.success() {
1614 let mut note = prog.stderr.clone();
1615 note.extend_from_slice(&prog.stdout);
1617 handler.struct_err(&format!("linking with `{}` failed: {}",
1620 .note(&format!("{:?}", &cmd))
1621 .note(str::from_utf8(¬e[..]).unwrap())
1623 handler.abort_if_errors();
1627 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
1628 handler.abort_if_errors();
1634 enum SharedEmitterMessage {
1635 Diagnostic(Diagnostic),
1636 InlineAsmError(u32, String),
1642 pub struct SharedEmitter {
1643 sender: Sender<SharedEmitterMessage>,
1646 pub struct SharedEmitterMain {
1647 receiver: Receiver<SharedEmitterMessage>,
1650 impl SharedEmitter {
1651 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1652 let (sender, receiver) = channel();
1654 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1657 pub fn inline_asm_error(&self, cookie: u32, msg: String) {
1658 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
1661 pub fn fatal(&self, msg: &str) {
1662 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1666 impl Emitter for SharedEmitter {
1667 fn emit_diagnostic(&mut self, diag: &rustc_errors::Diagnostic) {
1668 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1669 msg: diag.message(),
1670 code: diag.code.clone(),
1673 for child in &diag.children {
1674 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1675 msg: child.message(),
1680 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1682 fn source_map(&self) -> Option<&Lrc<SourceMapperDyn>> {
1687 impl SharedEmitterMain {
1688 pub fn check(&self, sess: &Session, blocking: bool) {
1690 let message = if blocking {
1691 match self.receiver.recv() {
1692 Ok(message) => Ok(message),
1696 match self.receiver.try_recv() {
1697 Ok(message) => Ok(message),
1703 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1704 let handler = sess.diagnostic();
1705 let mut d = rustc_errors::Diagnostic::new(diag.lvl, &diag.msg);
1706 if let Some(code) = diag.code {
1709 handler.emit_diagnostic(&d);
1710 handler.abort_if_errors_and_should_abort();
1712 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
1713 sess.span_err(ExpnId::from_u32(cookie).expn_data().call_site, &msg)
1715 Ok(SharedEmitterMessage::AbortIfErrors) => {
1716 sess.abort_if_errors();
1718 Ok(SharedEmitterMessage::Fatal(msg)) => {
1730 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1732 pub crate_name: Symbol,
1733 pub crate_hash: Svh,
1734 pub metadata: EncodedMetadata,
1735 pub windows_subsystem: Option<String>,
1736 pub linker_info: LinkerInfo,
1737 pub crate_info: CrateInfo,
1738 pub coordinator_send: Sender<Box<dyn Any + Send>>,
1739 pub codegen_worker_receive: Receiver<Message<B>>,
1740 pub shared_emitter_main: SharedEmitterMain,
1741 pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1742 pub output_filenames: Arc<OutputFilenames>,
1745 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1749 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1750 self.shared_emitter_main.check(sess, true);
1751 let compiled_modules = match self.future.join() {
1752 Ok(Ok(compiled_modules)) => compiled_modules,
1754 sess.abort_if_errors();
1755 panic!("expected abort due to worker thread errors")
1758 bug!("panic during codegen/LLVM phase");
1762 sess.cgu_reuse_tracker.check_expected_reuse(sess);
1764 sess.abort_if_errors();
1767 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
1769 produce_final_output_artifacts(sess,
1771 &self.output_filenames);
1773 // FIXME: time_llvm_passes support - does this use a global context or
1775 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1776 self.backend.print_pass_timings()
1780 crate_name: self.crate_name,
1781 crate_hash: self.crate_hash,
1782 metadata: self.metadata,
1783 windows_subsystem: self.windows_subsystem,
1784 linker_info: self.linker_info,
1785 crate_info: self.crate_info,
1787 modules: compiled_modules.modules,
1788 allocator_module: compiled_modules.allocator_module,
1789 metadata_module: compiled_modules.metadata_module,
1793 pub fn submit_pre_codegened_module_to_llvm(
1796 module: ModuleCodegen<B::Module>,
1798 self.wait_for_signal_to_codegen_item();
1799 self.check_for_errors(tcx.sess);
1801 // These are generally cheap and won't throw off scheduling.
1803 submit_codegened_module_to_llvm(&self.backend, &self.coordinator_send, module, cost);
1806 pub fn codegen_finished(&self, tcx: TyCtxt<'_>) {
1807 self.wait_for_signal_to_codegen_item();
1808 self.check_for_errors(tcx.sess);
1809 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1812 /// Consumes this context indicating that codegen was entirely aborted, and
1813 /// we need to exit as quickly as possible.
1815 /// This method blocks the current thread until all worker threads have
1816 /// finished, and all worker threads should have exited or be real close to
1817 /// exiting at this point.
1818 pub fn codegen_aborted(self) {
1819 // Signal to the coordinator it should spawn no more work and start
1821 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1822 drop(self.future.join());
1825 pub fn check_for_errors(&self, sess: &Session) {
1826 self.shared_emitter_main.check(sess, false);
1829 pub fn wait_for_signal_to_codegen_item(&self) {
1830 match self.codegen_worker_receive.recv() {
1831 Ok(Message::CodegenItem) => {
1834 Ok(_) => panic!("unexpected message"),
1836 // One of the LLVM threads must have panicked, fall through so
1837 // error handling can be reached.
1843 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1845 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1846 module: ModuleCodegen<B::Module>,
1849 let llvm_work_item = WorkItem::Optimize(module);
1850 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> {
1856 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1858 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1859 module: CachedModuleCodegen,
1861 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1862 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> {
1868 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1871 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1872 module: CachedModuleCodegen,
1874 let filename = pre_lto_bitcode_filename(&module.name);
1875 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1876 let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
1877 panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
1881 memmap::Mmap::map(&file).unwrap_or_else(|e| {
1882 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1885 // Schedule the module to be loaded
1886 drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule::<B> {
1887 module_data: SerializedModule::FromUncompressedFile(mmap),
1888 work_product: module.source,
1892 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1893 format!("{}.{}", module_name, PRE_LTO_BC_EXT)
1896 fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
1897 // This should never be true (because it's not supported). If it is true,
1898 // something is wrong with commandline arg validation.
1899 assert!(!(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
1900 tcx.sess.target.target.options.is_like_msvc &&
1901 tcx.sess.opts.cg.prefer_dynamic));
1903 tcx.sess.target.target.options.is_like_msvc &&
1904 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
1905 // ThinLTO can't handle this workaround in all cases, so we don't
1906 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
1907 // dynamic linking when linker plugin LTO is enabled.
1908 !tcx.sess.opts.cg.linker_plugin_lto.enabled()