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