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