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