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