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_errors::{Handler, Level, FatalError, DiagnosticId};
26 use rustc_errors::emitter::{Emitter};
27 use rustc_target::spec::MergeFunctions;
29 use syntax::ext::hygiene::ExpnId;
30 use syntax_pos::symbol::{Symbol, sym};
31 use jobserver::{Client, Acquired};
37 use std::path::{Path, PathBuf};
40 use std::sync::mpsc::{channel, Sender, Receiver};
41 use std::time::Instant;
44 const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
46 /// Module-specific configuration for `optimize_and_codegen`.
47 pub struct ModuleConfig {
48 /// Names of additional optimization passes to run.
49 pub passes: Vec<String>,
50 /// Some(level) to optimize at a certain level, or None to run
51 /// absolutely no optimizations (used for the metadata module).
52 pub opt_level: Option<config::OptLevel>,
54 /// Some(level) to optimize binary size, or None to not affect program size.
55 pub opt_size: Option<config::OptLevel>,
57 pub pgo_gen: SwitchWithOptPath,
58 pub pgo_use: Option<PathBuf>,
60 // Flags indicating which outputs to produce.
61 pub emit_pre_lto_bc: bool,
62 pub emit_no_opt_bc: bool,
64 pub emit_bc_compressed: bool,
65 pub emit_lto_bc: bool,
69 // Miscellaneous flags. These are mostly copied from command-line
71 pub verify_llvm_ir: bool,
72 pub no_prepopulate_passes: bool,
73 pub no_builtins: bool,
74 pub time_passes: bool,
75 pub vectorize_loop: bool,
76 pub vectorize_slp: bool,
77 pub merge_functions: bool,
78 pub inline_threshold: Option<usize>,
79 // Instead of creating an object file by doing LLVM codegen, just
80 // make the object file bitcode. Provides easy compatibility with
81 // emscripten's ecc compiler, when used as the linker.
82 pub obj_is_bitcode: bool,
83 pub no_integrated_as: bool,
84 pub embed_bitcode: bool,
85 pub embed_bitcode_marker: bool,
89 fn new(passes: Vec<String>) -> ModuleConfig {
95 pgo_gen: SwitchWithOptPath::Disabled,
98 emit_no_opt_bc: false,
99 emit_pre_lto_bc: false,
101 emit_bc_compressed: false,
106 obj_is_bitcode: false,
107 embed_bitcode: false,
108 embed_bitcode_marker: false,
109 no_integrated_as: false,
111 verify_llvm_ir: false,
112 no_prepopulate_passes: false,
115 vectorize_loop: false,
116 vectorize_slp: false,
117 merge_functions: false,
118 inline_threshold: None
122 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
123 self.verify_llvm_ir = sess.verify_llvm_ir();
124 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
125 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
126 self.time_passes = sess.time_extended();
127 self.inline_threshold = sess.opts.cg.inline_threshold;
128 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
129 sess.opts.cg.linker_plugin_lto.enabled();
130 let embed_bitcode = sess.target.target.options.embed_bitcode ||
131 sess.opts.debugging_opts.embed_bitcode;
133 match sess.opts.optimize {
134 config::OptLevel::No |
135 config::OptLevel::Less => {
136 self.embed_bitcode_marker = embed_bitcode;
138 _ => self.embed_bitcode = embed_bitcode,
142 // Copy what clang does by turning on loop vectorization at O2 and
143 // slp vectorization at O3. Otherwise configure other optimization aspects
144 // of this pass manager builder.
145 // Turn off vectorization for emscripten, as it's not very well supported.
146 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
147 (sess.opts.optimize == config::OptLevel::Default ||
148 sess.opts.optimize == config::OptLevel::Aggressive) &&
149 !sess.target.target.options.is_like_emscripten;
151 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
152 sess.opts.optimize == config::OptLevel::Aggressive &&
153 !sess.target.target.options.is_like_emscripten;
155 // Some targets (namely, NVPTX) interact badly with the MergeFunctions
156 // pass. This is because MergeFunctions can generate new function calls
157 // which may interfere with the target calling convention; e.g. for the
158 // NVPTX target, PTX kernels should not call other PTX kernels.
159 // MergeFunctions can also be configured to generate aliases instead,
160 // but aliases are not supported by some backends (again, NVPTX).
161 // Therefore, allow targets to opt out of the MergeFunctions pass,
162 // but otherwise keep the pass enabled (at O2 and O3) since it can be
163 // useful for reducing code size.
164 self.merge_functions = match sess.opts.debugging_opts.merge_functions
165 .unwrap_or(sess.target.target.options.merge_functions) {
166 MergeFunctions::Disabled => false,
167 MergeFunctions::Trampolines |
168 MergeFunctions::Aliases => {
169 sess.opts.optimize == config::OptLevel::Default ||
170 sess.opts.optimize == config::OptLevel::Aggressive
175 pub fn bitcode_needed(&self) -> bool {
176 self.emit_bc || self.obj_is_bitcode
177 || self.emit_bc_compressed || self.embed_bitcode
181 /// Assembler name and command used by codegen when no_integrated_as is enabled
182 pub struct AssemblerCommand {
187 // HACK(eddyb) work around `#[derive]` producing wrong bounds for `Clone`.
188 pub struct TargetMachineFactory<B: WriteBackendMethods>(
189 pub Arc<dyn Fn() -> Result<B::TargetMachine, String> + Send + Sync>,
192 impl<B: WriteBackendMethods> Clone for TargetMachineFactory<B> {
193 fn clone(&self) -> Self {
194 TargetMachineFactory(self.0.clone())
198 /// Additional resources used by optimize_and_codegen (not module specific)
200 pub struct CodegenContext<B: WriteBackendMethods> {
201 // Resources needed when running LTO
203 pub time_passes: bool,
204 pub prof: SelfProfilerRef,
206 pub no_landing_pads: bool,
207 pub save_temps: bool,
208 pub fewer_names: bool,
209 pub exported_symbols: Option<Arc<ExportedSymbols>>,
210 pub opts: Arc<config::Options>,
211 pub crate_types: Vec<config::CrateType>,
212 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
213 pub output_filenames: Arc<OutputFilenames>,
214 pub regular_module_config: Arc<ModuleConfig>,
215 pub metadata_module_config: Arc<ModuleConfig>,
216 pub allocator_module_config: Arc<ModuleConfig>,
217 pub tm_factory: TargetMachineFactory<B>,
218 pub msvc_imps_needed: bool,
219 pub target_pointer_width: String,
220 pub target_arch: String,
221 pub debuginfo: config::DebugInfo,
223 // Number of cgus excluding the allocator/metadata modules
224 pub total_cgus: usize,
225 // Handler to use for diagnostics produced during codegen.
226 pub diag_emitter: SharedEmitter,
227 // LLVM passes added by plugins.
228 pub plugin_passes: Vec<String>,
229 // LLVM optimizations for which we want to print remarks.
231 // Worker thread number
233 // The incremental compilation session directory, or None if we are not
234 // compiling incrementally
235 pub incr_comp_session_dir: Option<PathBuf>,
236 // Used to update CGU re-use information during the thinlto phase.
237 pub cgu_reuse_tracker: CguReuseTracker,
238 // Channel back to the main control thread to send messages to
239 pub coordinator_send: Sender<Box<dyn Any + Send>>,
240 // The assembler command if no_integrated_as option is enabled, None otherwise
241 pub assembler_cmd: Option<Arc<AssemblerCommand>>
244 impl<B: WriteBackendMethods> CodegenContext<B> {
245 pub fn create_diag_handler(&self) -> Handler {
246 Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
249 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
251 ModuleKind::Regular => &self.regular_module_config,
252 ModuleKind::Metadata => &self.metadata_module_config,
253 ModuleKind::Allocator => &self.allocator_module_config,
258 fn generate_lto_work<B: ExtraBackendMethods>(
259 cgcx: &CodegenContext<B>,
260 needs_fat_lto: Vec<FatLTOInput<B>>,
261 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
262 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>
263 ) -> Vec<(WorkItem<B>, u64)> {
264 let _prof_timer = cgcx.prof.generic_activity("codegen_run_lto");
266 let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
267 assert!(needs_thin_lto.is_empty());
268 let lto_module = B::run_fat_lto(
273 .unwrap_or_else(|e| e.raise());
274 (vec![lto_module], vec![])
276 assert!(needs_fat_lto.is_empty());
277 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules)
278 .unwrap_or_else(|e| e.raise())
281 let result = lto_modules.into_iter().map(|module| {
282 let cost = module.cost();
283 (WorkItem::LTO(module), cost)
284 }).chain(copy_jobs.into_iter().map(|wp| {
285 (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
286 name: wp.cgu_name.clone(),
294 pub struct CompiledModules {
295 pub modules: Vec<CompiledModule>,
296 pub metadata_module: Option<CompiledModule>,
297 pub allocator_module: Option<CompiledModule>,
300 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
301 sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
302 sess.opts.output_types.contains_key(&OutputType::Exe)
305 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
306 if sess.opts.incremental.is_none() {
314 Lto::ThinLocal => true,
318 pub fn start_async_codegen<B: ExtraBackendMethods>(
321 metadata: EncodedMetadata,
323 ) -> OngoingCodegen<B> {
324 let (coordinator_send, coordinator_receive) = channel();
327 let crate_name = tcx.crate_name(LOCAL_CRATE);
328 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
329 let no_builtins = attr::contains_name(&tcx.hir().krate().attrs, sym::no_builtins);
330 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir().krate().attrs,
331 sym::windows_subsystem);
332 let windows_subsystem = subsystem.map(|subsystem| {
333 if subsystem != sym::windows && subsystem != sym::console {
334 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
335 `windows` and `console` are allowed",
338 subsystem.to_string()
341 let linker_info = LinkerInfo::new(tcx);
342 let crate_info = CrateInfo::new(tcx);
344 // Figure out what we actually need to build.
345 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
346 let mut metadata_config = ModuleConfig::new(vec![]);
347 let mut allocator_config = ModuleConfig::new(vec![]);
349 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
351 Sanitizer::Address => {
352 modules_config.passes.push("asan".to_owned());
353 modules_config.passes.push("asan-module".to_owned());
355 Sanitizer::Memory => {
356 modules_config.passes.push("msan".to_owned())
358 Sanitizer::Thread => {
359 modules_config.passes.push("tsan".to_owned())
365 if sess.opts.debugging_opts.profile {
366 modules_config.passes.push("insert-gcov-profiling".to_owned())
369 modules_config.pgo_gen = sess.opts.cg.profile_generate.clone();
370 modules_config.pgo_use = sess.opts.cg.profile_use.clone();
372 modules_config.opt_level = Some(sess.opts.optimize);
373 modules_config.opt_size = Some(sess.opts.optimize);
375 // Save all versions of the bytecode if we're saving our temporaries.
376 if sess.opts.cg.save_temps {
377 modules_config.emit_no_opt_bc = true;
378 modules_config.emit_pre_lto_bc = true;
379 modules_config.emit_bc = true;
380 modules_config.emit_lto_bc = true;
381 metadata_config.emit_bc = true;
382 allocator_config.emit_bc = true;
385 // Emit compressed bitcode files for the crate if we're emitting an rlib.
386 // Whenever an rlib is created, the bitcode is inserted into the archive in
387 // order to allow LTO against it.
388 if need_crate_bitcode_for_rlib(sess) {
389 modules_config.emit_bc_compressed = true;
390 allocator_config.emit_bc_compressed = true;
393 modules_config.emit_pre_lto_bc =
394 need_pre_lto_bitcode_for_incr_comp(sess);
396 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
397 tcx.sess.target.target.options.no_integrated_as;
399 for output_type in sess.opts.output_types.keys() {
401 OutputType::Bitcode => { modules_config.emit_bc = true; }
402 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
403 OutputType::Assembly => {
404 modules_config.emit_asm = true;
405 // If we're not using the LLVM assembler, this function
406 // could be invoked specially with output_type_assembly, so
407 // in this case we still want the metadata object file.
408 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
409 metadata_config.emit_obj = true;
410 allocator_config.emit_obj = true;
413 OutputType::Object => { modules_config.emit_obj = true; }
414 OutputType::Metadata => { metadata_config.emit_obj = true; }
416 modules_config.emit_obj = true;
417 metadata_config.emit_obj = true;
418 allocator_config.emit_obj = true;
420 OutputType::Mir => {}
421 OutputType::DepInfo => {}
425 modules_config.set_flags(sess, no_builtins);
426 metadata_config.set_flags(sess, no_builtins);
427 allocator_config.set_flags(sess, no_builtins);
429 // Exclude metadata and allocator modules from time_passes output, since
430 // they throw off the "LLVM passes" measurement.
431 metadata_config.time_passes = false;
432 allocator_config.time_passes = false;
434 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
435 let (codegen_worker_send, codegen_worker_receive) = channel();
437 let coordinator_thread = start_executing_work(backend.clone(),
444 sess.jobserver.clone(),
445 Arc::new(modules_config),
446 Arc::new(metadata_config),
447 Arc::new(allocator_config),
448 coordinator_send.clone());
460 codegen_worker_receive,
462 future: coordinator_thread,
463 output_filenames: tcx.output_filenames(LOCAL_CRATE),
467 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
469 compiled_modules: &CompiledModules,
470 ) -> FxHashMap<WorkProductId, WorkProduct> {
471 let mut work_products = FxHashMap::default();
473 if sess.opts.incremental.is_none() {
474 return work_products;
477 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
478 let mut files = vec![];
480 if let Some(ref path) = module.object {
481 files.push((WorkProductFileKind::Object, path.clone()));
483 if let Some(ref path) = module.bytecode {
484 files.push((WorkProductFileKind::Bytecode, path.clone()));
486 if let Some(ref path) = module.bytecode_compressed {
487 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
490 if let Some((id, product)) =
491 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
492 work_products.insert(id, product);
499 fn produce_final_output_artifacts(sess: &Session,
500 compiled_modules: &CompiledModules,
501 crate_output: &OutputFilenames) {
502 let mut user_wants_bitcode = false;
503 let mut user_wants_objects = false;
505 // Produce final compile outputs.
506 let copy_gracefully = |from: &Path, to: &Path| {
507 if let Err(e) = fs::copy(from, to) {
508 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
512 let copy_if_one_unit = |output_type: OutputType,
513 keep_numbered: bool| {
514 if compiled_modules.modules.len() == 1 {
515 // 1) Only one codegen unit. In this case it's no difficulty
516 // to copy `foo.0.x` to `foo.x`.
517 let module_name = Some(&compiled_modules.modules[0].name[..]);
518 let path = crate_output.temp_path(output_type, module_name);
519 copy_gracefully(&path,
520 &crate_output.path(output_type));
521 if !sess.opts.cg.save_temps && !keep_numbered {
522 // The user just wants `foo.x`, not `foo.#module-name#.x`.
526 let ext = crate_output.temp_path(output_type, None)
533 if crate_output.outputs.contains_key(&output_type) {
534 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
535 // no good solution for this case, so warn the user.
536 sess.warn(&format!("ignoring emit path because multiple .{} files \
537 were produced", ext));
538 } else if crate_output.single_output_file.is_some() {
539 // 3) Multiple codegen units, with `-o some_name`. We have
540 // no good solution for this case, so warn the user.
541 sess.warn(&format!("ignoring -o because multiple .{} files \
542 were produced", ext));
544 // 4) Multiple codegen units, but no explicit name. We
545 // just leave the `foo.0.x` files in place.
546 // (We don't have to do any work in this case.)
551 // Flag to indicate whether the user explicitly requested bitcode.
552 // Otherwise, we produced it only as a temporary output, and will need
554 for output_type in crate_output.outputs.keys() {
556 OutputType::Bitcode => {
557 user_wants_bitcode = true;
558 // Copy to .bc, but always keep the .0.bc. There is a later
559 // check to figure out if we should delete .0.bc files, or keep
560 // them for making an rlib.
561 copy_if_one_unit(OutputType::Bitcode, true);
563 OutputType::LlvmAssembly => {
564 copy_if_one_unit(OutputType::LlvmAssembly, false);
566 OutputType::Assembly => {
567 copy_if_one_unit(OutputType::Assembly, false);
569 OutputType::Object => {
570 user_wants_objects = true;
571 copy_if_one_unit(OutputType::Object, true);
574 OutputType::Metadata |
576 OutputType::DepInfo => {}
580 // Clean up unwanted temporary files.
582 // We create the following files by default:
583 // - #crate#.#module-name#.bc
584 // - #crate#.#module-name#.o
585 // - #crate#.crate.metadata.bc
586 // - #crate#.crate.metadata.o
587 // - #crate#.o (linked from crate.##.o)
588 // - #crate#.bc (copied from crate.##.bc)
589 // We may create additional files if requested by the user (through
590 // `-C save-temps` or `--emit=` flags).
592 if !sess.opts.cg.save_temps {
593 // Remove the temporary .#module-name#.o objects. If the user didn't
594 // explicitly request bitcode (with --emit=bc), and the bitcode is not
595 // needed for building an rlib, then we must remove .#module-name#.bc as
598 // Specific rules for keeping .#module-name#.bc:
599 // - If the user requested bitcode (`user_wants_bitcode`), and
600 // codegen_units > 1, then keep it.
601 // - If the user requested bitcode but codegen_units == 1, then we
602 // can toss .#module-name#.bc because we copied it to .bc earlier.
603 // - If we're not building an rlib and the user didn't request
604 // bitcode, then delete .#module-name#.bc.
605 // If you change how this works, also update back::link::link_rlib,
606 // where .#module-name#.bc files are (maybe) deleted after making an
608 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
610 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
612 let keep_numbered_objects = needs_crate_object ||
613 (user_wants_objects && sess.codegen_units() > 1);
615 for module in compiled_modules.modules.iter() {
616 if let Some(ref path) = module.object {
617 if !keep_numbered_objects {
622 if let Some(ref path) = module.bytecode {
623 if !keep_numbered_bitcode {
629 if !user_wants_bitcode {
630 if let Some(ref metadata_module) = compiled_modules.metadata_module {
631 if let Some(ref path) = metadata_module.bytecode {
636 if let Some(ref allocator_module) = compiled_modules.allocator_module {
637 if let Some(ref path) = allocator_module.bytecode {
644 // We leave the following files around by default:
646 // - #crate#.crate.metadata.o
648 // These are used in linking steps and will be cleaned up afterward.
651 pub fn dump_incremental_data(_codegen_results: &CodegenResults) {
652 // FIXME(mw): This does not work at the moment because the situation has
653 // become more complicated due to incremental LTO. Now a CGU
654 // can have more than two caching states.
655 // println!("[incremental] Re-using {} out of {} modules",
656 // codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
657 // codegen_results.modules.len());
660 pub enum WorkItem<B: WriteBackendMethods> {
661 /// Optimize a newly codegened, totally unoptimized module.
662 Optimize(ModuleCodegen<B::Module>),
663 /// Copy the post-LTO artifacts from the incremental cache to the output
665 CopyPostLtoArtifacts(CachedModuleCodegen),
666 /// Performs (Thin)LTO on the given module.
667 LTO(lto::LtoModuleCodegen<B>),
670 impl<B: WriteBackendMethods> WorkItem<B> {
671 pub fn module_kind(&self) -> ModuleKind {
673 WorkItem::Optimize(ref m) => m.kind,
674 WorkItem::CopyPostLtoArtifacts(_) |
675 WorkItem::LTO(_) => ModuleKind::Regular,
679 pub fn name(&self) -> String {
681 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
682 WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
683 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
688 enum WorkItemResult<B: WriteBackendMethods> {
689 Compiled(CompiledModule),
690 NeedsFatLTO(FatLTOInput<B>),
691 NeedsThinLTO(String, B::ThinBuffer),
694 pub enum FatLTOInput<B: WriteBackendMethods> {
697 buffer: B::ModuleBuffer,
699 InMemory(ModuleCodegen<B::Module>),
702 fn execute_work_item<B: ExtraBackendMethods>(
703 cgcx: &CodegenContext<B>,
704 work_item: WorkItem<B>,
705 ) -> Result<WorkItemResult<B>, FatalError> {
706 let module_config = cgcx.config(work_item.module_kind());
709 WorkItem::Optimize(module) => {
710 execute_optimize_work_item(cgcx, module, module_config)
712 WorkItem::CopyPostLtoArtifacts(module) => {
713 execute_copy_from_cache_work_item(cgcx, module, module_config)
715 WorkItem::LTO(module) => {
716 execute_lto_work_item(cgcx, module, module_config)
721 // Actual LTO type we end up chosing based on multiple factors.
722 enum ComputedLtoType {
728 fn execute_optimize_work_item<B: ExtraBackendMethods>(
729 cgcx: &CodegenContext<B>,
730 module: ModuleCodegen<B::Module>,
731 module_config: &ModuleConfig,
732 ) -> Result<WorkItemResult<B>, FatalError> {
733 let diag_handler = cgcx.create_diag_handler();
736 B::optimize(cgcx, &diag_handler, &module, module_config)?;
739 // After we've done the initial round of optimizations we need to
740 // decide whether to synchronously codegen this module or ship it
741 // back to the coordinator thread for further LTO processing (which
742 // has to wait for all the initial modules to be optimized).
744 // If the linker does LTO, we don't have to do it. Note that we
745 // keep doing full LTO, if it is requested, as not to break the
746 // assumption that the output will be a single module.
747 let linker_does_lto = cgcx.opts.cg.linker_plugin_lto.enabled();
749 // When we're automatically doing ThinLTO for multi-codegen-unit
750 // builds we don't actually want to LTO the allocator modules if
751 // it shows up. This is due to various linker shenanigans that
752 // we'll encounter later.
753 let is_allocator = module.kind == ModuleKind::Allocator;
755 // We ignore a request for full crate grath LTO if the cate type
756 // is only an rlib, as there is no full crate graph to process,
757 // that'll happen later.
759 // This use case currently comes up primarily for targets that
760 // require LTO so the request for LTO is always unconditionally
761 // passed down to the backend, but we don't actually want to do
762 // anything about it yet until we've got a final product.
763 let is_rlib = cgcx.crate_types.len() == 1
764 && cgcx.crate_types[0] == config::CrateType::Rlib;
766 // Metadata modules never participate in LTO regardless of the lto
768 let lto_type = if module.kind == ModuleKind::Metadata {
772 Lto::ThinLocal if !linker_does_lto && !is_allocator
773 => ComputedLtoType::Thin,
774 Lto::Thin if !linker_does_lto && !is_rlib
775 => ComputedLtoType::Thin,
776 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
777 _ => ComputedLtoType::No,
781 // If we're doing some form of incremental LTO then we need to be sure to
782 // save our module to disk first.
783 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
784 let filename = pre_lto_bitcode_filename(&module.name);
785 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
791 ComputedLtoType::No => {
792 let module = unsafe {
793 B::codegen(cgcx, &diag_handler, module, module_config)?
795 WorkItemResult::Compiled(module)
797 ComputedLtoType::Thin => {
798 let (name, thin_buffer) = B::prepare_thin(module);
799 if let Some(path) = bitcode {
800 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
801 panic!("Error writing pre-lto-bitcode file `{}`: {}",
806 WorkItemResult::NeedsThinLTO(name, thin_buffer)
808 ComputedLtoType::Fat => {
811 let (name, buffer) = B::serialize_module(module);
812 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
813 panic!("Error writing pre-lto-bitcode file `{}`: {}",
817 WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer })
819 None => WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module)),
825 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
826 cgcx: &CodegenContext<B>,
827 module: CachedModuleCodegen,
828 module_config: &ModuleConfig,
829 ) -> Result<WorkItemResult<B>, FatalError> {
830 let incr_comp_session_dir = cgcx.incr_comp_session_dir
833 let mut object = None;
834 let mut bytecode = None;
835 let mut bytecode_compressed = None;
836 for (kind, saved_file) in &module.source.saved_files {
837 let obj_out = match kind {
838 WorkProductFileKind::Object => {
839 let path = cgcx.output_filenames.temp_path(OutputType::Object,
841 object = Some(path.clone());
844 WorkProductFileKind::Bytecode => {
845 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
847 bytecode = Some(path.clone());
850 WorkProductFileKind::BytecodeCompressed => {
851 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
853 .with_extension(RLIB_BYTECODE_EXTENSION);
854 bytecode_compressed = Some(path.clone());
858 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
860 debug!("copying pre-existing module `{}` from {:?} to {}",
864 if let Err(err) = link_or_copy(&source_file, &obj_out) {
865 let diag_handler = cgcx.create_diag_handler();
866 diag_handler.err(&format!("unable to copy {} to {}: {}",
867 source_file.display(),
873 assert_eq!(object.is_some(), module_config.emit_obj);
874 assert_eq!(bytecode.is_some(), module_config.emit_bc);
875 assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
877 Ok(WorkItemResult::Compiled(CompiledModule {
879 kind: ModuleKind::Regular,
886 fn execute_lto_work_item<B: ExtraBackendMethods>(
887 cgcx: &CodegenContext<B>,
888 mut module: lto::LtoModuleCodegen<B>,
889 module_config: &ModuleConfig,
890 ) -> Result<WorkItemResult<B>, FatalError> {
891 let diag_handler = cgcx.create_diag_handler();
894 let module = module.optimize(cgcx)?;
895 let module = B::codegen(cgcx, &diag_handler, module, module_config)?;
896 Ok(WorkItemResult::Compiled(module))
900 pub enum Message<B: WriteBackendMethods> {
901 Token(io::Result<Acquired>),
903 result: FatLTOInput<B>,
908 thin_buffer: B::ThinBuffer,
912 result: Result<CompiledModule, ()>,
916 llvm_work_item: WorkItem<B>,
919 AddImportOnlyModule {
920 module_data: SerializedModule<B::ModuleBuffer>,
921 work_product: WorkProduct,
930 code: Option<DiagnosticId>,
934 #[derive(PartialEq, Clone, Copy, Debug)]
935 enum MainThreadWorkerState {
941 fn start_executing_work<B: ExtraBackendMethods>(
944 crate_info: &CrateInfo,
945 shared_emitter: SharedEmitter,
946 codegen_worker_send: Sender<Message<B>>,
947 coordinator_receive: Receiver<Box<dyn Any + Send>>,
950 modules_config: Arc<ModuleConfig>,
951 metadata_config: Arc<ModuleConfig>,
952 allocator_config: Arc<ModuleConfig>,
953 tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
954 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
955 let coordinator_send = tx_to_llvm_workers;
958 // Compute the set of symbols we need to retain when doing LTO (if we need to)
959 let exported_symbols = {
960 let mut exported_symbols = FxHashMap::default();
962 let copy_symbols = |cnum| {
963 let symbols = tcx.exported_symbols(cnum)
965 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
973 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
974 Some(Arc::new(exported_symbols))
976 Lto::Fat | Lto::Thin => {
977 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
978 for &cnum in tcx.crates().iter() {
979 exported_symbols.insert(cnum, copy_symbols(cnum));
981 Some(Arc::new(exported_symbols))
986 // First up, convert our jobserver into a helper thread so we can use normal
987 // mpsc channels to manage our messages and such.
988 // After we've requested tokens then we'll, when we can,
989 // get tokens on `coordinator_receive` which will
990 // get managed in the main loop below.
991 let coordinator_send2 = coordinator_send.clone();
992 let helper = jobserver.into_helper_thread(move |token| {
993 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
994 }).expect("failed to spawn helper thread");
996 let mut each_linked_rlib_for_lto = Vec::new();
997 drop(link::each_linked_rlib(crate_info, &mut |cnum, path| {
998 if link::ignored_for_lto(sess, crate_info, cnum) {
1001 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1004 let assembler_cmd = if modules_config.no_integrated_as {
1005 // HACK: currently we use linker (gcc) as our assembler
1006 let (linker, flavor) = link::linker_and_flavor(sess);
1008 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1009 cmd.args(&sess.target.target.options.asm_args);
1010 Some(Arc::new(AssemblerCommand {
1018 let ol = if tcx.sess.opts.debugging_opts.no_codegen
1019 || !tcx.sess.opts.output_types.should_codegen() {
1020 // If we know that we won’t be doing codegen, create target machines without optimisation.
1021 config::OptLevel::No
1023 tcx.backend_optimization_level(LOCAL_CRATE)
1025 let cgcx = CodegenContext::<B> {
1026 backend: backend.clone(),
1027 crate_types: sess.crate_types.borrow().clone(),
1028 each_linked_rlib_for_lto,
1030 no_landing_pads: sess.no_landing_pads(),
1031 fewer_names: sess.fewer_names(),
1032 save_temps: sess.opts.cg.save_temps,
1033 opts: Arc::new(sess.opts.clone()),
1034 time_passes: sess.time_extended(),
1035 prof: sess.prof.clone(),
1037 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1038 remark: sess.opts.cg.remark.clone(),
1040 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1041 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1043 diag_emitter: shared_emitter.clone(),
1044 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1045 regular_module_config: modules_config,
1046 metadata_module_config: metadata_config,
1047 allocator_module_config: allocator_config,
1048 tm_factory: TargetMachineFactory(backend.target_machine_factory(tcx.sess, ol, false)),
1050 msvc_imps_needed: msvc_imps_needed(tcx),
1051 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1052 target_arch: tcx.sess.target.target.arch.clone(),
1053 debuginfo: tcx.sess.opts.debuginfo,
1057 // This is the "main loop" of parallel work happening for parallel codegen.
1058 // It's here that we manage parallelism, schedule work, and work with
1059 // messages coming from clients.
1061 // There are a few environmental pre-conditions that shape how the system
1064 // - Error reporting only can happen on the main thread because that's the
1065 // only place where we have access to the compiler `Session`.
1066 // - LLVM work can be done on any thread.
1067 // - Codegen can only happen on the main thread.
1068 // - Each thread doing substantial work most be in possession of a `Token`
1069 // from the `Jobserver`.
1070 // - The compiler process always holds one `Token`. Any additional `Tokens`
1071 // have to be requested from the `Jobserver`.
1075 // The error reporting restriction is handled separately from the rest: We
1076 // set up a `SharedEmitter` the holds an open channel to the main thread.
1077 // When an error occurs on any thread, the shared emitter will send the
1078 // error message to the receiver main thread (`SharedEmitterMain`). The
1079 // main thread will periodically query this error message queue and emit
1080 // any error messages it has received. It might even abort compilation if
1081 // has received a fatal error. In this case we rely on all other threads
1082 // being torn down automatically with the main thread.
1083 // Since the main thread will often be busy doing codegen work, error
1084 // reporting will be somewhat delayed, since the message queue can only be
1085 // checked in between to work packages.
1087 // Work Processing Infrastructure
1088 // ==============================
1089 // The work processing infrastructure knows three major actors:
1091 // - the coordinator thread,
1092 // - the main thread, and
1093 // - LLVM worker threads
1095 // The coordinator thread is running a message loop. It instructs the main
1096 // thread about what work to do when, and it will spawn off LLVM worker
1097 // threads as open LLVM WorkItems become available.
1099 // The job of the main thread is to codegen CGUs into LLVM work package
1100 // (since the main thread is the only thread that can do this). The main
1101 // thread will block until it receives a message from the coordinator, upon
1102 // which it will codegen one CGU, send it to the coordinator and block
1103 // again. This way the coordinator can control what the main thread is
1106 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1107 // available, it will spawn off a new LLVM worker thread and let it process
1108 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1109 // it will just shut down, which also frees all resources associated with
1110 // the given LLVM module, and sends a message to the coordinator that the
1111 // has been completed.
1115 // The scheduler's goal is to minimize the time it takes to complete all
1116 // work there is, however, we also want to keep memory consumption low
1117 // if possible. These two goals are at odds with each other: If memory
1118 // consumption were not an issue, we could just let the main thread produce
1119 // LLVM WorkItems at full speed, assuring maximal utilization of
1120 // Tokens/LLVM worker threads. However, since codegen usual is faster
1121 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1122 // WorkItem potentially holds on to a substantial amount of memory.
1124 // So the actual goal is to always produce just enough LLVM WorkItems as
1125 // not to starve our LLVM worker threads. That means, once we have enough
1126 // WorkItems in our queue, we can block the main thread, so it does not
1127 // produce more until we need them.
1129 // Doing LLVM Work on the Main Thread
1130 // ----------------------------------
1131 // Since the main thread owns the compiler processes implicit `Token`, it is
1132 // wasteful to keep it blocked without doing any work. Therefore, what we do
1133 // in this case is: We spawn off an additional LLVM worker thread that helps
1134 // reduce the queue. The work it is doing corresponds to the implicit
1135 // `Token`. The coordinator will mark the main thread as being busy with
1136 // LLVM work. (The actual work happens on another OS thread but we just care
1137 // about `Tokens`, not actual threads).
1139 // When any LLVM worker thread finishes while the main thread is marked as
1140 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1141 // of the just finished thread to the LLVM worker thread that is working on
1142 // behalf of the main thread's implicit Token, thus freeing up the main
1143 // thread again. The coordinator can then again decide what the main thread
1144 // should do. This allows the coordinator to make decisions at more points
1147 // Striking a Balance between Throughput and Memory Consumption
1148 // ------------------------------------------------------------
1149 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1150 // memory consumption as low as possible, are in conflict with each other,
1151 // we have to find a trade off between them. Right now, the goal is to keep
1152 // all workers busy, which means that no worker should find the queue empty
1153 // when it is ready to start.
1154 // How do we do achieve this? Good question :) We actually never know how
1155 // many `Tokens` are potentially available so it's hard to say how much to
1156 // fill up the queue before switching the main thread to LLVM work. Also we
1157 // currently don't have a means to estimate how long a running LLVM worker
1158 // will still be busy with it's current WorkItem. However, we know the
1159 // maximal count of available Tokens that makes sense (=the number of CPU
1160 // cores), so we can take a conservative guess. The heuristic we use here
1161 // is implemented in the `queue_full_enough()` function.
1163 // Some Background on Jobservers
1164 // -----------------------------
1165 // It's worth also touching on the management of parallelism here. We don't
1166 // want to just spawn a thread per work item because while that's optimal
1167 // parallelism it may overload a system with too many threads or violate our
1168 // configuration for the maximum amount of cpu to use for this process. To
1169 // manage this we use the `jobserver` crate.
1171 // Job servers are an artifact of GNU make and are used to manage
1172 // parallelism between processes. A jobserver is a glorified IPC semaphore
1173 // basically. Whenever we want to run some work we acquire the semaphore,
1174 // and whenever we're done with that work we release the semaphore. In this
1175 // manner we can ensure that the maximum number of parallel workers is
1176 // capped at any one point in time.
1178 // LTO and the coordinator thread
1179 // ------------------------------
1181 // The final job the coordinator thread is responsible for is managing LTO
1182 // and how that works. When LTO is requested what we'll to is collect all
1183 // optimized LLVM modules into a local vector on the coordinator. Once all
1184 // modules have been codegened and optimized we hand this to the `lto`
1185 // module for further optimization. The `lto` module will return back a list
1186 // of more modules to work on, which the coordinator will continue to spawn
1189 // Each LLVM module is automatically sent back to the coordinator for LTO if
1190 // necessary. There's already optimizations in place to avoid sending work
1191 // back to the coordinator if LTO isn't requested.
1192 return thread::spawn(move || {
1193 // We pretend to be within the top-level LLVM time-passes task here:
1196 let max_workers = ::num_cpus::get();
1197 let mut worker_id_counter = 0;
1198 let mut free_worker_ids = Vec::new();
1199 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1200 if let Some(id) = free_worker_ids.pop() {
1203 let id = worker_id_counter;
1204 worker_id_counter += 1;
1209 // This is where we collect codegen units that have gone all the way
1210 // through codegen and LLVM.
1211 let mut compiled_modules = vec![];
1212 let mut compiled_metadata_module = None;
1213 let mut compiled_allocator_module = None;
1214 let mut needs_fat_lto = Vec::new();
1215 let mut needs_thin_lto = Vec::new();
1216 let mut lto_import_only_modules = Vec::new();
1217 let mut started_lto = false;
1218 let mut codegen_aborted = false;
1220 // This flag tracks whether all items have gone through codegens
1221 let mut codegen_done = false;
1223 // This is the queue of LLVM work items that still need processing.
1224 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1226 // This are the Jobserver Tokens we currently hold. Does not include
1227 // the implicit Token the compiler process owns no matter what.
1228 let mut tokens = Vec::new();
1230 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1231 let mut running = 0;
1233 let mut llvm_start_time = None;
1235 // Run the message loop while there's still anything that needs message
1236 // processing. Note that as soon as codegen is aborted we simply want to
1237 // wait for all existing work to finish, so many of the conditions here
1238 // only apply if codegen hasn't been aborted as they represent pending
1240 while !codegen_done ||
1242 (!codegen_aborted && (
1243 work_items.len() > 0 ||
1244 needs_fat_lto.len() > 0 ||
1245 needs_thin_lto.len() > 0 ||
1246 lto_import_only_modules.len() > 0 ||
1247 main_thread_worker_state != MainThreadWorkerState::Idle
1251 // While there are still CGUs to be codegened, the coordinator has
1252 // to decide how to utilize the compiler processes implicit Token:
1253 // For codegenning more CGU or for running them through LLVM.
1255 if main_thread_worker_state == MainThreadWorkerState::Idle {
1256 if !queue_full_enough(work_items.len(), running, max_workers) {
1257 // The queue is not full enough, codegen more items:
1258 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1259 panic!("Could not send Message::CodegenItem to main thread")
1261 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1263 // The queue is full enough to not let the worker
1264 // threads starve. Use the implicit Token to do some
1266 let (item, _) = work_items.pop()
1267 .expect("queue empty - queue_full_enough() broken?");
1268 let cgcx = CodegenContext {
1269 worker: get_worker_id(&mut free_worker_ids),
1272 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1273 &mut llvm_start_time);
1274 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1275 spawn_work(cgcx, item);
1278 } else if codegen_aborted {
1279 // don't queue up any more work if codegen was aborted, we're
1280 // just waiting for our existing children to finish
1282 // If we've finished everything related to normal codegen
1283 // then it must be the case that we've got some LTO work to do.
1284 // Perform the serial work here of figuring out what we're
1285 // going to LTO and then push a bunch of work items onto our
1287 if work_items.len() == 0 &&
1289 main_thread_worker_state == MainThreadWorkerState::Idle {
1290 assert!(!started_lto);
1293 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1294 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1295 let import_only_modules = mem::take(&mut lto_import_only_modules);
1297 for (work, cost) in generate_lto_work(&cgcx, needs_fat_lto,
1298 needs_thin_lto, import_only_modules) {
1299 let insertion_index = work_items
1300 .binary_search_by_key(&cost, |&(_, cost)| cost)
1301 .unwrap_or_else(|e| e);
1302 work_items.insert(insertion_index, (work, cost));
1303 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1304 helper.request_token();
1309 // In this branch, we know that everything has been codegened,
1310 // so it's just a matter of determining whether the implicit
1311 // Token is free to use for LLVM work.
1312 match main_thread_worker_state {
1313 MainThreadWorkerState::Idle => {
1314 if let Some((item, _)) = work_items.pop() {
1315 let cgcx = CodegenContext {
1316 worker: get_worker_id(&mut free_worker_ids),
1319 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1320 &mut llvm_start_time);
1321 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1322 spawn_work(cgcx, item);
1324 // There is no unstarted work, so let the main thread
1325 // take over for a running worker. Otherwise the
1326 // implicit token would just go to waste.
1327 // We reduce the `running` counter by one. The
1328 // `tokens.truncate()` below will take care of
1329 // giving the Token back.
1330 debug_assert!(running > 0);
1332 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1335 MainThreadWorkerState::Codegenning => {
1336 bug!("codegen worker should not be codegenning after \
1337 codegen was already completed")
1339 MainThreadWorkerState::LLVMing => {
1340 // Already making good use of that token
1345 // Spin up what work we can, only doing this while we've got available
1346 // parallelism slots and work left to spawn.
1347 while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1348 let (item, _) = work_items.pop().unwrap();
1350 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1351 &mut llvm_start_time);
1353 let cgcx = CodegenContext {
1354 worker: get_worker_id(&mut free_worker_ids),
1358 spawn_work(cgcx, item);
1362 // Relinquish accidentally acquired extra tokens
1363 tokens.truncate(running);
1365 // If a thread exits successfully then we drop a token associated
1366 // with that worker and update our `running` count. We may later
1367 // re-acquire a token to continue running more work. We may also not
1368 // actually drop a token here if the worker was running with an
1369 // "ephemeral token"
1370 let mut free_worker = |worker_id| {
1371 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1372 main_thread_worker_state = MainThreadWorkerState::Idle;
1377 free_worker_ids.push(worker_id);
1380 let msg = coordinator_receive.recv().unwrap();
1381 match *msg.downcast::<Message<B>>().ok().unwrap() {
1382 // Save the token locally and the next turn of the loop will use
1383 // this to spawn a new unit of work, or it may get dropped
1384 // immediately if we have no more work to spawn.
1385 Message::Token(token) => {
1390 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1391 // If the main thread token is used for LLVM work
1392 // at the moment, we turn that thread into a regular
1393 // LLVM worker thread, so the main thread is free
1394 // to react to codegen demand.
1395 main_thread_worker_state = MainThreadWorkerState::Idle;
1400 let msg = &format!("failed to acquire jobserver token: {}", e);
1401 shared_emitter.fatal(msg);
1402 // Exit the coordinator thread
1408 Message::CodegenDone { llvm_work_item, cost } => {
1409 // We keep the queue sorted by estimated processing cost,
1410 // so that more expensive items are processed earlier. This
1411 // is good for throughput as it gives the main thread more
1412 // time to fill up the queue and it avoids scheduling
1413 // expensive items to the end.
1414 // Note, however, that this is not ideal for memory
1415 // consumption, as LLVM module sizes are not evenly
1417 let insertion_index =
1418 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1419 let insertion_index = match insertion_index {
1420 Ok(idx) | Err(idx) => idx
1422 work_items.insert(insertion_index, (llvm_work_item, cost));
1424 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1425 helper.request_token();
1427 assert!(!codegen_aborted);
1428 assert_eq!(main_thread_worker_state,
1429 MainThreadWorkerState::Codegenning);
1430 main_thread_worker_state = MainThreadWorkerState::Idle;
1433 Message::CodegenComplete => {
1434 codegen_done = true;
1435 assert!(!codegen_aborted);
1436 assert_eq!(main_thread_worker_state,
1437 MainThreadWorkerState::Codegenning);
1438 main_thread_worker_state = MainThreadWorkerState::Idle;
1441 // If codegen is aborted that means translation was aborted due
1442 // to some normal-ish compiler error. In this situation we want
1443 // to exit as soon as possible, but we want to make sure all
1444 // existing work has finished. Flag codegen as being done, and
1445 // then conditions above will ensure no more work is spawned but
1446 // we'll keep executing this loop until `running` hits 0.
1447 Message::CodegenAborted => {
1448 assert!(!codegen_aborted);
1449 codegen_done = true;
1450 codegen_aborted = true;
1451 assert_eq!(main_thread_worker_state,
1452 MainThreadWorkerState::Codegenning);
1454 Message::Done { result: Ok(compiled_module), worker_id } => {
1455 free_worker(worker_id);
1456 match compiled_module.kind {
1457 ModuleKind::Regular => {
1458 compiled_modules.push(compiled_module);
1460 ModuleKind::Metadata => {
1461 assert!(compiled_metadata_module.is_none());
1462 compiled_metadata_module = Some(compiled_module);
1464 ModuleKind::Allocator => {
1465 assert!(compiled_allocator_module.is_none());
1466 compiled_allocator_module = Some(compiled_module);
1470 Message::NeedsFatLTO { result, worker_id } => {
1471 assert!(!started_lto);
1472 free_worker(worker_id);
1473 needs_fat_lto.push(result);
1475 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1476 assert!(!started_lto);
1477 free_worker(worker_id);
1478 needs_thin_lto.push((name, thin_buffer));
1480 Message::AddImportOnlyModule { module_data, work_product } => {
1481 assert!(!started_lto);
1482 assert!(!codegen_done);
1483 assert_eq!(main_thread_worker_state,
1484 MainThreadWorkerState::Codegenning);
1485 lto_import_only_modules.push((module_data, work_product));
1486 main_thread_worker_state = MainThreadWorkerState::Idle;
1488 // If the thread failed that means it panicked, so we abort immediately.
1489 Message::Done { result: Err(()), worker_id: _ } => {
1490 bug!("worker thread panicked");
1492 Message::CodegenItem => {
1493 bug!("the coordinator should not receive codegen requests")
1498 if let Some(llvm_start_time) = llvm_start_time {
1499 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
1500 // This is the top-level timing for all of LLVM, set the time-depth
1503 print_time_passes_entry(cgcx.time_passes,
1508 // Regardless of what order these modules completed in, report them to
1509 // the backend in the same order every time to ensure that we're handing
1510 // out deterministic results.
1511 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1513 Ok(CompiledModules {
1514 modules: compiled_modules,
1515 metadata_module: compiled_metadata_module,
1516 allocator_module: compiled_allocator_module,
1520 // A heuristic that determines if we have enough LLVM WorkItems in the
1521 // queue so that the main thread can do LLVM work instead of codegen
1522 fn queue_full_enough(items_in_queue: usize,
1523 workers_running: usize,
1524 max_workers: usize) -> bool {
1526 items_in_queue > 0 &&
1527 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1530 fn maybe_start_llvm_timer(config: &ModuleConfig,
1531 llvm_start_time: &mut Option<Instant>) {
1532 // We keep track of the -Ztime-passes output manually,
1533 // since the closure-based interface does not fit well here.
1534 if config.time_passes {
1535 if llvm_start_time.is_none() {
1536 *llvm_start_time = Some(Instant::now());
1542 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1544 fn spawn_work<B: ExtraBackendMethods>(
1545 cgcx: CodegenContext<B>,
1548 let depth = time_depth();
1550 thread::spawn(move || {
1551 set_time_depth(depth);
1553 // Set up a destructor which will fire off a message that we're done as
1555 struct Bomb<B: ExtraBackendMethods> {
1556 coordinator_send: Sender<Box<dyn Any + Send>>,
1557 result: Option<WorkItemResult<B>>,
1560 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1561 fn drop(&mut self) {
1562 let worker_id = self.worker_id;
1563 let msg = match self.result.take() {
1564 Some(WorkItemResult::Compiled(m)) => {
1565 Message::Done::<B> { result: Ok(m), worker_id }
1567 Some(WorkItemResult::NeedsFatLTO(m)) => {
1568 Message::NeedsFatLTO::<B> { result: m, worker_id }
1570 Some(WorkItemResult::NeedsThinLTO(name, thin_buffer)) => {
1571 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1573 None => Message::Done::<B> { result: Err(()), worker_id }
1575 drop(self.coordinator_send.send(Box::new(msg)));
1579 let mut bomb = Bomb::<B> {
1580 coordinator_send: cgcx.coordinator_send.clone(),
1582 worker_id: cgcx.worker,
1585 // Execute the work itself, and if it finishes successfully then flag
1586 // ourselves as a success as well.
1588 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1589 // as a diagnostic was already sent off to the main thread - just
1590 // surface that there was an error in this worker.
1592 let _prof_timer = cgcx.prof.generic_activity(&work.name());
1593 execute_work_item(&cgcx, work).ok()
1598 pub fn run_assembler<B: ExtraBackendMethods>(
1599 cgcx: &CodegenContext<B>,
1604 let assembler = cgcx.assembler_cmd
1606 .expect("cgcx.assembler_cmd is missing?");
1608 let pname = &assembler.name;
1609 let mut cmd = assembler.cmd.clone();
1610 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
1611 debug!("{:?}", cmd);
1613 match cmd.output() {
1615 if !prog.status.success() {
1616 let mut note = prog.stderr.clone();
1617 note.extend_from_slice(&prog.stdout);
1619 handler.struct_err(&format!("linking with `{}` failed: {}",
1622 .note(&format!("{:?}", &cmd))
1623 .note(str::from_utf8(¬e[..]).unwrap())
1625 handler.abort_if_errors();
1629 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
1630 handler.abort_if_errors();
1636 enum SharedEmitterMessage {
1637 Diagnostic(Diagnostic),
1638 InlineAsmError(u32, String),
1644 pub struct SharedEmitter {
1645 sender: Sender<SharedEmitterMessage>,
1648 pub struct SharedEmitterMain {
1649 receiver: Receiver<SharedEmitterMessage>,
1652 impl SharedEmitter {
1653 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1654 let (sender, receiver) = channel();
1656 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1659 pub fn inline_asm_error(&self, cookie: u32, msg: String) {
1660 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
1663 pub fn fatal(&self, msg: &str) {
1664 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1668 impl Emitter for SharedEmitter {
1669 fn emit_diagnostic(&mut self, db: &rustc_errors::Diagnostic) {
1670 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1672 code: db.code.clone(),
1675 for child in &db.children {
1676 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1677 msg: child.message(),
1682 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1686 impl SharedEmitterMain {
1687 pub fn check(&self, sess: &Session, blocking: bool) {
1689 let message = if blocking {
1690 match self.receiver.recv() {
1691 Ok(message) => Ok(message),
1695 match self.receiver.try_recv() {
1696 Ok(message) => Ok(message),
1702 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1703 let handler = sess.diagnostic();
1704 let mut d = rustc_errors::Diagnostic::new(diag.lvl, &diag.msg);
1705 if let Some(code) = diag.code {
1708 handler.emit_diagnostic(&d);
1709 handler.abort_if_errors_and_should_abort();
1711 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
1712 sess.span_err(ExpnId::from_u32(cookie).expn_data().call_site, &msg)
1714 Ok(SharedEmitterMessage::AbortIfErrors) => {
1715 sess.abort_if_errors();
1717 Ok(SharedEmitterMessage::Fatal(msg)) => {
1729 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1731 pub crate_name: Symbol,
1732 pub crate_hash: Svh,
1733 pub metadata: EncodedMetadata,
1734 pub windows_subsystem: Option<String>,
1735 pub linker_info: LinkerInfo,
1736 pub crate_info: CrateInfo,
1737 pub coordinator_send: Sender<Box<dyn Any + Send>>,
1738 pub codegen_worker_receive: Receiver<Message<B>>,
1739 pub shared_emitter_main: SharedEmitterMain,
1740 pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1741 pub output_filenames: Arc<OutputFilenames>,
1744 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1748 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1749 self.shared_emitter_main.check(sess, true);
1750 let compiled_modules = match self.future.join() {
1751 Ok(Ok(compiled_modules)) => compiled_modules,
1753 sess.abort_if_errors();
1754 panic!("expected abort due to worker thread errors")
1757 bug!("panic during codegen/LLVM phase");
1761 sess.cgu_reuse_tracker.check_expected_reuse(sess);
1763 sess.abort_if_errors();
1766 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
1768 produce_final_output_artifacts(sess,
1770 &self.output_filenames);
1772 // FIXME: time_llvm_passes support - does this use a global context or
1774 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1775 self.backend.print_pass_timings()
1779 crate_name: self.crate_name,
1780 crate_hash: self.crate_hash,
1781 metadata: self.metadata,
1782 windows_subsystem: self.windows_subsystem,
1783 linker_info: self.linker_info,
1784 crate_info: self.crate_info,
1786 modules: compiled_modules.modules,
1787 allocator_module: compiled_modules.allocator_module,
1788 metadata_module: compiled_modules.metadata_module,
1792 pub fn submit_pre_codegened_module_to_llvm(
1795 module: ModuleCodegen<B::Module>,
1797 self.wait_for_signal_to_codegen_item();
1798 self.check_for_errors(tcx.sess);
1800 // These are generally cheap and won't throw off scheduling.
1802 submit_codegened_module_to_llvm(&self.backend, &self.coordinator_send, module, cost);
1805 pub fn codegen_finished(&self, tcx: TyCtxt<'_>) {
1806 self.wait_for_signal_to_codegen_item();
1807 self.check_for_errors(tcx.sess);
1808 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1811 /// Consumes this context indicating that codegen was entirely aborted, and
1812 /// we need to exit as quickly as possible.
1814 /// This method blocks the current thread until all worker threads have
1815 /// finished, and all worker threads should have exited or be real close to
1816 /// exiting at this point.
1817 pub fn codegen_aborted(self) {
1818 // Signal to the coordinator it should spawn no more work and start
1820 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1821 drop(self.future.join());
1824 pub fn check_for_errors(&self, sess: &Session) {
1825 self.shared_emitter_main.check(sess, false);
1828 pub fn wait_for_signal_to_codegen_item(&self) {
1829 match self.codegen_worker_receive.recv() {
1830 Ok(Message::CodegenItem) => {
1833 Ok(_) => panic!("unexpected message"),
1835 // One of the LLVM threads must have panicked, fall through so
1836 // error handling can be reached.
1842 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1844 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1845 module: ModuleCodegen<B::Module>,
1848 let llvm_work_item = WorkItem::Optimize(module);
1849 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> {
1855 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1857 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1858 module: CachedModuleCodegen,
1860 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1861 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> {
1867 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1870 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1871 module: CachedModuleCodegen,
1873 let filename = pre_lto_bitcode_filename(&module.name);
1874 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1875 let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
1876 panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
1880 memmap::Mmap::map(&file).unwrap_or_else(|e| {
1881 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1884 // Schedule the module to be loaded
1885 drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule::<B> {
1886 module_data: SerializedModule::FromUncompressedFile(mmap),
1887 work_product: module.source,
1891 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1892 format!("{}.{}", module_name, PRE_LTO_BC_EXT)
1895 fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
1896 // This should never be true (because it's not supported). If it is true,
1897 // something is wrong with commandline arg validation.
1898 assert!(!(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
1899 tcx.sess.target.target.options.is_like_msvc &&
1900 tcx.sess.opts.cg.prefer_dynamic));
1902 tcx.sess.target.target.options.is_like_msvc &&
1903 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
1904 // ThinLTO can't handle this workaround in all cases, so we don't
1905 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
1906 // dynamic linking when linker plugin LTO is enabled.
1907 !tcx.sess.opts.cg.linker_plugin_lto.enabled()