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