]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/back/write.rs
Rollup merge of #83809 - GuillaumeGomez:remove-initial-ids, r=camelid
[rust.git] / compiler / rustc_codegen_ssa / src / back / write.rs
1 use super::link::{self, ensure_removed};
2 use super::linker::LinkerInfo;
3 use super::lto::{self, SerializedModule};
4 use super::symbol_export::symbol_name_for_instance_in_crate;
5
6 use crate::{
7     CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
8 };
9
10 use crate::traits::*;
11 use jobserver::{Acquired, Client};
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_data_structures::memmap::Mmap;
14 use rustc_data_structures::profiling::SelfProfilerRef;
15 use rustc_data_structures::profiling::TimingGuard;
16 use rustc_data_structures::profiling::VerboseTimingGuard;
17 use rustc_data_structures::sync::Lrc;
18 use rustc_errors::emitter::Emitter;
19 use rustc_errors::{DiagnosticId, FatalError, Handler, Level};
20 use rustc_fs_util::link_or_copy;
21 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
22 use rustc_incremental::{
23     copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
24 };
25 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
26 use rustc_middle::middle::cstore::EncodedMetadata;
27 use rustc_middle::middle::exported_symbols::SymbolExportLevel;
28 use rustc_middle::ty::TyCtxt;
29 use rustc_session::cgu_reuse_tracker::CguReuseTracker;
30 use rustc_session::config::{self, CrateType, Lto, OutputFilenames, OutputType};
31 use rustc_session::config::{Passes, SwitchWithOptPath};
32 use rustc_session::Session;
33 use rustc_span::source_map::SourceMap;
34 use rustc_span::symbol::{sym, Symbol};
35 use rustc_span::{BytePos, FileName, InnerSpan, Pos, Span};
36 use rustc_target::spec::{MergeFunctions, PanicStrategy, SanitizerSet};
37
38 use std::any::Any;
39 use std::fs;
40 use std::io;
41 use std::mem;
42 use std::path::{Path, PathBuf};
43 use std::str;
44 use std::sync::mpsc::{channel, Receiver, Sender};
45 use std::sync::Arc;
46 use std::thread;
47
48 const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
49
50 /// What kind of object file to emit.
51 #[derive(Clone, Copy, PartialEq)]
52 pub enum EmitObj {
53     // No object file.
54     None,
55
56     // Just uncompressed llvm bitcode. Provides easy compatibility with
57     // emscripten's ecc compiler, when used as the linker.
58     Bitcode,
59
60     // Object code, possibly augmented with a bitcode section.
61     ObjectCode(BitcodeSection),
62 }
63
64 /// What kind of llvm bitcode section to embed in an object file.
65 #[derive(Clone, Copy, PartialEq)]
66 pub enum BitcodeSection {
67     // No bitcode section.
68     None,
69
70     // A full, uncompressed bitcode section.
71     Full,
72 }
73
74 /// Module-specific configuration for `optimize_and_codegen`.
75 pub struct ModuleConfig {
76     /// Names of additional optimization passes to run.
77     pub passes: Vec<String>,
78     /// Some(level) to optimize at a certain level, or None to run
79     /// absolutely no optimizations (used for the metadata module).
80     pub opt_level: Option<config::OptLevel>,
81
82     /// Some(level) to optimize binary size, or None to not affect program size.
83     pub opt_size: Option<config::OptLevel>,
84
85     pub pgo_gen: SwitchWithOptPath,
86     pub pgo_use: Option<PathBuf>,
87
88     pub sanitizer: SanitizerSet,
89     pub sanitizer_recover: SanitizerSet,
90     pub sanitizer_memory_track_origins: usize,
91
92     // Flags indicating which outputs to produce.
93     pub emit_pre_lto_bc: bool,
94     pub emit_no_opt_bc: bool,
95     pub emit_bc: bool,
96     pub emit_ir: bool,
97     pub emit_asm: bool,
98     pub emit_obj: EmitObj,
99     pub bc_cmdline: String,
100
101     // Miscellaneous flags.  These are mostly copied from command-line
102     // options.
103     pub verify_llvm_ir: bool,
104     pub no_prepopulate_passes: bool,
105     pub no_builtins: bool,
106     pub time_module: bool,
107     pub vectorize_loop: bool,
108     pub vectorize_slp: bool,
109     pub merge_functions: bool,
110     pub inline_threshold: Option<usize>,
111     pub new_llvm_pass_manager: bool,
112     pub emit_lifetime_markers: bool,
113 }
114
115 impl ModuleConfig {
116     fn new(
117         kind: ModuleKind,
118         sess: &Session,
119         no_builtins: bool,
120         is_compiler_builtins: bool,
121     ) -> ModuleConfig {
122         // If it's a regular module, use `$regular`, otherwise use `$other`.
123         // `$regular` and `$other` are evaluated lazily.
124         macro_rules! if_regular {
125             ($regular: expr, $other: expr) => {
126                 if let ModuleKind::Regular = kind { $regular } else { $other }
127             };
128         }
129
130         let opt_level_and_size = if_regular!(Some(sess.opts.optimize), None);
131
132         let save_temps = sess.opts.cg.save_temps;
133
134         let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
135             || match kind {
136                 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
137                 ModuleKind::Allocator => false,
138                 ModuleKind::Metadata => sess.opts.output_types.contains_key(&OutputType::Metadata),
139             };
140
141         let emit_obj = if !should_emit_obj {
142             EmitObj::None
143         } else if sess.target.obj_is_bitcode
144             || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
145         {
146             // This case is selected if the target uses objects as bitcode, or
147             // if linker plugin LTO is enabled. In the linker plugin LTO case
148             // the assumption is that the final link-step will read the bitcode
149             // and convert it to object code. This may be done by either the
150             // native linker or rustc itself.
151             //
152             // Note, however, that the linker-plugin-lto requested here is
153             // explicitly ignored for `#![no_builtins]` crates. These crates are
154             // specifically ignored by rustc's LTO passes and wouldn't work if
155             // loaded into the linker. These crates define symbols that LLVM
156             // lowers intrinsics to, and these symbol dependencies aren't known
157             // until after codegen. As a result any crate marked
158             // `#![no_builtins]` is assumed to not participate in LTO and
159             // instead goes on to generate object code.
160             EmitObj::Bitcode
161         } else if need_bitcode_in_object(sess) {
162             EmitObj::ObjectCode(BitcodeSection::Full)
163         } else {
164             EmitObj::ObjectCode(BitcodeSection::None)
165         };
166
167         ModuleConfig {
168             passes: if_regular!(
169                 {
170                     let mut passes = sess.opts.cg.passes.clone();
171                     // compiler_builtins overrides the codegen-units settings,
172                     // which is incompatible with -Zprofile which requires that
173                     // only a single codegen unit is used per crate.
174                     if sess.opts.debugging_opts.profile && !is_compiler_builtins {
175                         passes.push("insert-gcov-profiling".to_owned());
176                     }
177
178                     // The rustc option `-Zinstrument_coverage` injects intrinsic calls to
179                     // `llvm.instrprof.increment()`, which requires the LLVM `instrprof` pass.
180                     if sess.instrument_coverage() {
181                         passes.push("instrprof".to_owned());
182                     }
183                     passes
184                 },
185                 vec![]
186             ),
187
188             opt_level: opt_level_and_size,
189             opt_size: opt_level_and_size,
190
191             pgo_gen: if_regular!(
192                 sess.opts.cg.profile_generate.clone(),
193                 SwitchWithOptPath::Disabled
194             ),
195             pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
196
197             sanitizer: if_regular!(sess.opts.debugging_opts.sanitizer, SanitizerSet::empty()),
198             sanitizer_recover: if_regular!(
199                 sess.opts.debugging_opts.sanitizer_recover,
200                 SanitizerSet::empty()
201             ),
202             sanitizer_memory_track_origins: if_regular!(
203                 sess.opts.debugging_opts.sanitizer_memory_track_origins,
204                 0
205             ),
206
207             emit_pre_lto_bc: if_regular!(
208                 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
209                 false
210             ),
211             emit_no_opt_bc: if_regular!(save_temps, false),
212             emit_bc: if_regular!(
213                 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
214                 save_temps
215             ),
216             emit_ir: if_regular!(
217                 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
218                 false
219             ),
220             emit_asm: if_regular!(
221                 sess.opts.output_types.contains_key(&OutputType::Assembly),
222                 false
223             ),
224             emit_obj,
225             bc_cmdline: sess.target.bitcode_llvm_cmdline.clone(),
226
227             verify_llvm_ir: sess.verify_llvm_ir(),
228             no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
229             no_builtins: no_builtins || sess.target.no_builtins,
230
231             // Exclude metadata and allocator modules from time_passes output,
232             // since they throw off the "LLVM passes" measurement.
233             time_module: if_regular!(true, false),
234
235             // Copy what clang does by turning on loop vectorization at O2 and
236             // slp vectorization at O3.
237             vectorize_loop: !sess.opts.cg.no_vectorize_loops
238                 && (sess.opts.optimize == config::OptLevel::Default
239                     || sess.opts.optimize == config::OptLevel::Aggressive),
240             vectorize_slp: !sess.opts.cg.no_vectorize_slp
241                 && sess.opts.optimize == config::OptLevel::Aggressive,
242
243             // Some targets (namely, NVPTX) interact badly with the
244             // MergeFunctions pass. This is because MergeFunctions can generate
245             // new function calls which may interfere with the target calling
246             // convention; e.g. for the NVPTX target, PTX kernels should not
247             // call other PTX kernels. MergeFunctions can also be configured to
248             // generate aliases instead, but aliases are not supported by some
249             // backends (again, NVPTX). Therefore, allow targets to opt out of
250             // the MergeFunctions pass, but otherwise keep the pass enabled (at
251             // O2 and O3) since it can be useful for reducing code size.
252             merge_functions: match sess
253                 .opts
254                 .debugging_opts
255                 .merge_functions
256                 .unwrap_or(sess.target.merge_functions)
257             {
258                 MergeFunctions::Disabled => false,
259                 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
260                     sess.opts.optimize == config::OptLevel::Default
261                         || sess.opts.optimize == config::OptLevel::Aggressive
262                 }
263             },
264
265             inline_threshold: sess.opts.cg.inline_threshold,
266             new_llvm_pass_manager: sess.opts.debugging_opts.new_llvm_pass_manager,
267             emit_lifetime_markers: sess.emit_lifetime_markers(),
268         }
269     }
270
271     pub fn bitcode_needed(&self) -> bool {
272         self.emit_bc
273             || self.emit_obj == EmitObj::Bitcode
274             || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
275     }
276 }
277
278 /// Configuration passed to the function returned by the `target_machine_factory`.
279 pub struct TargetMachineFactoryConfig {
280     /// Split DWARF is enabled in LLVM by checking that `TM.MCOptions.SplitDwarfFile` isn't empty,
281     /// so the path to the dwarf object has to be provided when we create the target machine.
282     /// This can be ignored by backends which do not need it for their Split DWARF support.
283     pub split_dwarf_file: Option<PathBuf>,
284 }
285
286 impl TargetMachineFactoryConfig {
287     pub fn new(
288         cgcx: &CodegenContext<impl WriteBackendMethods>,
289         module_name: &str,
290     ) -> TargetMachineFactoryConfig {
291         let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
292             cgcx.output_filenames.split_dwarf_path(cgcx.split_debuginfo, Some(module_name))
293         } else {
294             None
295         };
296         TargetMachineFactoryConfig { split_dwarf_file }
297     }
298 }
299
300 pub type TargetMachineFactoryFn<B> = Arc<
301     dyn Fn(TargetMachineFactoryConfig) -> Result<<B as WriteBackendMethods>::TargetMachine, String>
302         + Send
303         + Sync,
304 >;
305
306 pub type ExportedSymbols = FxHashMap<CrateNum, Arc<Vec<(String, SymbolExportLevel)>>>;
307
308 /// Additional resources used by optimize_and_codegen (not module specific)
309 #[derive(Clone)]
310 pub struct CodegenContext<B: WriteBackendMethods> {
311     // Resources needed when running LTO
312     pub backend: B,
313     pub prof: SelfProfilerRef,
314     pub lto: Lto,
315     pub no_landing_pads: bool,
316     pub save_temps: bool,
317     pub fewer_names: bool,
318     pub exported_symbols: Option<Arc<ExportedSymbols>>,
319     pub opts: Arc<config::Options>,
320     pub crate_types: Vec<CrateType>,
321     pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
322     pub output_filenames: Arc<OutputFilenames>,
323     pub regular_module_config: Arc<ModuleConfig>,
324     pub metadata_module_config: Arc<ModuleConfig>,
325     pub allocator_module_config: Arc<ModuleConfig>,
326     pub tm_factory: TargetMachineFactoryFn<B>,
327     pub msvc_imps_needed: bool,
328     pub is_pe_coff: bool,
329     pub target_can_use_split_dwarf: bool,
330     pub target_pointer_width: u32,
331     pub target_arch: String,
332     pub debuginfo: config::DebugInfo,
333     pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
334
335     // Number of cgus excluding the allocator/metadata modules
336     pub total_cgus: usize,
337     // Handler to use for diagnostics produced during codegen.
338     pub diag_emitter: SharedEmitter,
339     // LLVM optimizations for which we want to print remarks.
340     pub remark: Passes,
341     // Worker thread number
342     pub worker: usize,
343     // The incremental compilation session directory, or None if we are not
344     // compiling incrementally
345     pub incr_comp_session_dir: Option<PathBuf>,
346     // Used to update CGU re-use information during the thinlto phase.
347     pub cgu_reuse_tracker: CguReuseTracker,
348     // Channel back to the main control thread to send messages to
349     pub coordinator_send: Sender<Box<dyn Any + Send>>,
350 }
351
352 impl<B: WriteBackendMethods> CodegenContext<B> {
353     pub fn create_diag_handler(&self) -> Handler {
354         Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
355     }
356
357     pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
358         match kind {
359             ModuleKind::Regular => &self.regular_module_config,
360             ModuleKind::Metadata => &self.metadata_module_config,
361             ModuleKind::Allocator => &self.allocator_module_config,
362         }
363     }
364 }
365
366 fn generate_lto_work<B: ExtraBackendMethods>(
367     cgcx: &CodegenContext<B>,
368     needs_fat_lto: Vec<FatLTOInput<B>>,
369     needs_thin_lto: Vec<(String, B::ThinBuffer)>,
370     import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
371 ) -> Vec<(WorkItem<B>, u64)> {
372     let _prof_timer = cgcx.prof.generic_activity("codegen_generate_lto_work");
373
374     let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
375         assert!(needs_thin_lto.is_empty());
376         let lto_module =
377             B::run_fat_lto(cgcx, needs_fat_lto, import_only_modules).unwrap_or_else(|e| e.raise());
378         (vec![lto_module], vec![])
379     } else {
380         assert!(needs_fat_lto.is_empty());
381         B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules).unwrap_or_else(|e| e.raise())
382     };
383
384     lto_modules
385         .into_iter()
386         .map(|module| {
387             let cost = module.cost();
388             (WorkItem::LTO(module), cost)
389         })
390         .chain(copy_jobs.into_iter().map(|wp| {
391             (
392                 WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
393                     name: wp.cgu_name.clone(),
394                     source: wp,
395                 }),
396                 0,
397             )
398         }))
399         .collect()
400 }
401
402 pub struct CompiledModules {
403     pub modules: Vec<CompiledModule>,
404     pub metadata_module: Option<CompiledModule>,
405     pub allocator_module: Option<CompiledModule>,
406 }
407
408 fn need_bitcode_in_object(sess: &Session) -> bool {
409     let requested_for_rlib = sess.opts.cg.embed_bitcode
410         && sess.crate_types().contains(&CrateType::Rlib)
411         && sess.opts.output_types.contains_key(&OutputType::Exe);
412     let forced_by_target = sess.target.forces_embed_bitcode;
413     requested_for_rlib || forced_by_target
414 }
415
416 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
417     if sess.opts.incremental.is_none() {
418         return false;
419     }
420
421     match sess.lto() {
422         Lto::No => false,
423         Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
424     }
425 }
426
427 pub fn start_async_codegen<B: ExtraBackendMethods>(
428     backend: B,
429     tcx: TyCtxt<'_>,
430     metadata: EncodedMetadata,
431     total_cgus: usize,
432 ) -> OngoingCodegen<B> {
433     let (coordinator_send, coordinator_receive) = channel();
434     let sess = tcx.sess;
435
436     let crate_name = tcx.crate_name(LOCAL_CRATE);
437     let crate_attrs = tcx.hir().attrs(rustc_hir::CRATE_HIR_ID);
438     let no_builtins = tcx.sess.contains_name(crate_attrs, sym::no_builtins);
439     let is_compiler_builtins = tcx.sess.contains_name(crate_attrs, sym::compiler_builtins);
440     let subsystem = tcx.sess.first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem);
441     let windows_subsystem = subsystem.map(|subsystem| {
442         if subsystem != sym::windows && subsystem != sym::console {
443             tcx.sess.fatal(&format!(
444                 "invalid windows subsystem `{}`, only \
445                                      `windows` and `console` are allowed",
446                 subsystem
447             ));
448         }
449         subsystem.to_string()
450     });
451
452     let linker_info = LinkerInfo::new(tcx);
453     let crate_info = CrateInfo::new(tcx);
454
455     let regular_config =
456         ModuleConfig::new(ModuleKind::Regular, sess, no_builtins, is_compiler_builtins);
457     let metadata_config =
458         ModuleConfig::new(ModuleKind::Metadata, sess, no_builtins, is_compiler_builtins);
459     let allocator_config =
460         ModuleConfig::new(ModuleKind::Allocator, sess, no_builtins, is_compiler_builtins);
461
462     let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
463     let (codegen_worker_send, codegen_worker_receive) = channel();
464
465     let coordinator_thread = start_executing_work(
466         backend.clone(),
467         tcx,
468         &crate_info,
469         shared_emitter,
470         codegen_worker_send,
471         coordinator_receive,
472         total_cgus,
473         sess.jobserver.clone(),
474         Arc::new(regular_config),
475         Arc::new(metadata_config),
476         Arc::new(allocator_config),
477         coordinator_send.clone(),
478     );
479
480     OngoingCodegen {
481         backend,
482         crate_name,
483         metadata,
484         windows_subsystem,
485         linker_info,
486         crate_info,
487
488         coordinator_send,
489         codegen_worker_receive,
490         shared_emitter_main,
491         future: coordinator_thread,
492         output_filenames: tcx.output_filenames(LOCAL_CRATE),
493     }
494 }
495
496 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
497     sess: &Session,
498     compiled_modules: &CompiledModules,
499 ) -> FxHashMap<WorkProductId, WorkProduct> {
500     let mut work_products = FxHashMap::default();
501
502     if sess.opts.incremental.is_none() {
503         return work_products;
504     }
505
506     let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
507
508     for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
509         let path = module.object.as_ref().cloned();
510
511         if let Some((id, product)) =
512             copy_cgu_workproduct_to_incr_comp_cache_dir(sess, &module.name, &path)
513         {
514             work_products.insert(id, product);
515         }
516     }
517
518     work_products
519 }
520
521 fn produce_final_output_artifacts(
522     sess: &Session,
523     compiled_modules: &CompiledModules,
524     crate_output: &OutputFilenames,
525 ) {
526     let mut user_wants_bitcode = false;
527     let mut user_wants_objects = false;
528
529     // Produce final compile outputs.
530     let copy_gracefully = |from: &Path, to: &Path| {
531         if let Err(e) = fs::copy(from, to) {
532             sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
533         }
534     };
535
536     let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
537         if compiled_modules.modules.len() == 1 {
538             // 1) Only one codegen unit.  In this case it's no difficulty
539             //    to copy `foo.0.x` to `foo.x`.
540             let module_name = Some(&compiled_modules.modules[0].name[..]);
541             let path = crate_output.temp_path(output_type, module_name);
542             copy_gracefully(&path, &crate_output.path(output_type));
543             if !sess.opts.cg.save_temps && !keep_numbered {
544                 // The user just wants `foo.x`, not `foo.#module-name#.x`.
545                 ensure_removed(sess.diagnostic(), &path);
546             }
547         } else {
548             let ext = crate_output
549                 .temp_path(output_type, None)
550                 .extension()
551                 .unwrap()
552                 .to_str()
553                 .unwrap()
554                 .to_owned();
555
556             if crate_output.outputs.contains_key(&output_type) {
557                 // 2) Multiple codegen units, with `--emit foo=some_name`.  We have
558                 //    no good solution for this case, so warn the user.
559                 sess.warn(&format!(
560                     "ignoring emit path because multiple .{} files \
561                                     were produced",
562                     ext
563                 ));
564             } else if crate_output.single_output_file.is_some() {
565                 // 3) Multiple codegen units, with `-o some_name`.  We have
566                 //    no good solution for this case, so warn the user.
567                 sess.warn(&format!(
568                     "ignoring -o because multiple .{} files \
569                                     were produced",
570                     ext
571                 ));
572             } else {
573                 // 4) Multiple codegen units, but no explicit name.  We
574                 //    just leave the `foo.0.x` files in place.
575                 // (We don't have to do any work in this case.)
576             }
577         }
578     };
579
580     // Flag to indicate whether the user explicitly requested bitcode.
581     // Otherwise, we produced it only as a temporary output, and will need
582     // to get rid of it.
583     for output_type in crate_output.outputs.keys() {
584         match *output_type {
585             OutputType::Bitcode => {
586                 user_wants_bitcode = true;
587                 // Copy to .bc, but always keep the .0.bc.  There is a later
588                 // check to figure out if we should delete .0.bc files, or keep
589                 // them for making an rlib.
590                 copy_if_one_unit(OutputType::Bitcode, true);
591             }
592             OutputType::LlvmAssembly => {
593                 copy_if_one_unit(OutputType::LlvmAssembly, false);
594             }
595             OutputType::Assembly => {
596                 copy_if_one_unit(OutputType::Assembly, false);
597             }
598             OutputType::Object => {
599                 user_wants_objects = true;
600                 copy_if_one_unit(OutputType::Object, true);
601             }
602             OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
603         }
604     }
605
606     // Clean up unwanted temporary files.
607
608     // We create the following files by default:
609     //  - #crate#.#module-name#.bc
610     //  - #crate#.#module-name#.o
611     //  - #crate#.crate.metadata.bc
612     //  - #crate#.crate.metadata.o
613     //  - #crate#.o (linked from crate.##.o)
614     //  - #crate#.bc (copied from crate.##.bc)
615     // We may create additional files if requested by the user (through
616     // `-C save-temps` or `--emit=` flags).
617
618     if !sess.opts.cg.save_temps {
619         // Remove the temporary .#module-name#.o objects.  If the user didn't
620         // explicitly request bitcode (with --emit=bc), and the bitcode is not
621         // needed for building an rlib, then we must remove .#module-name#.bc as
622         // well.
623
624         // Specific rules for keeping .#module-name#.bc:
625         //  - If the user requested bitcode (`user_wants_bitcode`), and
626         //    codegen_units > 1, then keep it.
627         //  - If the user requested bitcode but codegen_units == 1, then we
628         //    can toss .#module-name#.bc because we copied it to .bc earlier.
629         //  - If we're not building an rlib and the user didn't request
630         //    bitcode, then delete .#module-name#.bc.
631         // If you change how this works, also update back::link::link_rlib,
632         // where .#module-name#.bc files are (maybe) deleted after making an
633         // rlib.
634         let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
635
636         let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
637
638         let keep_numbered_objects =
639             needs_crate_object || (user_wants_objects && sess.codegen_units() > 1);
640
641         for module in compiled_modules.modules.iter() {
642             if let Some(ref path) = module.object {
643                 if !keep_numbered_objects {
644                     ensure_removed(sess.diagnostic(), path);
645                 }
646             }
647
648             if let Some(ref path) = module.dwarf_object {
649                 if !keep_numbered_objects {
650                     ensure_removed(sess.diagnostic(), path);
651                 }
652             }
653
654             if let Some(ref path) = module.bytecode {
655                 if !keep_numbered_bitcode {
656                     ensure_removed(sess.diagnostic(), path);
657                 }
658             }
659         }
660
661         if !user_wants_bitcode {
662             if let Some(ref metadata_module) = compiled_modules.metadata_module {
663                 if let Some(ref path) = metadata_module.bytecode {
664                     ensure_removed(sess.diagnostic(), &path);
665                 }
666             }
667
668             if let Some(ref allocator_module) = compiled_modules.allocator_module {
669                 if let Some(ref path) = allocator_module.bytecode {
670                     ensure_removed(sess.diagnostic(), path);
671                 }
672             }
673         }
674     }
675
676     // We leave the following files around by default:
677     //  - #crate#.o
678     //  - #crate#.crate.metadata.o
679     //  - #crate#.bc
680     // These are used in linking steps and will be cleaned up afterward.
681 }
682
683 pub enum WorkItem<B: WriteBackendMethods> {
684     /// Optimize a newly codegened, totally unoptimized module.
685     Optimize(ModuleCodegen<B::Module>),
686     /// Copy the post-LTO artifacts from the incremental cache to the output
687     /// directory.
688     CopyPostLtoArtifacts(CachedModuleCodegen),
689     /// Performs (Thin)LTO on the given module.
690     LTO(lto::LtoModuleCodegen<B>),
691 }
692
693 impl<B: WriteBackendMethods> WorkItem<B> {
694     pub fn module_kind(&self) -> ModuleKind {
695         match *self {
696             WorkItem::Optimize(ref m) => m.kind,
697             WorkItem::CopyPostLtoArtifacts(_) | WorkItem::LTO(_) => ModuleKind::Regular,
698         }
699     }
700
701     fn start_profiling<'a>(&self, cgcx: &'a CodegenContext<B>) -> TimingGuard<'a> {
702         match *self {
703             WorkItem::Optimize(ref m) => {
704                 cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &m.name[..])
705             }
706             WorkItem::CopyPostLtoArtifacts(ref m) => cgcx
707                 .prof
708                 .generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &m.name[..]),
709             WorkItem::LTO(ref m) => {
710                 cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name())
711             }
712         }
713     }
714
715     /// Generate a short description of this work item suitable for use as a thread name.
716     fn short_description(&self) -> String {
717         // `pthread_setname()` on *nix is limited to 15 characters and longer names are ignored.
718         // Use very short descriptions in this case to maximize the space available for the module name.
719         // Windows does not have that limitation so use slightly more descriptive names there.
720         match self {
721             WorkItem::Optimize(m) => {
722                 #[cfg(windows)]
723                 return format!("optimize module {}", m.name);
724                 #[cfg(not(windows))]
725                 return format!("opt {}", m.name);
726             }
727             WorkItem::CopyPostLtoArtifacts(m) => {
728                 #[cfg(windows)]
729                 return format!("copy LTO artifacts for {}", m.name);
730                 #[cfg(not(windows))]
731                 return format!("copy {}", m.name);
732             }
733             WorkItem::LTO(m) => {
734                 #[cfg(windows)]
735                 return format!("LTO module {}", m.name());
736                 #[cfg(not(windows))]
737                 return format!("LTO {}", m.name());
738             }
739         }
740     }
741 }
742
743 enum WorkItemResult<B: WriteBackendMethods> {
744     Compiled(CompiledModule),
745     NeedsLink(ModuleCodegen<B::Module>),
746     NeedsFatLTO(FatLTOInput<B>),
747     NeedsThinLTO(String, B::ThinBuffer),
748 }
749
750 pub enum FatLTOInput<B: WriteBackendMethods> {
751     Serialized { name: String, buffer: B::ModuleBuffer },
752     InMemory(ModuleCodegen<B::Module>),
753 }
754
755 fn execute_work_item<B: ExtraBackendMethods>(
756     cgcx: &CodegenContext<B>,
757     work_item: WorkItem<B>,
758 ) -> Result<WorkItemResult<B>, FatalError> {
759     let module_config = cgcx.config(work_item.module_kind());
760
761     match work_item {
762         WorkItem::Optimize(module) => execute_optimize_work_item(cgcx, module, module_config),
763         WorkItem::CopyPostLtoArtifacts(module) => {
764             Ok(execute_copy_from_cache_work_item(cgcx, module, module_config))
765         }
766         WorkItem::LTO(module) => execute_lto_work_item(cgcx, module, module_config),
767     }
768 }
769
770 // Actual LTO type we end up choosing based on multiple factors.
771 pub enum ComputedLtoType {
772     No,
773     Thin,
774     Fat,
775 }
776
777 pub fn compute_per_cgu_lto_type(
778     sess_lto: &Lto,
779     opts: &config::Options,
780     sess_crate_types: &[CrateType],
781     module_kind: ModuleKind,
782 ) -> ComputedLtoType {
783     // Metadata modules never participate in LTO regardless of the lto
784     // settings.
785     if module_kind == ModuleKind::Metadata {
786         return ComputedLtoType::No;
787     }
788
789     // If the linker does LTO, we don't have to do it. Note that we
790     // keep doing full LTO, if it is requested, as not to break the
791     // assumption that the output will be a single module.
792     let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
793
794     // When we're automatically doing ThinLTO for multi-codegen-unit
795     // builds we don't actually want to LTO the allocator modules if
796     // it shows up. This is due to various linker shenanigans that
797     // we'll encounter later.
798     let is_allocator = module_kind == ModuleKind::Allocator;
799
800     // We ignore a request for full crate grath LTO if the cate type
801     // is only an rlib, as there is no full crate graph to process,
802     // that'll happen later.
803     //
804     // This use case currently comes up primarily for targets that
805     // require LTO so the request for LTO is always unconditionally
806     // passed down to the backend, but we don't actually want to do
807     // anything about it yet until we've got a final product.
808     let is_rlib = sess_crate_types.len() == 1 && sess_crate_types[0] == CrateType::Rlib;
809
810     match sess_lto {
811         Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
812         Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
813         Lto::Fat if !is_rlib => ComputedLtoType::Fat,
814         _ => ComputedLtoType::No,
815     }
816 }
817
818 fn execute_optimize_work_item<B: ExtraBackendMethods>(
819     cgcx: &CodegenContext<B>,
820     module: ModuleCodegen<B::Module>,
821     module_config: &ModuleConfig,
822 ) -> Result<WorkItemResult<B>, FatalError> {
823     let diag_handler = cgcx.create_diag_handler();
824
825     unsafe {
826         B::optimize(cgcx, &diag_handler, &module, module_config)?;
827     }
828
829     // After we've done the initial round of optimizations we need to
830     // decide whether to synchronously codegen this module or ship it
831     // back to the coordinator thread for further LTO processing (which
832     // has to wait for all the initial modules to be optimized).
833
834     let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
835
836     // If we're doing some form of incremental LTO then we need to be sure to
837     // save our module to disk first.
838     let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
839         let filename = pre_lto_bitcode_filename(&module.name);
840         cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
841     } else {
842         None
843     };
844
845     match lto_type {
846         ComputedLtoType::No => finish_intra_module_work(cgcx, module, module_config),
847         ComputedLtoType::Thin => {
848             let (name, thin_buffer) = B::prepare_thin(module);
849             if let Some(path) = bitcode {
850                 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
851                     panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
852                 });
853             }
854             Ok(WorkItemResult::NeedsThinLTO(name, thin_buffer))
855         }
856         ComputedLtoType::Fat => match bitcode {
857             Some(path) => {
858                 let (name, buffer) = B::serialize_module(module);
859                 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
860                     panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
861                 });
862                 Ok(WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer }))
863             }
864             None => Ok(WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module))),
865         },
866     }
867 }
868
869 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
870     cgcx: &CodegenContext<B>,
871     module: CachedModuleCodegen,
872     module_config: &ModuleConfig,
873 ) -> WorkItemResult<B> {
874     let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
875     let mut object = None;
876     if let Some(saved_file) = module.source.saved_file {
877         let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, Some(&module.name));
878         object = Some(obj_out.clone());
879         let source_file = in_incr_comp_dir(&incr_comp_session_dir, &saved_file);
880         debug!(
881             "copying pre-existing module `{}` from {:?} to {}",
882             module.name,
883             source_file,
884             obj_out.display()
885         );
886         if let Err(err) = link_or_copy(&source_file, &obj_out) {
887             let diag_handler = cgcx.create_diag_handler();
888             diag_handler.err(&format!(
889                 "unable to copy {} to {}: {}",
890                 source_file.display(),
891                 obj_out.display(),
892                 err
893             ));
894         }
895     }
896
897     assert_eq!(object.is_some(), module_config.emit_obj != EmitObj::None);
898
899     WorkItemResult::Compiled(CompiledModule {
900         name: module.name,
901         kind: ModuleKind::Regular,
902         object,
903         dwarf_object: None,
904         bytecode: None,
905     })
906 }
907
908 fn execute_lto_work_item<B: ExtraBackendMethods>(
909     cgcx: &CodegenContext<B>,
910     mut module: lto::LtoModuleCodegen<B>,
911     module_config: &ModuleConfig,
912 ) -> Result<WorkItemResult<B>, FatalError> {
913     let module = unsafe { module.optimize(cgcx)? };
914     finish_intra_module_work(cgcx, module, module_config)
915 }
916
917 fn finish_intra_module_work<B: ExtraBackendMethods>(
918     cgcx: &CodegenContext<B>,
919     module: ModuleCodegen<B::Module>,
920     module_config: &ModuleConfig,
921 ) -> Result<WorkItemResult<B>, FatalError> {
922     let diag_handler = cgcx.create_diag_handler();
923
924     if !cgcx.opts.debugging_opts.combine_cgu
925         || module.kind == ModuleKind::Metadata
926         || module.kind == ModuleKind::Allocator
927     {
928         let module = unsafe { B::codegen(cgcx, &diag_handler, module, module_config)? };
929         Ok(WorkItemResult::Compiled(module))
930     } else {
931         Ok(WorkItemResult::NeedsLink(module))
932     }
933 }
934
935 pub enum Message<B: WriteBackendMethods> {
936     Token(io::Result<Acquired>),
937     NeedsFatLTO {
938         result: FatLTOInput<B>,
939         worker_id: usize,
940     },
941     NeedsThinLTO {
942         name: String,
943         thin_buffer: B::ThinBuffer,
944         worker_id: usize,
945     },
946     NeedsLink {
947         module: ModuleCodegen<B::Module>,
948         worker_id: usize,
949     },
950     Done {
951         result: Result<CompiledModule, Option<WorkerFatalError>>,
952         worker_id: usize,
953     },
954     CodegenDone {
955         llvm_work_item: WorkItem<B>,
956         cost: u64,
957     },
958     AddImportOnlyModule {
959         module_data: SerializedModule<B::ModuleBuffer>,
960         work_product: WorkProduct,
961     },
962     CodegenComplete,
963     CodegenItem,
964     CodegenAborted,
965 }
966
967 struct Diagnostic {
968     msg: String,
969     code: Option<DiagnosticId>,
970     lvl: Level,
971 }
972
973 #[derive(PartialEq, Clone, Copy, Debug)]
974 enum MainThreadWorkerState {
975     Idle,
976     Codegenning,
977     LLVMing,
978 }
979
980 fn start_executing_work<B: ExtraBackendMethods>(
981     backend: B,
982     tcx: TyCtxt<'_>,
983     crate_info: &CrateInfo,
984     shared_emitter: SharedEmitter,
985     codegen_worker_send: Sender<Message<B>>,
986     coordinator_receive: Receiver<Box<dyn Any + Send>>,
987     total_cgus: usize,
988     jobserver: Client,
989     regular_config: Arc<ModuleConfig>,
990     metadata_config: Arc<ModuleConfig>,
991     allocator_config: Arc<ModuleConfig>,
992     tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
993 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
994     let coordinator_send = tx_to_llvm_workers;
995     let sess = tcx.sess;
996
997     // Compute the set of symbols we need to retain when doing LTO (if we need to)
998     let exported_symbols = {
999         let mut exported_symbols = FxHashMap::default();
1000
1001         let copy_symbols = |cnum| {
1002             let symbols = tcx
1003                 .exported_symbols(cnum)
1004                 .iter()
1005                 .map(|&(s, lvl)| (symbol_name_for_instance_in_crate(tcx, s, cnum), lvl))
1006                 .collect();
1007             Arc::new(symbols)
1008         };
1009
1010         match sess.lto() {
1011             Lto::No => None,
1012             Lto::ThinLocal => {
1013                 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1014                 Some(Arc::new(exported_symbols))
1015             }
1016             Lto::Fat | Lto::Thin => {
1017                 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1018                 for &cnum in tcx.crates().iter() {
1019                     exported_symbols.insert(cnum, copy_symbols(cnum));
1020                 }
1021                 Some(Arc::new(exported_symbols))
1022             }
1023         }
1024     };
1025
1026     // First up, convert our jobserver into a helper thread so we can use normal
1027     // mpsc channels to manage our messages and such.
1028     // After we've requested tokens then we'll, when we can,
1029     // get tokens on `coordinator_receive` which will
1030     // get managed in the main loop below.
1031     let coordinator_send2 = coordinator_send.clone();
1032     let helper = jobserver
1033         .into_helper_thread(move |token| {
1034             drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
1035         })
1036         .expect("failed to spawn helper thread");
1037
1038     let mut each_linked_rlib_for_lto = Vec::new();
1039     drop(link::each_linked_rlib(crate_info, &mut |cnum, path| {
1040         if link::ignored_for_lto(sess, crate_info, cnum) {
1041             return;
1042         }
1043         each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1044     }));
1045
1046     let ol = if tcx.sess.opts.debugging_opts.no_codegen
1047         || !tcx.sess.opts.output_types.should_codegen()
1048     {
1049         // If we know that we won’t be doing codegen, create target machines without optimisation.
1050         config::OptLevel::No
1051     } else {
1052         tcx.backend_optimization_level(LOCAL_CRATE)
1053     };
1054     let cgcx = CodegenContext::<B> {
1055         backend: backend.clone(),
1056         crate_types: sess.crate_types().to_vec(),
1057         each_linked_rlib_for_lto,
1058         lto: sess.lto(),
1059         no_landing_pads: sess.panic_strategy() == PanicStrategy::Abort,
1060         fewer_names: sess.fewer_names(),
1061         save_temps: sess.opts.cg.save_temps,
1062         opts: Arc::new(sess.opts.clone()),
1063         prof: sess.prof.clone(),
1064         exported_symbols,
1065         remark: sess.opts.cg.remark.clone(),
1066         worker: 0,
1067         incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1068         cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1069         coordinator_send,
1070         diag_emitter: shared_emitter.clone(),
1071         output_filenames: tcx.output_filenames(LOCAL_CRATE),
1072         regular_module_config: regular_config,
1073         metadata_module_config: metadata_config,
1074         allocator_module_config: allocator_config,
1075         tm_factory: backend.target_machine_factory(tcx.sess, ol),
1076         total_cgus,
1077         msvc_imps_needed: msvc_imps_needed(tcx),
1078         is_pe_coff: tcx.sess.target.is_like_windows,
1079         target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1080         target_pointer_width: tcx.sess.target.pointer_width,
1081         target_arch: tcx.sess.target.arch.clone(),
1082         debuginfo: tcx.sess.opts.debuginfo,
1083         split_debuginfo: tcx.sess.split_debuginfo(),
1084     };
1085
1086     // This is the "main loop" of parallel work happening for parallel codegen.
1087     // It's here that we manage parallelism, schedule work, and work with
1088     // messages coming from clients.
1089     //
1090     // There are a few environmental pre-conditions that shape how the system
1091     // is set up:
1092     //
1093     // - Error reporting only can happen on the main thread because that's the
1094     //   only place where we have access to the compiler `Session`.
1095     // - LLVM work can be done on any thread.
1096     // - Codegen can only happen on the main thread.
1097     // - Each thread doing substantial work most be in possession of a `Token`
1098     //   from the `Jobserver`.
1099     // - The compiler process always holds one `Token`. Any additional `Tokens`
1100     //   have to be requested from the `Jobserver`.
1101     //
1102     // Error Reporting
1103     // ===============
1104     // The error reporting restriction is handled separately from the rest: We
1105     // set up a `SharedEmitter` the holds an open channel to the main thread.
1106     // When an error occurs on any thread, the shared emitter will send the
1107     // error message to the receiver main thread (`SharedEmitterMain`). The
1108     // main thread will periodically query this error message queue and emit
1109     // any error messages it has received. It might even abort compilation if
1110     // has received a fatal error. In this case we rely on all other threads
1111     // being torn down automatically with the main thread.
1112     // Since the main thread will often be busy doing codegen work, error
1113     // reporting will be somewhat delayed, since the message queue can only be
1114     // checked in between to work packages.
1115     //
1116     // Work Processing Infrastructure
1117     // ==============================
1118     // The work processing infrastructure knows three major actors:
1119     //
1120     // - the coordinator thread,
1121     // - the main thread, and
1122     // - LLVM worker threads
1123     //
1124     // The coordinator thread is running a message loop. It instructs the main
1125     // thread about what work to do when, and it will spawn off LLVM worker
1126     // threads as open LLVM WorkItems become available.
1127     //
1128     // The job of the main thread is to codegen CGUs into LLVM work package
1129     // (since the main thread is the only thread that can do this). The main
1130     // thread will block until it receives a message from the coordinator, upon
1131     // which it will codegen one CGU, send it to the coordinator and block
1132     // again. This way the coordinator can control what the main thread is
1133     // doing.
1134     //
1135     // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1136     // available, it will spawn off a new LLVM worker thread and let it process
1137     // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1138     // it will just shut down, which also frees all resources associated with
1139     // the given LLVM module, and sends a message to the coordinator that the
1140     // has been completed.
1141     //
1142     // Work Scheduling
1143     // ===============
1144     // The scheduler's goal is to minimize the time it takes to complete all
1145     // work there is, however, we also want to keep memory consumption low
1146     // if possible. These two goals are at odds with each other: If memory
1147     // consumption were not an issue, we could just let the main thread produce
1148     // LLVM WorkItems at full speed, assuring maximal utilization of
1149     // Tokens/LLVM worker threads. However, since codegen usual is faster
1150     // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1151     // WorkItem potentially holds on to a substantial amount of memory.
1152     //
1153     // So the actual goal is to always produce just enough LLVM WorkItems as
1154     // not to starve our LLVM worker threads. That means, once we have enough
1155     // WorkItems in our queue, we can block the main thread, so it does not
1156     // produce more until we need them.
1157     //
1158     // Doing LLVM Work on the Main Thread
1159     // ----------------------------------
1160     // Since the main thread owns the compiler processes implicit `Token`, it is
1161     // wasteful to keep it blocked without doing any work. Therefore, what we do
1162     // in this case is: We spawn off an additional LLVM worker thread that helps
1163     // reduce the queue. The work it is doing corresponds to the implicit
1164     // `Token`. The coordinator will mark the main thread as being busy with
1165     // LLVM work. (The actual work happens on another OS thread but we just care
1166     // about `Tokens`, not actual threads).
1167     //
1168     // When any LLVM worker thread finishes while the main thread is marked as
1169     // "busy with LLVM work", we can do a little switcheroo: We give the Token
1170     // of the just finished thread to the LLVM worker thread that is working on
1171     // behalf of the main thread's implicit Token, thus freeing up the main
1172     // thread again. The coordinator can then again decide what the main thread
1173     // should do. This allows the coordinator to make decisions at more points
1174     // in time.
1175     //
1176     // Striking a Balance between Throughput and Memory Consumption
1177     // ------------------------------------------------------------
1178     // Since our two goals, (1) use as many Tokens as possible and (2) keep
1179     // memory consumption as low as possible, are in conflict with each other,
1180     // we have to find a trade off between them. Right now, the goal is to keep
1181     // all workers busy, which means that no worker should find the queue empty
1182     // when it is ready to start.
1183     // How do we do achieve this? Good question :) We actually never know how
1184     // many `Tokens` are potentially available so it's hard to say how much to
1185     // fill up the queue before switching the main thread to LLVM work. Also we
1186     // currently don't have a means to estimate how long a running LLVM worker
1187     // will still be busy with it's current WorkItem. However, we know the
1188     // maximal count of available Tokens that makes sense (=the number of CPU
1189     // cores), so we can take a conservative guess. The heuristic we use here
1190     // is implemented in the `queue_full_enough()` function.
1191     //
1192     // Some Background on Jobservers
1193     // -----------------------------
1194     // It's worth also touching on the management of parallelism here. We don't
1195     // want to just spawn a thread per work item because while that's optimal
1196     // parallelism it may overload a system with too many threads or violate our
1197     // configuration for the maximum amount of cpu to use for this process. To
1198     // manage this we use the `jobserver` crate.
1199     //
1200     // Job servers are an artifact of GNU make and are used to manage
1201     // parallelism between processes. A jobserver is a glorified IPC semaphore
1202     // basically. Whenever we want to run some work we acquire the semaphore,
1203     // and whenever we're done with that work we release the semaphore. In this
1204     // manner we can ensure that the maximum number of parallel workers is
1205     // capped at any one point in time.
1206     //
1207     // LTO and the coordinator thread
1208     // ------------------------------
1209     //
1210     // The final job the coordinator thread is responsible for is managing LTO
1211     // and how that works. When LTO is requested what we'll to is collect all
1212     // optimized LLVM modules into a local vector on the coordinator. Once all
1213     // modules have been codegened and optimized we hand this to the `lto`
1214     // module for further optimization. The `lto` module will return back a list
1215     // of more modules to work on, which the coordinator will continue to spawn
1216     // work for.
1217     //
1218     // Each LLVM module is automatically sent back to the coordinator for LTO if
1219     // necessary. There's already optimizations in place to avoid sending work
1220     // back to the coordinator if LTO isn't requested.
1221     return thread::spawn(move || {
1222         let mut worker_id_counter = 0;
1223         let mut free_worker_ids = Vec::new();
1224         let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1225             if let Some(id) = free_worker_ids.pop() {
1226                 id
1227             } else {
1228                 let id = worker_id_counter;
1229                 worker_id_counter += 1;
1230                 id
1231             }
1232         };
1233
1234         // This is where we collect codegen units that have gone all the way
1235         // through codegen and LLVM.
1236         let mut compiled_modules = vec![];
1237         let mut compiled_metadata_module = None;
1238         let mut compiled_allocator_module = None;
1239         let mut needs_link = Vec::new();
1240         let mut needs_fat_lto = Vec::new();
1241         let mut needs_thin_lto = Vec::new();
1242         let mut lto_import_only_modules = Vec::new();
1243         let mut started_lto = false;
1244         let mut codegen_aborted = false;
1245
1246         // This flag tracks whether all items have gone through codegens
1247         let mut codegen_done = false;
1248
1249         // This is the queue of LLVM work items that still need processing.
1250         let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1251
1252         // This are the Jobserver Tokens we currently hold. Does not include
1253         // the implicit Token the compiler process owns no matter what.
1254         let mut tokens = Vec::new();
1255
1256         let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1257         let mut running = 0;
1258
1259         let prof = &cgcx.prof;
1260         let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1261
1262         // Run the message loop while there's still anything that needs message
1263         // processing. Note that as soon as codegen is aborted we simply want to
1264         // wait for all existing work to finish, so many of the conditions here
1265         // only apply if codegen hasn't been aborted as they represent pending
1266         // work to be done.
1267         while !codegen_done
1268             || running > 0
1269             || (!codegen_aborted
1270                 && !(work_items.is_empty()
1271                     && needs_fat_lto.is_empty()
1272                     && needs_thin_lto.is_empty()
1273                     && lto_import_only_modules.is_empty()
1274                     && main_thread_worker_state == MainThreadWorkerState::Idle))
1275         {
1276             // While there are still CGUs to be codegened, the coordinator has
1277             // to decide how to utilize the compiler processes implicit Token:
1278             // For codegenning more CGU or for running them through LLVM.
1279             if !codegen_done {
1280                 if main_thread_worker_state == MainThreadWorkerState::Idle {
1281                     // Compute the number of workers that will be running once we've taken as many
1282                     // items from the work queue as we can, plus one for the main thread. It's not
1283                     // critically important that we use this instead of just `running`, but it
1284                     // prevents the `queue_full_enough` heuristic from fluctuating just because a
1285                     // worker finished up and we decreased the `running` count, even though we're
1286                     // just going to increase it right after this when we put a new worker to work.
1287                     let extra_tokens = tokens.len().checked_sub(running).unwrap();
1288                     let additional_running = std::cmp::min(extra_tokens, work_items.len());
1289                     let anticipated_running = running + additional_running + 1;
1290
1291                     if !queue_full_enough(work_items.len(), anticipated_running) {
1292                         // The queue is not full enough, codegen more items:
1293                         if codegen_worker_send.send(Message::CodegenItem).is_err() {
1294                             panic!("Could not send Message::CodegenItem to main thread")
1295                         }
1296                         main_thread_worker_state = MainThreadWorkerState::Codegenning;
1297                     } else {
1298                         // The queue is full enough to not let the worker
1299                         // threads starve. Use the implicit Token to do some
1300                         // LLVM work too.
1301                         let (item, _) =
1302                             work_items.pop().expect("queue empty - queue_full_enough() broken?");
1303                         let cgcx = CodegenContext {
1304                             worker: get_worker_id(&mut free_worker_ids),
1305                             ..cgcx.clone()
1306                         };
1307                         maybe_start_llvm_timer(
1308                             prof,
1309                             cgcx.config(item.module_kind()),
1310                             &mut llvm_start_time,
1311                         );
1312                         main_thread_worker_state = MainThreadWorkerState::LLVMing;
1313                         spawn_work(cgcx, item);
1314                     }
1315                 }
1316             } else if codegen_aborted {
1317                 // don't queue up any more work if codegen was aborted, we're
1318                 // just waiting for our existing children to finish
1319             } else {
1320                 // If we've finished everything related to normal codegen
1321                 // then it must be the case that we've got some LTO work to do.
1322                 // Perform the serial work here of figuring out what we're
1323                 // going to LTO and then push a bunch of work items onto our
1324                 // queue to do LTO
1325                 if work_items.is_empty()
1326                     && running == 0
1327                     && main_thread_worker_state == MainThreadWorkerState::Idle
1328                 {
1329                     assert!(!started_lto);
1330                     started_lto = true;
1331
1332                     let needs_fat_lto = mem::take(&mut needs_fat_lto);
1333                     let needs_thin_lto = mem::take(&mut needs_thin_lto);
1334                     let import_only_modules = mem::take(&mut lto_import_only_modules);
1335
1336                     for (work, cost) in
1337                         generate_lto_work(&cgcx, needs_fat_lto, needs_thin_lto, import_only_modules)
1338                     {
1339                         let insertion_index = work_items
1340                             .binary_search_by_key(&cost, |&(_, cost)| cost)
1341                             .unwrap_or_else(|e| e);
1342                         work_items.insert(insertion_index, (work, cost));
1343                         if !cgcx.opts.debugging_opts.no_parallel_llvm {
1344                             helper.request_token();
1345                         }
1346                     }
1347                 }
1348
1349                 // In this branch, we know that everything has been codegened,
1350                 // so it's just a matter of determining whether the implicit
1351                 // Token is free to use for LLVM work.
1352                 match main_thread_worker_state {
1353                     MainThreadWorkerState::Idle => {
1354                         if let Some((item, _)) = work_items.pop() {
1355                             let cgcx = CodegenContext {
1356                                 worker: get_worker_id(&mut free_worker_ids),
1357                                 ..cgcx.clone()
1358                             };
1359                             maybe_start_llvm_timer(
1360                                 prof,
1361                                 cgcx.config(item.module_kind()),
1362                                 &mut llvm_start_time,
1363                             );
1364                             main_thread_worker_state = MainThreadWorkerState::LLVMing;
1365                             spawn_work(cgcx, item);
1366                         } else {
1367                             // There is no unstarted work, so let the main thread
1368                             // take over for a running worker. Otherwise the
1369                             // implicit token would just go to waste.
1370                             // We reduce the `running` counter by one. The
1371                             // `tokens.truncate()` below will take care of
1372                             // giving the Token back.
1373                             debug_assert!(running > 0);
1374                             running -= 1;
1375                             main_thread_worker_state = MainThreadWorkerState::LLVMing;
1376                         }
1377                     }
1378                     MainThreadWorkerState::Codegenning => bug!(
1379                         "codegen worker should not be codegenning after \
1380                               codegen was already completed"
1381                     ),
1382                     MainThreadWorkerState::LLVMing => {
1383                         // Already making good use of that token
1384                     }
1385                 }
1386             }
1387
1388             // Spin up what work we can, only doing this while we've got available
1389             // parallelism slots and work left to spawn.
1390             while !codegen_aborted && !work_items.is_empty() && running < tokens.len() {
1391                 let (item, _) = work_items.pop().unwrap();
1392
1393                 maybe_start_llvm_timer(prof, cgcx.config(item.module_kind()), &mut llvm_start_time);
1394
1395                 let cgcx =
1396                     CodegenContext { worker: get_worker_id(&mut free_worker_ids), ..cgcx.clone() };
1397
1398                 spawn_work(cgcx, item);
1399                 running += 1;
1400             }
1401
1402             // Relinquish accidentally acquired extra tokens
1403             tokens.truncate(running);
1404
1405             // If a thread exits successfully then we drop a token associated
1406             // with that worker and update our `running` count. We may later
1407             // re-acquire a token to continue running more work. We may also not
1408             // actually drop a token here if the worker was running with an
1409             // "ephemeral token"
1410             let mut free_worker = |worker_id| {
1411                 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1412                     main_thread_worker_state = MainThreadWorkerState::Idle;
1413                 } else {
1414                     running -= 1;
1415                 }
1416
1417                 free_worker_ids.push(worker_id);
1418             };
1419
1420             let msg = coordinator_receive.recv().unwrap();
1421             match *msg.downcast::<Message<B>>().ok().unwrap() {
1422                 // Save the token locally and the next turn of the loop will use
1423                 // this to spawn a new unit of work, or it may get dropped
1424                 // immediately if we have no more work to spawn.
1425                 Message::Token(token) => {
1426                     match token {
1427                         Ok(token) => {
1428                             tokens.push(token);
1429
1430                             if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1431                                 // If the main thread token is used for LLVM work
1432                                 // at the moment, we turn that thread into a regular
1433                                 // LLVM worker thread, so the main thread is free
1434                                 // to react to codegen demand.
1435                                 main_thread_worker_state = MainThreadWorkerState::Idle;
1436                                 running += 1;
1437                             }
1438                         }
1439                         Err(e) => {
1440                             let msg = &format!("failed to acquire jobserver token: {}", e);
1441                             shared_emitter.fatal(msg);
1442                             // Exit the coordinator thread
1443                             panic!("{}", msg)
1444                         }
1445                     }
1446                 }
1447
1448                 Message::CodegenDone { llvm_work_item, cost } => {
1449                     // We keep the queue sorted by estimated processing cost,
1450                     // so that more expensive items are processed earlier. This
1451                     // is good for throughput as it gives the main thread more
1452                     // time to fill up the queue and it avoids scheduling
1453                     // expensive items to the end.
1454                     // Note, however, that this is not ideal for memory
1455                     // consumption, as LLVM module sizes are not evenly
1456                     // distributed.
1457                     let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1458                     let insertion_index = match insertion_index {
1459                         Ok(idx) | Err(idx) => idx,
1460                     };
1461                     work_items.insert(insertion_index, (llvm_work_item, cost));
1462
1463                     if !cgcx.opts.debugging_opts.no_parallel_llvm {
1464                         helper.request_token();
1465                     }
1466                     assert!(!codegen_aborted);
1467                     assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1468                     main_thread_worker_state = MainThreadWorkerState::Idle;
1469                 }
1470
1471                 Message::CodegenComplete => {
1472                     codegen_done = true;
1473                     assert!(!codegen_aborted);
1474                     assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1475                     main_thread_worker_state = MainThreadWorkerState::Idle;
1476                 }
1477
1478                 // If codegen is aborted that means translation was aborted due
1479                 // to some normal-ish compiler error. In this situation we want
1480                 // to exit as soon as possible, but we want to make sure all
1481                 // existing work has finished. Flag codegen as being done, and
1482                 // then conditions above will ensure no more work is spawned but
1483                 // we'll keep executing this loop until `running` hits 0.
1484                 Message::CodegenAborted => {
1485                     assert!(!codegen_aborted);
1486                     codegen_done = true;
1487                     codegen_aborted = true;
1488                     assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1489                 }
1490                 Message::Done { result: Ok(compiled_module), worker_id } => {
1491                     free_worker(worker_id);
1492                     match compiled_module.kind {
1493                         ModuleKind::Regular => {
1494                             compiled_modules.push(compiled_module);
1495                         }
1496                         ModuleKind::Metadata => {
1497                             assert!(compiled_metadata_module.is_none());
1498                             compiled_metadata_module = Some(compiled_module);
1499                         }
1500                         ModuleKind::Allocator => {
1501                             assert!(compiled_allocator_module.is_none());
1502                             compiled_allocator_module = Some(compiled_module);
1503                         }
1504                     }
1505                 }
1506                 Message::NeedsLink { module, worker_id } => {
1507                     free_worker(worker_id);
1508                     needs_link.push(module);
1509                 }
1510                 Message::NeedsFatLTO { result, worker_id } => {
1511                     assert!(!started_lto);
1512                     free_worker(worker_id);
1513                     needs_fat_lto.push(result);
1514                 }
1515                 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1516                     assert!(!started_lto);
1517                     free_worker(worker_id);
1518                     needs_thin_lto.push((name, thin_buffer));
1519                 }
1520                 Message::AddImportOnlyModule { module_data, work_product } => {
1521                     assert!(!started_lto);
1522                     assert!(!codegen_done);
1523                     assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1524                     lto_import_only_modules.push((module_data, work_product));
1525                     main_thread_worker_state = MainThreadWorkerState::Idle;
1526                 }
1527                 // If the thread failed that means it panicked, so we abort immediately.
1528                 Message::Done { result: Err(None), worker_id: _ } => {
1529                     bug!("worker thread panicked");
1530                 }
1531                 Message::Done { result: Err(Some(WorkerFatalError)), worker_id: _ } => {
1532                     return Err(());
1533                 }
1534                 Message::CodegenItem => bug!("the coordinator should not receive codegen requests"),
1535             }
1536         }
1537
1538         let needs_link = mem::take(&mut needs_link);
1539         if !needs_link.is_empty() {
1540             assert!(compiled_modules.is_empty());
1541             let diag_handler = cgcx.create_diag_handler();
1542             let module = B::run_link(&cgcx, &diag_handler, needs_link).map_err(|_| ())?;
1543             let module = unsafe {
1544                 B::codegen(&cgcx, &diag_handler, module, cgcx.config(ModuleKind::Regular))
1545                     .map_err(|_| ())?
1546             };
1547             compiled_modules.push(module);
1548         }
1549
1550         // Drop to print timings
1551         drop(llvm_start_time);
1552
1553         // Regardless of what order these modules completed in, report them to
1554         // the backend in the same order every time to ensure that we're handing
1555         // out deterministic results.
1556         compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1557
1558         Ok(CompiledModules {
1559             modules: compiled_modules,
1560             metadata_module: compiled_metadata_module,
1561             allocator_module: compiled_allocator_module,
1562         })
1563     });
1564
1565     // A heuristic that determines if we have enough LLVM WorkItems in the
1566     // queue so that the main thread can do LLVM work instead of codegen
1567     fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1568         // This heuristic scales ahead-of-time codegen according to available
1569         // concurrency, as measured by `workers_running`. The idea is that the
1570         // more concurrency we have available, the more demand there will be for
1571         // work items, and the fuller the queue should be kept to meet demand.
1572         // An important property of this approach is that we codegen ahead of
1573         // time only as much as necessary, so as to keep fewer LLVM modules in
1574         // memory at once, thereby reducing memory consumption.
1575         //
1576         // When the number of workers running is less than the max concurrency
1577         // available to us, this heuristic can cause us to instruct the main
1578         // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1579         // of codegen, even though it seems like it *should* be codegenning so
1580         // that we can create more work items and spawn more LLVM workers.
1581         //
1582         // But this is not a problem. When the main thread is told to LLVM,
1583         // according to this heuristic and how work is scheduled, there is
1584         // always at least one item in the queue, and therefore at least one
1585         // pending jobserver token request. If there *is* more concurrency
1586         // available, we will immediately receive a token, which will upgrade
1587         // the main thread's LLVM worker to a real one (conceptually), and free
1588         // up the main thread to codegen if necessary. On the other hand, if
1589         // there isn't more concurrency, then the main thread working on an LLVM
1590         // item is appropriate, as long as the queue is full enough for demand.
1591         //
1592         // Speaking of which, how full should we keep the queue? Probably less
1593         // full than you'd think. A lot has to go wrong for the queue not to be
1594         // full enough and for that to have a negative effect on compile times.
1595         //
1596         // Workers are unlikely to finish at exactly the same time, so when one
1597         // finishes and takes another work item off the queue, we often have
1598         // ample time to codegen at that point before the next worker finishes.
1599         // But suppose that codegen takes so long that the workers exhaust the
1600         // queue, and we have one or more workers that have nothing to work on.
1601         // Well, it might not be so bad. Of all the LLVM modules we create and
1602         // optimize, one has to finish last. It's not necessarily the case that
1603         // by losing some concurrency for a moment, we delay the point at which
1604         // that last LLVM module is finished and the rest of compilation can
1605         // proceed. Also, when we can't take advantage of some concurrency, we
1606         // give tokens back to the job server. That enables some other rustc to
1607         // potentially make use of the available concurrency. That could even
1608         // *decrease* overall compile time if we're lucky. But yes, if no other
1609         // rustc can make use of the concurrency, then we've squandered it.
1610         //
1611         // However, keeping the queue full is also beneficial when we have a
1612         // surge in available concurrency. Then items can be taken from the
1613         // queue immediately, without having to wait for codegen.
1614         //
1615         // So, the heuristic below tries to keep one item in the queue for every
1616         // four running workers. Based on limited benchmarking, this appears to
1617         // be more than sufficient to avoid increasing compilation times.
1618         let quarter_of_workers = workers_running - 3 * workers_running / 4;
1619         items_in_queue > 0 && items_in_queue >= quarter_of_workers
1620     }
1621
1622     fn maybe_start_llvm_timer<'a>(
1623         prof: &'a SelfProfilerRef,
1624         config: &ModuleConfig,
1625         llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1626     ) {
1627         if config.time_module && llvm_start_time.is_none() {
1628             *llvm_start_time = Some(prof.extra_verbose_generic_activity("LLVM_passes", "crate"));
1629         }
1630     }
1631 }
1632
1633 /// `FatalError` is explicitly not `Send`.
1634 #[must_use]
1635 pub struct WorkerFatalError;
1636
1637 fn spawn_work<B: ExtraBackendMethods>(cgcx: CodegenContext<B>, work: WorkItem<B>) {
1638     let builder = thread::Builder::new().name(work.short_description());
1639     builder
1640         .spawn(move || {
1641             // Set up a destructor which will fire off a message that we're done as
1642             // we exit.
1643             struct Bomb<B: ExtraBackendMethods> {
1644                 coordinator_send: Sender<Box<dyn Any + Send>>,
1645                 result: Option<Result<WorkItemResult<B>, FatalError>>,
1646                 worker_id: usize,
1647             }
1648             impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1649                 fn drop(&mut self) {
1650                     let worker_id = self.worker_id;
1651                     let msg = match self.result.take() {
1652                         Some(Ok(WorkItemResult::Compiled(m))) => {
1653                             Message::Done::<B> { result: Ok(m), worker_id }
1654                         }
1655                         Some(Ok(WorkItemResult::NeedsLink(m))) => {
1656                             Message::NeedsLink::<B> { module: m, worker_id }
1657                         }
1658                         Some(Ok(WorkItemResult::NeedsFatLTO(m))) => {
1659                             Message::NeedsFatLTO::<B> { result: m, worker_id }
1660                         }
1661                         Some(Ok(WorkItemResult::NeedsThinLTO(name, thin_buffer))) => {
1662                             Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1663                         }
1664                         Some(Err(FatalError)) => {
1665                             Message::Done::<B> { result: Err(Some(WorkerFatalError)), worker_id }
1666                         }
1667                         None => Message::Done::<B> { result: Err(None), worker_id },
1668                     };
1669                     drop(self.coordinator_send.send(Box::new(msg)));
1670                 }
1671             }
1672
1673             let mut bomb = Bomb::<B> {
1674                 coordinator_send: cgcx.coordinator_send.clone(),
1675                 result: None,
1676                 worker_id: cgcx.worker,
1677             };
1678
1679             // Execute the work itself, and if it finishes successfully then flag
1680             // ourselves as a success as well.
1681             //
1682             // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1683             // as a diagnostic was already sent off to the main thread - just
1684             // surface that there was an error in this worker.
1685             bomb.result = {
1686                 let _prof_timer = work.start_profiling(&cgcx);
1687                 Some(execute_work_item(&cgcx, work))
1688             };
1689         })
1690         .expect("failed to spawn thread");
1691 }
1692
1693 enum SharedEmitterMessage {
1694     Diagnostic(Diagnostic),
1695     InlineAsmError(u32, String, Level, Option<(String, Vec<InnerSpan>)>),
1696     AbortIfErrors,
1697     Fatal(String),
1698 }
1699
1700 #[derive(Clone)]
1701 pub struct SharedEmitter {
1702     sender: Sender<SharedEmitterMessage>,
1703 }
1704
1705 pub struct SharedEmitterMain {
1706     receiver: Receiver<SharedEmitterMessage>,
1707 }
1708
1709 impl SharedEmitter {
1710     pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1711         let (sender, receiver) = channel();
1712
1713         (SharedEmitter { sender }, SharedEmitterMain { receiver })
1714     }
1715
1716     pub fn inline_asm_error(
1717         &self,
1718         cookie: u32,
1719         msg: String,
1720         level: Level,
1721         source: Option<(String, Vec<InnerSpan>)>,
1722     ) {
1723         drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)));
1724     }
1725
1726     pub fn fatal(&self, msg: &str) {
1727         drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1728     }
1729 }
1730
1731 impl Emitter for SharedEmitter {
1732     fn emit_diagnostic(&mut self, diag: &rustc_errors::Diagnostic) {
1733         drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1734             msg: diag.message(),
1735             code: diag.code.clone(),
1736             lvl: diag.level,
1737         })));
1738         for child in &diag.children {
1739             drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1740                 msg: child.message(),
1741                 code: None,
1742                 lvl: child.level,
1743             })));
1744         }
1745         drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1746     }
1747     fn source_map(&self) -> Option<&Lrc<SourceMap>> {
1748         None
1749     }
1750 }
1751
1752 impl SharedEmitterMain {
1753     pub fn check(&self, sess: &Session, blocking: bool) {
1754         loop {
1755             let message = if blocking {
1756                 match self.receiver.recv() {
1757                     Ok(message) => Ok(message),
1758                     Err(_) => Err(()),
1759                 }
1760             } else {
1761                 match self.receiver.try_recv() {
1762                     Ok(message) => Ok(message),
1763                     Err(_) => Err(()),
1764                 }
1765             };
1766
1767             match message {
1768                 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1769                     let handler = sess.diagnostic();
1770                     let mut d = rustc_errors::Diagnostic::new(diag.lvl, &diag.msg);
1771                     if let Some(code) = diag.code {
1772                         d.code(code);
1773                     }
1774                     handler.emit_diagnostic(&d);
1775                 }
1776                 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => {
1777                     let msg = msg.strip_prefix("error: ").unwrap_or(&msg);
1778
1779                     let mut err = match level {
1780                         Level::Error => sess.struct_err(&msg),
1781                         Level::Warning => sess.struct_warn(&msg),
1782                         Level::Note => sess.struct_note_without_error(&msg),
1783                         _ => bug!("Invalid inline asm diagnostic level"),
1784                     };
1785
1786                     // If the cookie is 0 then we don't have span information.
1787                     if cookie != 0 {
1788                         let pos = BytePos::from_u32(cookie);
1789                         let span = Span::with_root_ctxt(pos, pos);
1790                         err.set_span(span);
1791                     };
1792
1793                     // Point to the generated assembly if it is available.
1794                     if let Some((buffer, spans)) = source {
1795                         let source = sess
1796                             .source_map()
1797                             .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
1798                         let source_span = Span::with_root_ctxt(source.start_pos, source.end_pos);
1799                         let spans: Vec<_> =
1800                             spans.iter().map(|sp| source_span.from_inner(*sp)).collect();
1801                         err.span_note(spans, "instantiated into assembly here");
1802                     }
1803
1804                     err.emit();
1805                 }
1806                 Ok(SharedEmitterMessage::AbortIfErrors) => {
1807                     sess.abort_if_errors();
1808                 }
1809                 Ok(SharedEmitterMessage::Fatal(msg)) => {
1810                     sess.fatal(&msg);
1811                 }
1812                 Err(_) => {
1813                     break;
1814                 }
1815             }
1816         }
1817     }
1818 }
1819
1820 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1821     pub backend: B,
1822     pub crate_name: Symbol,
1823     pub metadata: EncodedMetadata,
1824     pub windows_subsystem: Option<String>,
1825     pub linker_info: LinkerInfo,
1826     pub crate_info: CrateInfo,
1827     pub coordinator_send: Sender<Box<dyn Any + Send>>,
1828     pub codegen_worker_receive: Receiver<Message<B>>,
1829     pub shared_emitter_main: SharedEmitterMain,
1830     pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1831     pub output_filenames: Arc<OutputFilenames>,
1832 }
1833
1834 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1835     pub fn join(self, sess: &Session) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1836         let _timer = sess.timer("finish_ongoing_codegen");
1837
1838         self.shared_emitter_main.check(sess, true);
1839         let future = self.future;
1840         let compiled_modules = sess.time("join_worker_thread", || match future.join() {
1841             Ok(Ok(compiled_modules)) => compiled_modules,
1842             Ok(Err(())) => {
1843                 sess.abort_if_errors();
1844                 panic!("expected abort due to worker thread errors")
1845             }
1846             Err(_) => {
1847                 bug!("panic during codegen/LLVM phase");
1848             }
1849         });
1850
1851         sess.cgu_reuse_tracker.check_expected_reuse(sess.diagnostic());
1852
1853         sess.abort_if_errors();
1854
1855         let work_products =
1856             copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
1857         produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
1858
1859         // FIXME: time_llvm_passes support - does this use a global context or
1860         // something?
1861         if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1862             self.backend.print_pass_timings()
1863         }
1864
1865         (
1866             CodegenResults {
1867                 crate_name: self.crate_name,
1868                 metadata: self.metadata,
1869                 windows_subsystem: self.windows_subsystem,
1870                 linker_info: self.linker_info,
1871                 crate_info: self.crate_info,
1872
1873                 modules: compiled_modules.modules,
1874                 allocator_module: compiled_modules.allocator_module,
1875                 metadata_module: compiled_modules.metadata_module,
1876             },
1877             work_products,
1878         )
1879     }
1880
1881     pub fn submit_pre_codegened_module_to_llvm(
1882         &self,
1883         tcx: TyCtxt<'_>,
1884         module: ModuleCodegen<B::Module>,
1885     ) {
1886         self.wait_for_signal_to_codegen_item();
1887         self.check_for_errors(tcx.sess);
1888
1889         // These are generally cheap and won't throw off scheduling.
1890         let cost = 0;
1891         submit_codegened_module_to_llvm(&self.backend, &self.coordinator_send, module, cost);
1892     }
1893
1894     pub fn codegen_finished(&self, tcx: TyCtxt<'_>) {
1895         self.wait_for_signal_to_codegen_item();
1896         self.check_for_errors(tcx.sess);
1897         drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1898     }
1899
1900     /// Consumes this context indicating that codegen was entirely aborted, and
1901     /// we need to exit as quickly as possible.
1902     ///
1903     /// This method blocks the current thread until all worker threads have
1904     /// finished, and all worker threads should have exited or be real close to
1905     /// exiting at this point.
1906     pub fn codegen_aborted(self) {
1907         // Signal to the coordinator it should spawn no more work and start
1908         // shutdown.
1909         drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1910         drop(self.future.join());
1911     }
1912
1913     pub fn check_for_errors(&self, sess: &Session) {
1914         self.shared_emitter_main.check(sess, false);
1915     }
1916
1917     pub fn wait_for_signal_to_codegen_item(&self) {
1918         match self.codegen_worker_receive.recv() {
1919             Ok(Message::CodegenItem) => {
1920                 // Nothing to do
1921             }
1922             Ok(_) => panic!("unexpected message"),
1923             Err(_) => {
1924                 // One of the LLVM threads must have panicked, fall through so
1925                 // error handling can be reached.
1926             }
1927         }
1928     }
1929 }
1930
1931 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1932     _backend: &B,
1933     tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1934     module: ModuleCodegen<B::Module>,
1935     cost: u64,
1936 ) {
1937     let llvm_work_item = WorkItem::Optimize(module);
1938     drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost })));
1939 }
1940
1941 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1942     _backend: &B,
1943     tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1944     module: CachedModuleCodegen,
1945 ) {
1946     let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1947     drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost: 0 })));
1948 }
1949
1950 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1951     _backend: &B,
1952     tcx: TyCtxt<'_>,
1953     tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1954     module: CachedModuleCodegen,
1955 ) {
1956     let filename = pre_lto_bitcode_filename(&module.name);
1957     let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1958     let file = fs::File::open(&bc_path)
1959         .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
1960
1961     let mmap = unsafe {
1962         Mmap::map(file).unwrap_or_else(|e| {
1963             panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1964         })
1965     };
1966     // Schedule the module to be loaded
1967     drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule::<B> {
1968         module_data: SerializedModule::FromUncompressedFile(mmap),
1969         work_product: module.source,
1970     })));
1971 }
1972
1973 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1974     format!("{}.{}", module_name, PRE_LTO_BC_EXT)
1975 }
1976
1977 fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
1978     // This should never be true (because it's not supported). If it is true,
1979     // something is wrong with commandline arg validation.
1980     assert!(
1981         !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
1982             && tcx.sess.target.is_like_windows
1983             && tcx.sess.opts.cg.prefer_dynamic)
1984     );
1985
1986     tcx.sess.target.is_like_windows &&
1987         tcx.sess.crate_types().iter().any(|ct| *ct == CrateType::Rlib) &&
1988     // ThinLTO can't handle this workaround in all cases, so we don't
1989     // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
1990     // dynamic linking when linker plugin LTO is enabled.
1991     !tcx.sess.opts.cg.linker_plugin_lto.enabled()
1992 }