]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/back/write.rs
Auto merge of #53830 - davidtwco:issue-53228, r=nikomatsakis
[rust.git] / src / librustc_codegen_llvm / back / write.rs
1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use attributes;
12 use back::bytecode::{self, RLIB_BYTECODE_EXTENSION};
13 use back::lto::{self, ModuleBuffer, ThinBuffer, SerializedModule};
14 use back::link::{self, get_linker, remove};
15 use back::command::Command;
16 use back::linker::LinkerInfo;
17 use back::symbol_export::ExportedSymbols;
18 use base;
19 use consts;
20 use memmap;
21 use rustc_incremental::{copy_cgu_workproducts_to_incr_comp_cache_dir,
22                         in_incr_comp_dir, in_incr_comp_dir_sess};
23 use rustc::dep_graph::{WorkProduct, WorkProductId, WorkProductFileKind};
24 use rustc::middle::cstore::EncodedMetadata;
25 use rustc::session::config::{self, OutputFilenames, OutputType, Passes, Sanitizer, Lto};
26 use rustc::session::Session;
27 use rustc::util::nodemap::FxHashMap;
28 use time_graph::{self, TimeGraph, Timeline};
29 use llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
30 use llvm_util;
31 use {CodegenResults, ModuleCodegen, CompiledModule, ModuleKind, // ModuleLlvm,
32      CachedModuleCodegen};
33 use CrateInfo;
34 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
35 use rustc::ty::TyCtxt;
36 use rustc::util::common::{time_ext, time_depth, set_time_depth, print_time_passes_entry};
37 use rustc_fs_util::{path2cstr, link_or_copy};
38 use rustc_data_structures::small_c_str::SmallCStr;
39 use rustc_data_structures::svh::Svh;
40 use errors::{self, Handler, Level, DiagnosticBuilder, FatalError, DiagnosticId};
41 use errors::emitter::{Emitter};
42 use syntax::attr;
43 use syntax::ext::hygiene::Mark;
44 use syntax_pos::MultiSpan;
45 use syntax_pos::symbol::Symbol;
46 use type_::Type;
47 use context::{is_pie_binary, get_reloc_model};
48 use common::{C_bytes_in_context, val_ty};
49 use jobserver::{Client, Acquired};
50 use rustc_demangle;
51
52 use std::any::Any;
53 use std::ffi::{CString, CStr};
54 use std::fs;
55 use std::io::{self, Write};
56 use std::mem;
57 use std::path::{Path, PathBuf};
58 use std::str;
59 use std::sync::Arc;
60 use std::sync::mpsc::{channel, Sender, Receiver};
61 use std::slice;
62 use std::time::Instant;
63 use std::thread;
64 use libc::{c_uint, c_void, c_char, size_t};
65
66 pub const RELOC_MODEL_ARGS : [(&'static str, llvm::RelocMode); 7] = [
67     ("pic", llvm::RelocMode::PIC),
68     ("static", llvm::RelocMode::Static),
69     ("default", llvm::RelocMode::Default),
70     ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
71     ("ropi", llvm::RelocMode::ROPI),
72     ("rwpi", llvm::RelocMode::RWPI),
73     ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
74 ];
75
76 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
77     ("small", llvm::CodeModel::Small),
78     ("kernel", llvm::CodeModel::Kernel),
79     ("medium", llvm::CodeModel::Medium),
80     ("large", llvm::CodeModel::Large),
81 ];
82
83 pub const TLS_MODEL_ARGS : [(&'static str, llvm::ThreadLocalMode); 4] = [
84     ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
85     ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
86     ("initial-exec", llvm::ThreadLocalMode::InitialExec),
87     ("local-exec", llvm::ThreadLocalMode::LocalExec),
88 ];
89
90 const PRE_THIN_LTO_BC_EXT: &str = "pre-thin-lto.bc";
91
92 pub fn llvm_err(handler: &errors::Handler, msg: String) -> FatalError {
93     match llvm::last_error() {
94         Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
95         None => handler.fatal(&msg),
96     }
97 }
98
99 pub fn write_output_file(
100         handler: &errors::Handler,
101         target: &'ll llvm::TargetMachine,
102         pm: &llvm::PassManager<'ll>,
103         m: &'ll llvm::Module,
104         output: &Path,
105         file_type: llvm::FileType) -> Result<(), FatalError> {
106     unsafe {
107         let output_c = path2cstr(output);
108         let result = llvm::LLVMRustWriteOutputFile(
109                 target, pm, m, output_c.as_ptr(), file_type);
110         if result.into_result().is_err() {
111             let msg = format!("could not write output to {}", output.display());
112             Err(llvm_err(handler, msg))
113         } else {
114             Ok(())
115         }
116     }
117 }
118
119 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
120     match optimize {
121       config::OptLevel::No => llvm::CodeGenOptLevel::None,
122       config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
123       config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
124       config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
125       _ => llvm::CodeGenOptLevel::Default,
126     }
127 }
128
129 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
130     match optimize {
131       config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
132       config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
133       _ => llvm::CodeGenOptSizeNone,
134     }
135 }
136
137 pub fn create_target_machine(
138     sess: &Session,
139     find_features: bool,
140 ) -> &'static mut llvm::TargetMachine {
141     target_machine_factory(sess, find_features)().unwrap_or_else(|err| {
142         llvm_err(sess.diagnostic(), err).raise()
143     })
144 }
145
146 // If find_features is true this won't access `sess.crate_types` by assuming
147 // that `is_pie_binary` is false. When we discover LLVM target features
148 // `sess.crate_types` is uninitialized so we cannot access it.
149 pub fn target_machine_factory(sess: &Session, find_features: bool)
150     -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>
151 {
152     let reloc_model = get_reloc_model(sess);
153
154     let opt_level = get_llvm_opt_level(sess.opts.optimize);
155     let use_softfp = sess.opts.cg.soft_float;
156
157     let ffunction_sections = sess.target.target.options.function_sections;
158     let fdata_sections = ffunction_sections;
159
160     let code_model_arg = sess.opts.cg.code_model.as_ref().or(
161         sess.target.target.options.code_model.as_ref(),
162     );
163
164     let code_model = match code_model_arg {
165         Some(s) => {
166             match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
167                 Some(x) => x.1,
168                 _ => {
169                     sess.err(&format!("{:?} is not a valid code model",
170                                       code_model_arg));
171                     sess.abort_if_errors();
172                     bug!();
173                 }
174             }
175         }
176         None => llvm::CodeModel::None,
177     };
178
179     let features = attributes::llvm_target_features(sess).collect::<Vec<_>>();
180     let mut singlethread = sess.target.target.options.singlethread;
181
182     // On the wasm target once the `atomics` feature is enabled that means that
183     // we're no longer single-threaded, or otherwise we don't want LLVM to
184     // lower atomic operations to single-threaded operations.
185     if singlethread &&
186         sess.target.target.llvm_target.contains("wasm32") &&
187         features.iter().any(|s| *s == "+atomics")
188     {
189         singlethread = false;
190     }
191
192     let triple = SmallCStr::new(&sess.target.target.llvm_target);
193     let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
194     let features = features.join(",");
195     let features = CString::new(features).unwrap();
196     let is_pie_binary = !find_features && is_pie_binary(sess);
197     let trap_unreachable = sess.target.target.options.trap_unreachable;
198
199     let asm_comments = sess.asm_comments();
200
201     Arc::new(move || {
202         let tm = unsafe {
203             llvm::LLVMRustCreateTargetMachine(
204                 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
205                 code_model,
206                 reloc_model,
207                 opt_level,
208                 use_softfp,
209                 is_pie_binary,
210                 ffunction_sections,
211                 fdata_sections,
212                 trap_unreachable,
213                 singlethread,
214                 asm_comments,
215             )
216         };
217
218         tm.ok_or_else(|| {
219             format!("Could not create LLVM TargetMachine for triple: {}",
220                     triple.to_str().unwrap())
221         })
222     })
223 }
224
225 /// Module-specific configuration for `optimize_and_codegen`.
226 pub struct ModuleConfig {
227     /// Names of additional optimization passes to run.
228     passes: Vec<String>,
229     /// Some(level) to optimize at a certain level, or None to run
230     /// absolutely no optimizations (used for the metadata module).
231     pub opt_level: Option<llvm::CodeGenOptLevel>,
232
233     /// Some(level) to optimize binary size, or None to not affect program size.
234     opt_size: Option<llvm::CodeGenOptSize>,
235
236     pgo_gen: Option<String>,
237     pgo_use: String,
238
239     // Flags indicating which outputs to produce.
240     pub emit_pre_thin_lto_bc: bool,
241     emit_no_opt_bc: bool,
242     emit_bc: bool,
243     emit_bc_compressed: bool,
244     emit_lto_bc: bool,
245     emit_ir: bool,
246     emit_asm: bool,
247     emit_obj: bool,
248     // Miscellaneous flags.  These are mostly copied from command-line
249     // options.
250     pub verify_llvm_ir: bool,
251     no_prepopulate_passes: bool,
252     no_builtins: bool,
253     time_passes: bool,
254     vectorize_loop: bool,
255     vectorize_slp: bool,
256     merge_functions: bool,
257     inline_threshold: Option<usize>,
258     // Instead of creating an object file by doing LLVM codegen, just
259     // make the object file bitcode. Provides easy compatibility with
260     // emscripten's ecc compiler, when used as the linker.
261     obj_is_bitcode: bool,
262     no_integrated_as: bool,
263     embed_bitcode: bool,
264     embed_bitcode_marker: bool,
265 }
266
267 impl ModuleConfig {
268     fn new(passes: Vec<String>) -> ModuleConfig {
269         ModuleConfig {
270             passes,
271             opt_level: None,
272             opt_size: None,
273
274             pgo_gen: None,
275             pgo_use: String::new(),
276
277             emit_no_opt_bc: false,
278             emit_pre_thin_lto_bc: false,
279             emit_bc: false,
280             emit_bc_compressed: false,
281             emit_lto_bc: false,
282             emit_ir: false,
283             emit_asm: false,
284             emit_obj: false,
285             obj_is_bitcode: false,
286             embed_bitcode: false,
287             embed_bitcode_marker: false,
288             no_integrated_as: false,
289
290             verify_llvm_ir: false,
291             no_prepopulate_passes: false,
292             no_builtins: false,
293             time_passes: false,
294             vectorize_loop: false,
295             vectorize_slp: false,
296             merge_functions: false,
297             inline_threshold: None
298         }
299     }
300
301     fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
302         self.verify_llvm_ir = sess.verify_llvm_ir();
303         self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
304         self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
305         self.time_passes = sess.time_passes();
306         self.inline_threshold = sess.opts.cg.inline_threshold;
307         self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
308                               sess.opts.debugging_opts.cross_lang_lto.enabled();
309         let embed_bitcode = sess.target.target.options.embed_bitcode ||
310                             sess.opts.debugging_opts.embed_bitcode;
311         if embed_bitcode {
312             match sess.opts.optimize {
313                 config::OptLevel::No |
314                 config::OptLevel::Less => {
315                     self.embed_bitcode_marker = embed_bitcode;
316                 }
317                 _ => self.embed_bitcode = embed_bitcode,
318             }
319         }
320
321         // Copy what clang does by turning on loop vectorization at O2 and
322         // slp vectorization at O3. Otherwise configure other optimization aspects
323         // of this pass manager builder.
324         // Turn off vectorization for emscripten, as it's not very well supported.
325         self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
326                              (sess.opts.optimize == config::OptLevel::Default ||
327                               sess.opts.optimize == config::OptLevel::Aggressive) &&
328                              !sess.target.target.options.is_like_emscripten;
329
330         self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
331                             sess.opts.optimize == config::OptLevel::Aggressive &&
332                             !sess.target.target.options.is_like_emscripten;
333
334         self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
335                                sess.opts.optimize == config::OptLevel::Aggressive;
336     }
337 }
338
339 /// Assembler name and command used by codegen when no_integrated_as is enabled
340 struct AssemblerCommand {
341     name: PathBuf,
342     cmd: Command,
343 }
344
345 /// Additional resources used by optimize_and_codegen (not module specific)
346 #[derive(Clone)]
347 pub struct CodegenContext {
348     // Resources needed when running LTO
349     pub time_passes: bool,
350     pub lto: Lto,
351     pub no_landing_pads: bool,
352     pub save_temps: bool,
353     pub fewer_names: bool,
354     pub exported_symbols: Option<Arc<ExportedSymbols>>,
355     pub opts: Arc<config::Options>,
356     pub crate_types: Vec<config::CrateType>,
357     pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
358     output_filenames: Arc<OutputFilenames>,
359     regular_module_config: Arc<ModuleConfig>,
360     metadata_module_config: Arc<ModuleConfig>,
361     allocator_module_config: Arc<ModuleConfig>,
362     pub tm_factory: Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>,
363     pub msvc_imps_needed: bool,
364     pub target_pointer_width: String,
365     debuginfo: config::DebugInfo,
366
367     // Number of cgus excluding the allocator/metadata modules
368     pub total_cgus: usize,
369     // Handler to use for diagnostics produced during codegen.
370     pub diag_emitter: SharedEmitter,
371     // LLVM passes added by plugins.
372     pub plugin_passes: Vec<String>,
373     // LLVM optimizations for which we want to print remarks.
374     pub remark: Passes,
375     // Worker thread number
376     pub worker: usize,
377     // The incremental compilation session directory, or None if we are not
378     // compiling incrementally
379     pub incr_comp_session_dir: Option<PathBuf>,
380     // Channel back to the main control thread to send messages to
381     coordinator_send: Sender<Box<dyn Any + Send>>,
382     // A reference to the TimeGraph so we can register timings. None means that
383     // measuring is disabled.
384     time_graph: Option<TimeGraph>,
385     // The assembler command if no_integrated_as option is enabled, None otherwise
386     assembler_cmd: Option<Arc<AssemblerCommand>>,
387 }
388
389 impl CodegenContext {
390     pub fn create_diag_handler(&self) -> Handler {
391         Handler::with_emitter(true, false, Box::new(self.diag_emitter.clone()))
392     }
393
394     pub(crate) fn config(&self, kind: ModuleKind) -> &ModuleConfig {
395         match kind {
396             ModuleKind::Regular => &self.regular_module_config,
397             ModuleKind::Metadata => &self.metadata_module_config,
398             ModuleKind::Allocator => &self.allocator_module_config,
399         }
400     }
401
402     pub(crate) fn save_temp_bitcode(&self, module: &ModuleCodegen, name: &str) {
403         if !self.save_temps {
404             return
405         }
406         unsafe {
407             let ext = format!("{}.bc", name);
408             let cgu = Some(&module.name[..]);
409             let path = self.output_filenames.temp_path_ext(&ext, cgu);
410             let cstr = path2cstr(&path);
411             let llmod = module.module_llvm.llmod();
412             llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
413         }
414     }
415 }
416
417 pub struct DiagnosticHandlers<'a> {
418     data: *mut (&'a CodegenContext, &'a Handler),
419     llcx: &'a llvm::Context,
420 }
421
422 impl<'a> DiagnosticHandlers<'a> {
423     pub fn new(cgcx: &'a CodegenContext,
424                handler: &'a Handler,
425                llcx: &'a llvm::Context) -> Self {
426         let data = Box::into_raw(Box::new((cgcx, handler)));
427         unsafe {
428             llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data as *mut _);
429             llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data as *mut _);
430         }
431         DiagnosticHandlers { data, llcx }
432     }
433 }
434
435 impl<'a> Drop for DiagnosticHandlers<'a> {
436     fn drop(&mut self) {
437         use std::ptr::null_mut;
438         unsafe {
439             llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
440             llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
441             drop(Box::from_raw(self.data));
442         }
443     }
444 }
445
446 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext,
447                                                msg: &'b str,
448                                                cookie: c_uint) {
449     cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_string());
450 }
451
452 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
453                                         user: *const c_void,
454                                         cookie: c_uint) {
455     if user.is_null() {
456         return
457     }
458     let (cgcx, _) = *(user as *const (&CodegenContext, &Handler));
459
460     let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
461         .expect("non-UTF8 SMDiagnostic");
462
463     report_inline_asm(cgcx, &msg, cookie);
464 }
465
466 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
467     if user.is_null() {
468         return
469     }
470     let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler));
471
472     match llvm::diagnostic::Diagnostic::unpack(info) {
473         llvm::diagnostic::InlineAsm(inline) => {
474             report_inline_asm(cgcx,
475                               &llvm::twine_to_string(inline.message),
476                               inline.cookie);
477         }
478
479         llvm::diagnostic::Optimization(opt) => {
480             let enabled = match cgcx.remark {
481                 Passes::All => true,
482                 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
483             };
484
485             if enabled {
486                 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
487                                                 opt.kind.describe(),
488                                                 opt.pass_name,
489                                                 opt.filename,
490                                                 opt.line,
491                                                 opt.column,
492                                                 opt.message));
493             }
494         }
495         llvm::diagnostic::PGO(diagnostic_ref) |
496         llvm::diagnostic::Linker(diagnostic_ref) => {
497             let msg = llvm::build_string(|s| {
498                 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
499             }).expect("non-UTF8 diagnostic");
500             diag_handler.warn(&msg);
501         }
502         llvm::diagnostic::UnknownDiagnostic(..) => {},
503     }
504 }
505
506 // Unsafe due to LLVM calls.
507 unsafe fn optimize(cgcx: &CodegenContext,
508                    diag_handler: &Handler,
509                    module: &ModuleCodegen,
510                    config: &ModuleConfig,
511                    timeline: &mut Timeline)
512     -> Result<(), FatalError>
513 {
514     let llmod = module.module_llvm.llmod();
515     let llcx = &*module.module_llvm.llcx;
516     let tm = &*module.module_llvm.tm;
517     let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
518
519     let module_name = module.name.clone();
520     let module_name = Some(&module_name[..]);
521
522     if config.emit_no_opt_bc {
523         let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
524         let out = path2cstr(&out);
525         llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
526     }
527
528     if config.opt_level.is_some() {
529         // Create the two optimizing pass managers. These mirror what clang
530         // does, and are by populated by LLVM's default PassManagerBuilder.
531         // Each manager has a different set of passes, but they also share
532         // some common passes.
533         let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
534         let mpm = llvm::LLVMCreatePassManager();
535
536         {
537             // If we're verifying or linting, add them to the function pass
538             // manager.
539             let addpass = |pass_name: &str| {
540                 let pass_name = SmallCStr::new(pass_name);
541                 let pass = match llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr()) {
542                     Some(pass) => pass,
543                     None => return false,
544                 };
545                 let pass_manager = match llvm::LLVMRustPassKind(pass) {
546                     llvm::PassKind::Function => &*fpm,
547                     llvm::PassKind::Module => &*mpm,
548                     llvm::PassKind::Other => {
549                         diag_handler.err("Encountered LLVM pass kind we can't handle");
550                         return true
551                     },
552                 };
553                 llvm::LLVMRustAddPass(pass_manager, pass);
554                 true
555             };
556
557             if config.verify_llvm_ir { assert!(addpass("verify")); }
558
559             // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
560             // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
561             // we'll get errors in LLVM.
562             let using_thin_buffers = llvm::LLVMRustThinLTOAvailable() && (config.emit_bc
563                 || config.obj_is_bitcode || config.emit_bc_compressed || config.embed_bitcode);
564             let mut have_name_anon_globals_pass = false;
565             if !config.no_prepopulate_passes {
566                 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
567                 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
568                 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
569                 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal ||
570                     (cgcx.lto != Lto::Fat && cgcx.opts.debugging_opts.cross_lang_lto.enabled());
571                 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
572                 if using_thin_buffers && !prepare_for_thin_lto {
573                     assert!(addpass("name-anon-globals"));
574                     have_name_anon_globals_pass = true;
575                 }
576                 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
577                     llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
578                     llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
579                 })
580             }
581
582             for pass in &config.passes {
583                 if !addpass(pass) {
584                     diag_handler.warn(&format!("unknown pass `{}`, ignoring",
585                                             pass));
586                 }
587                 if pass == "name-anon-globals" {
588                     have_name_anon_globals_pass = true;
589                 }
590             }
591
592             for pass in &cgcx.plugin_passes {
593                 if !addpass(pass) {
594                     diag_handler.err(&format!("a plugin asked for LLVM pass \
595                                             `{}` but LLVM does not \
596                                             recognize it", pass));
597                 }
598                 if pass == "name-anon-globals" {
599                     have_name_anon_globals_pass = true;
600                 }
601             }
602
603             if using_thin_buffers && !have_name_anon_globals_pass {
604                 // As described above, this will probably cause an error in LLVM
605                 if config.no_prepopulate_passes {
606                     diag_handler.err("The current compilation is going to use thin LTO buffers \
607                                      without running LLVM's NameAnonGlobals pass. \
608                                      This will likely cause errors in LLVM. Consider adding \
609                                      -C passes=name-anon-globals to the compiler command line.");
610                 } else {
611                     bug!("We are using thin LTO buffers without running the NameAnonGlobals pass. \
612                          This will likely cause errors in LLVM and should never happen.");
613                 }
614             }
615         }
616
617         diag_handler.abort_if_errors();
618
619         // Finally, run the actual optimization passes
620         time_ext(config.time_passes,
621                  None,
622                  &format!("llvm function passes [{}]", module_name.unwrap()),
623                  || {
624             llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
625         });
626         timeline.record("fpm");
627         time_ext(config.time_passes,
628                  None,
629                  &format!("llvm module passes [{}]", module_name.unwrap()),
630                  || {
631             llvm::LLVMRunPassManager(mpm, llmod)
632         });
633
634         // Deallocate managers that we're now done with
635         llvm::LLVMDisposePassManager(fpm);
636         llvm::LLVMDisposePassManager(mpm);
637     }
638     Ok(())
639 }
640
641 fn generate_lto_work(cgcx: &CodegenContext,
642                      modules: Vec<ModuleCodegen>,
643                      import_only_modules: Vec<(SerializedModule, WorkProduct)>)
644     -> Vec<(WorkItem, u64)>
645 {
646     let mut timeline = cgcx.time_graph.as_ref().map(|tg| {
647         tg.start(CODEGEN_WORKER_TIMELINE,
648                  CODEGEN_WORK_PACKAGE_KIND,
649                  "generate lto")
650     }).unwrap_or(Timeline::noop());
651     let (lto_modules, copy_jobs) = lto::run(cgcx, modules, import_only_modules, &mut timeline)
652         .unwrap_or_else(|e| e.raise());
653
654     let lto_modules = lto_modules.into_iter().map(|module| {
655         let cost = module.cost();
656         (WorkItem::LTO(module), cost)
657     });
658
659     let copy_jobs = copy_jobs.into_iter().map(|wp| {
660         (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
661             name: wp.cgu_name.clone(),
662             source: wp,
663         }), 0)
664     });
665
666     lto_modules.chain(copy_jobs).collect()
667 }
668
669 unsafe fn codegen(cgcx: &CodegenContext,
670                   diag_handler: &Handler,
671                   module: ModuleCodegen,
672                   config: &ModuleConfig,
673                   timeline: &mut Timeline)
674     -> Result<CompiledModule, FatalError>
675 {
676     timeline.record("codegen");
677     {
678         let llmod = module.module_llvm.llmod();
679         let llcx = &*module.module_llvm.llcx;
680         let tm = &*module.module_llvm.tm;
681         let module_name = module.name.clone();
682         let module_name = Some(&module_name[..]);
683         let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
684
685         if cgcx.msvc_imps_needed {
686             create_msvc_imps(cgcx, llcx, llmod);
687         }
688
689         // A codegen-specific pass manager is used to generate object
690         // files for an LLVM module.
691         //
692         // Apparently each of these pass managers is a one-shot kind of
693         // thing, so we create a new one for each type of output. The
694         // pass manager passed to the closure should be ensured to not
695         // escape the closure itself, and the manager should only be
696         // used once.
697         unsafe fn with_codegen<'ll, F, R>(tm: &'ll llvm::TargetMachine,
698                                     llmod: &'ll llvm::Module,
699                                     no_builtins: bool,
700                                     f: F) -> R
701             where F: FnOnce(&'ll mut PassManager<'ll>) -> R,
702         {
703             let cpm = llvm::LLVMCreatePassManager();
704             llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
705             llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
706             f(cpm)
707         }
708
709         // If we don't have the integrated assembler, then we need to emit asm
710         // from LLVM and use `gcc` to create the object file.
711         let asm_to_obj = config.emit_obj && config.no_integrated_as;
712
713         // Change what we write and cleanup based on whether obj files are
714         // just llvm bitcode. In that case write bitcode, and possibly
715         // delete the bitcode if it wasn't requested. Don't generate the
716         // machine code, instead copy the .o file from the .bc
717         let write_bc = config.emit_bc || config.obj_is_bitcode;
718         let rm_bc = !config.emit_bc && config.obj_is_bitcode;
719         let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
720         let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
721
722         let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
723         let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
724
725
726         if write_bc || config.emit_bc_compressed || config.embed_bitcode {
727             let thin;
728             let old;
729             let data = if llvm::LLVMRustThinLTOAvailable() {
730                 thin = ThinBuffer::new(llmod);
731                 thin.data()
732             } else {
733                 old = ModuleBuffer::new(llmod);
734                 old.data()
735             };
736             timeline.record("make-bc");
737
738             if write_bc {
739                 if let Err(e) = fs::write(&bc_out, data) {
740                     diag_handler.err(&format!("failed to write bytecode: {}", e));
741                 }
742                 timeline.record("write-bc");
743             }
744
745             if config.embed_bitcode {
746                 embed_bitcode(cgcx, llcx, llmod, Some(data));
747                 timeline.record("embed-bc");
748             }
749
750             if config.emit_bc_compressed {
751                 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
752                 let data = bytecode::encode(&module.name, data);
753                 if let Err(e) = fs::write(&dst, data) {
754                     diag_handler.err(&format!("failed to write bytecode: {}", e));
755                 }
756                 timeline.record("compress-bc");
757             }
758         } else if config.embed_bitcode_marker {
759             embed_bitcode(cgcx, llcx, llmod, None);
760         }
761
762         time_ext(config.time_passes, None, &format!("codegen passes [{}]", module_name.unwrap()),
763             || -> Result<(), FatalError> {
764             if config.emit_ir {
765                 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
766                 let out = path2cstr(&out);
767
768                 extern "C" fn demangle_callback(input_ptr: *const c_char,
769                                                 input_len: size_t,
770                                                 output_ptr: *mut c_char,
771                                                 output_len: size_t) -> size_t {
772                     let input = unsafe {
773                         slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
774                     };
775
776                     let input = match str::from_utf8(input) {
777                         Ok(s) => s,
778                         Err(_) => return 0,
779                     };
780
781                     let output = unsafe {
782                         slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
783                     };
784                     let mut cursor = io::Cursor::new(output);
785
786                     let demangled = match rustc_demangle::try_demangle(input) {
787                         Ok(d) => d,
788                         Err(_) => return 0,
789                     };
790
791                     if let Err(_) = write!(cursor, "{:#}", demangled) {
792                         // Possible only if provided buffer is not big enough
793                         return 0;
794                     }
795
796                     cursor.position() as size_t
797                 }
798
799                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
800                     llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
801                     llvm::LLVMDisposePassManager(cpm);
802                 });
803                 timeline.record("ir");
804             }
805
806             if config.emit_asm || asm_to_obj {
807                 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
808
809                 // We can't use the same module for asm and binary output, because that triggers
810                 // various errors like invalid IR or broken binaries, so we might have to clone the
811                 // module to produce the asm output
812                 let llmod = if config.emit_obj {
813                     llvm::LLVMCloneModule(llmod)
814                 } else {
815                     llmod
816                 };
817                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
818                     write_output_file(diag_handler, tm, cpm, llmod, &path,
819                                     llvm::FileType::AssemblyFile)
820                 })?;
821                 timeline.record("asm");
822             }
823
824             if write_obj {
825                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
826                     write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
827                                     llvm::FileType::ObjectFile)
828                 })?;
829                 timeline.record("obj");
830             } else if asm_to_obj {
831                 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
832                 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
833                 timeline.record("asm_to_obj");
834
835                 if !config.emit_asm && !cgcx.save_temps {
836                     drop(fs::remove_file(&assembly));
837                 }
838             }
839
840             Ok(())
841         })?;
842
843         if copy_bc_to_obj {
844             debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
845             if let Err(e) = link_or_copy(&bc_out, &obj_out) {
846                 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
847             }
848         }
849
850         if rm_bc {
851             debug!("removing_bitcode {:?}", bc_out);
852             if let Err(e) = fs::remove_file(&bc_out) {
853                 diag_handler.err(&format!("failed to remove bitcode: {}", e));
854             }
855         }
856
857         drop(handlers);
858     }
859     Ok(module.into_compiled_module(config.emit_obj,
860                                    config.emit_bc,
861                                    config.emit_bc_compressed,
862                                    &cgcx.output_filenames))
863 }
864
865 /// Embed the bitcode of an LLVM module in the LLVM module itself.
866 ///
867 /// This is done primarily for iOS where it appears to be standard to compile C
868 /// code at least with `-fembed-bitcode` which creates two sections in the
869 /// executable:
870 ///
871 /// * __LLVM,__bitcode
872 /// * __LLVM,__cmdline
873 ///
874 /// It appears *both* of these sections are necessary to get the linker to
875 /// recognize what's going on. For us though we just always throw in an empty
876 /// cmdline section.
877 ///
878 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
879 /// embed an empty section.
880 ///
881 /// Basically all of this is us attempting to follow in the footsteps of clang
882 /// on iOS. See #35968 for lots more info.
883 unsafe fn embed_bitcode(cgcx: &CodegenContext,
884                         llcx: &llvm::Context,
885                         llmod: &llvm::Module,
886                         bitcode: Option<&[u8]>) {
887     let llconst = C_bytes_in_context(llcx, bitcode.unwrap_or(&[]));
888     let llglobal = llvm::LLVMAddGlobal(
889         llmod,
890         val_ty(llconst),
891         "rustc.embedded.module\0".as_ptr() as *const _,
892     );
893     llvm::LLVMSetInitializer(llglobal, llconst);
894
895     let is_apple = cgcx.opts.target_triple.triple().contains("-ios") ||
896                    cgcx.opts.target_triple.triple().contains("-darwin");
897
898     let section = if is_apple {
899         "__LLVM,__bitcode\0"
900     } else {
901         ".llvmbc\0"
902     };
903     llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
904     llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
905     llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
906
907     let llconst = C_bytes_in_context(llcx, &[]);
908     let llglobal = llvm::LLVMAddGlobal(
909         llmod,
910         val_ty(llconst),
911         "rustc.embedded.cmdline\0".as_ptr() as *const _,
912     );
913     llvm::LLVMSetInitializer(llglobal, llconst);
914     let section = if  is_apple {
915         "__LLVM,__cmdline\0"
916     } else {
917         ".llvmcmd\0"
918     };
919     llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
920     llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
921 }
922
923 pub(crate) struct CompiledModules {
924     pub modules: Vec<CompiledModule>,
925     pub metadata_module: CompiledModule,
926     pub allocator_module: Option<CompiledModule>,
927 }
928
929 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
930     sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
931     sess.opts.output_types.contains_key(&OutputType::Exe)
932 }
933
934 fn need_pre_thin_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
935     if sess.opts.incremental.is_none() {
936         return false
937     }
938
939     match sess.lto() {
940         Lto::Yes |
941         Lto::Fat |
942         Lto::No => false,
943         Lto::Thin |
944         Lto::ThinLocal => true,
945     }
946 }
947
948 pub fn start_async_codegen(tcx: TyCtxt,
949                                time_graph: Option<TimeGraph>,
950                                metadata: EncodedMetadata,
951                                coordinator_receive: Receiver<Box<dyn Any + Send>>,
952                                total_cgus: usize)
953                                -> OngoingCodegen {
954     let sess = tcx.sess;
955     let crate_name = tcx.crate_name(LOCAL_CRATE);
956     let crate_hash = tcx.crate_hash(LOCAL_CRATE);
957     let no_builtins = attr::contains_name(&tcx.hir.krate().attrs, "no_builtins");
958     let subsystem = attr::first_attr_value_str_by_name(&tcx.hir.krate().attrs,
959                                                        "windows_subsystem");
960     let windows_subsystem = subsystem.map(|subsystem| {
961         if subsystem != "windows" && subsystem != "console" {
962             tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
963                                      `windows` and `console` are allowed",
964                                     subsystem));
965         }
966         subsystem.to_string()
967     });
968
969     let linker_info = LinkerInfo::new(tcx);
970     let crate_info = CrateInfo::new(tcx);
971
972     // Figure out what we actually need to build.
973     let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
974     let mut metadata_config = ModuleConfig::new(vec![]);
975     let mut allocator_config = ModuleConfig::new(vec![]);
976
977     if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
978         match *sanitizer {
979             Sanitizer::Address => {
980                 modules_config.passes.push("asan".to_owned());
981                 modules_config.passes.push("asan-module".to_owned());
982             }
983             Sanitizer::Memory => {
984                 modules_config.passes.push("msan".to_owned())
985             }
986             Sanitizer::Thread => {
987                 modules_config.passes.push("tsan".to_owned())
988             }
989             _ => {}
990         }
991     }
992
993     if sess.opts.debugging_opts.profile {
994         modules_config.passes.push("insert-gcov-profiling".to_owned())
995     }
996
997     modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
998     modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
999
1000     modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
1001     modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
1002
1003     // Save all versions of the bytecode if we're saving our temporaries.
1004     if sess.opts.cg.save_temps {
1005         modules_config.emit_no_opt_bc = true;
1006         modules_config.emit_pre_thin_lto_bc = true;
1007         modules_config.emit_bc = true;
1008         modules_config.emit_lto_bc = true;
1009         metadata_config.emit_bc = true;
1010         allocator_config.emit_bc = true;
1011     }
1012
1013     // Emit compressed bitcode files for the crate if we're emitting an rlib.
1014     // Whenever an rlib is created, the bitcode is inserted into the archive in
1015     // order to allow LTO against it.
1016     if need_crate_bitcode_for_rlib(sess) {
1017         modules_config.emit_bc_compressed = true;
1018         allocator_config.emit_bc_compressed = true;
1019     }
1020
1021     modules_config.emit_pre_thin_lto_bc =
1022         need_pre_thin_lto_bitcode_for_incr_comp(sess);
1023
1024     modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
1025         tcx.sess.target.target.options.no_integrated_as;
1026
1027     for output_type in sess.opts.output_types.keys() {
1028         match *output_type {
1029             OutputType::Bitcode => { modules_config.emit_bc = true; }
1030             OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
1031             OutputType::Assembly => {
1032                 modules_config.emit_asm = true;
1033                 // If we're not using the LLVM assembler, this function
1034                 // could be invoked specially with output_type_assembly, so
1035                 // in this case we still want the metadata object file.
1036                 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
1037                     metadata_config.emit_obj = true;
1038                     allocator_config.emit_obj = true;
1039                 }
1040             }
1041             OutputType::Object => { modules_config.emit_obj = true; }
1042             OutputType::Metadata => { metadata_config.emit_obj = true; }
1043             OutputType::Exe => {
1044                 modules_config.emit_obj = true;
1045                 metadata_config.emit_obj = true;
1046                 allocator_config.emit_obj = true;
1047             },
1048             OutputType::Mir => {}
1049             OutputType::DepInfo => {}
1050         }
1051     }
1052
1053     modules_config.set_flags(sess, no_builtins);
1054     metadata_config.set_flags(sess, no_builtins);
1055     allocator_config.set_flags(sess, no_builtins);
1056
1057     // Exclude metadata and allocator modules from time_passes output, since
1058     // they throw off the "LLVM passes" measurement.
1059     metadata_config.time_passes = false;
1060     allocator_config.time_passes = false;
1061
1062     let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
1063     let (codegen_worker_send, codegen_worker_receive) = channel();
1064
1065     let coordinator_thread = start_executing_work(tcx,
1066                                                   &crate_info,
1067                                                   shared_emitter,
1068                                                   codegen_worker_send,
1069                                                   coordinator_receive,
1070                                                   total_cgus,
1071                                                   sess.jobserver.clone(),
1072                                                   time_graph.clone(),
1073                                                   Arc::new(modules_config),
1074                                                   Arc::new(metadata_config),
1075                                                   Arc::new(allocator_config));
1076
1077     OngoingCodegen {
1078         crate_name,
1079         crate_hash,
1080         metadata,
1081         windows_subsystem,
1082         linker_info,
1083         crate_info,
1084
1085         time_graph,
1086         coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
1087         codegen_worker_receive,
1088         shared_emitter_main,
1089         future: coordinator_thread,
1090         output_filenames: tcx.output_filenames(LOCAL_CRATE),
1091     }
1092 }
1093
1094 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
1095     sess: &Session,
1096     compiled_modules: &CompiledModules,
1097 ) -> FxHashMap<WorkProductId, WorkProduct> {
1098     let mut work_products = FxHashMap::default();
1099
1100     if sess.opts.incremental.is_none() {
1101         return work_products;
1102     }
1103
1104     for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
1105         let mut files = vec![];
1106
1107         if let Some(ref path) = module.object {
1108             files.push((WorkProductFileKind::Object, path.clone()));
1109         }
1110         if let Some(ref path) = module.bytecode {
1111             files.push((WorkProductFileKind::Bytecode, path.clone()));
1112         }
1113         if let Some(ref path) = module.bytecode_compressed {
1114             files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
1115         }
1116
1117         if let Some((id, product)) =
1118                 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
1119             work_products.insert(id, product);
1120         }
1121     }
1122
1123     work_products
1124 }
1125
1126 fn produce_final_output_artifacts(sess: &Session,
1127                                   compiled_modules: &CompiledModules,
1128                                   crate_output: &OutputFilenames) {
1129     let mut user_wants_bitcode = false;
1130     let mut user_wants_objects = false;
1131
1132     // Produce final compile outputs.
1133     let copy_gracefully = |from: &Path, to: &Path| {
1134         if let Err(e) = fs::copy(from, to) {
1135             sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
1136         }
1137     };
1138
1139     let copy_if_one_unit = |output_type: OutputType,
1140                             keep_numbered: bool| {
1141         if compiled_modules.modules.len() == 1 {
1142             // 1) Only one codegen unit.  In this case it's no difficulty
1143             //    to copy `foo.0.x` to `foo.x`.
1144             let module_name = Some(&compiled_modules.modules[0].name[..]);
1145             let path = crate_output.temp_path(output_type, module_name);
1146             copy_gracefully(&path,
1147                             &crate_output.path(output_type));
1148             if !sess.opts.cg.save_temps && !keep_numbered {
1149                 // The user just wants `foo.x`, not `foo.#module-name#.x`.
1150                 remove(sess, &path);
1151             }
1152         } else {
1153             let ext = crate_output.temp_path(output_type, None)
1154                                   .extension()
1155                                   .unwrap()
1156                                   .to_str()
1157                                   .unwrap()
1158                                   .to_owned();
1159
1160             if crate_output.outputs.contains_key(&output_type) {
1161                 // 2) Multiple codegen units, with `--emit foo=some_name`.  We have
1162                 //    no good solution for this case, so warn the user.
1163                 sess.warn(&format!("ignoring emit path because multiple .{} files \
1164                                     were produced", ext));
1165             } else if crate_output.single_output_file.is_some() {
1166                 // 3) Multiple codegen units, with `-o some_name`.  We have
1167                 //    no good solution for this case, so warn the user.
1168                 sess.warn(&format!("ignoring -o because multiple .{} files \
1169                                     were produced", ext));
1170             } else {
1171                 // 4) Multiple codegen units, but no explicit name.  We
1172                 //    just leave the `foo.0.x` files in place.
1173                 // (We don't have to do any work in this case.)
1174             }
1175         }
1176     };
1177
1178     // Flag to indicate whether the user explicitly requested bitcode.
1179     // Otherwise, we produced it only as a temporary output, and will need
1180     // to get rid of it.
1181     for output_type in crate_output.outputs.keys() {
1182         match *output_type {
1183             OutputType::Bitcode => {
1184                 user_wants_bitcode = true;
1185                 // Copy to .bc, but always keep the .0.bc.  There is a later
1186                 // check to figure out if we should delete .0.bc files, or keep
1187                 // them for making an rlib.
1188                 copy_if_one_unit(OutputType::Bitcode, true);
1189             }
1190             OutputType::LlvmAssembly => {
1191                 copy_if_one_unit(OutputType::LlvmAssembly, false);
1192             }
1193             OutputType::Assembly => {
1194                 copy_if_one_unit(OutputType::Assembly, false);
1195             }
1196             OutputType::Object => {
1197                 user_wants_objects = true;
1198                 copy_if_one_unit(OutputType::Object, true);
1199             }
1200             OutputType::Mir |
1201             OutputType::Metadata |
1202             OutputType::Exe |
1203             OutputType::DepInfo => {}
1204         }
1205     }
1206
1207     // Clean up unwanted temporary files.
1208
1209     // We create the following files by default:
1210     //  - #crate#.#module-name#.bc
1211     //  - #crate#.#module-name#.o
1212     //  - #crate#.crate.metadata.bc
1213     //  - #crate#.crate.metadata.o
1214     //  - #crate#.o (linked from crate.##.o)
1215     //  - #crate#.bc (copied from crate.##.bc)
1216     // We may create additional files if requested by the user (through
1217     // `-C save-temps` or `--emit=` flags).
1218
1219     if !sess.opts.cg.save_temps {
1220         // Remove the temporary .#module-name#.o objects.  If the user didn't
1221         // explicitly request bitcode (with --emit=bc), and the bitcode is not
1222         // needed for building an rlib, then we must remove .#module-name#.bc as
1223         // well.
1224
1225         // Specific rules for keeping .#module-name#.bc:
1226         //  - If the user requested bitcode (`user_wants_bitcode`), and
1227         //    codegen_units > 1, then keep it.
1228         //  - If the user requested bitcode but codegen_units == 1, then we
1229         //    can toss .#module-name#.bc because we copied it to .bc earlier.
1230         //  - If we're not building an rlib and the user didn't request
1231         //    bitcode, then delete .#module-name#.bc.
1232         // If you change how this works, also update back::link::link_rlib,
1233         // where .#module-name#.bc files are (maybe) deleted after making an
1234         // rlib.
1235         let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
1236
1237         let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
1238
1239         let keep_numbered_objects = needs_crate_object ||
1240                 (user_wants_objects && sess.codegen_units() > 1);
1241
1242         for module in compiled_modules.modules.iter() {
1243             if let Some(ref path) = module.object {
1244                 if !keep_numbered_objects {
1245                     remove(sess, path);
1246                 }
1247             }
1248
1249             if let Some(ref path) = module.bytecode {
1250                 if !keep_numbered_bitcode {
1251                     remove(sess, path);
1252                 }
1253             }
1254         }
1255
1256         if !user_wants_bitcode {
1257             if let Some(ref path) = compiled_modules.metadata_module.bytecode {
1258                 remove(sess, &path);
1259             }
1260
1261             if let Some(ref allocator_module) = compiled_modules.allocator_module {
1262                 if let Some(ref path) = allocator_module.bytecode {
1263                     remove(sess, path);
1264                 }
1265             }
1266         }
1267     }
1268
1269     // We leave the following files around by default:
1270     //  - #crate#.o
1271     //  - #crate#.crate.metadata.o
1272     //  - #crate#.bc
1273     // These are used in linking steps and will be cleaned up afterward.
1274 }
1275
1276 pub(crate) fn dump_incremental_data(_codegen_results: &CodegenResults) {
1277     // FIXME(mw): This does not work at the moment because the situation has
1278     //            become more complicated due to incremental LTO. Now a CGU
1279     //            can have more than two caching states.
1280     // println!("[incremental] Re-using {} out of {} modules",
1281     //           codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
1282     //           codegen_results.modules.len());
1283 }
1284
1285 enum WorkItem {
1286     /// Optimize a newly codegened, totally unoptimized module.
1287     Optimize(ModuleCodegen),
1288     /// Copy the post-LTO artifacts from the incremental cache to the output
1289     /// directory.
1290     CopyPostLtoArtifacts(CachedModuleCodegen),
1291     /// Perform (Thin)LTO on the given module.
1292     LTO(lto::LtoModuleCodegen),
1293 }
1294
1295 impl WorkItem {
1296     fn module_kind(&self) -> ModuleKind {
1297         match *self {
1298             WorkItem::Optimize(ref m) => m.kind,
1299             WorkItem::CopyPostLtoArtifacts(_) |
1300             WorkItem::LTO(_) => ModuleKind::Regular,
1301         }
1302     }
1303
1304     fn name(&self) -> String {
1305         match *self {
1306             WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
1307             WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
1308             WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
1309         }
1310     }
1311 }
1312
1313 enum WorkItemResult {
1314     Compiled(CompiledModule),
1315     NeedsLTO(ModuleCodegen),
1316 }
1317
1318 fn execute_work_item(cgcx: &CodegenContext,
1319                      work_item: WorkItem,
1320                      timeline: &mut Timeline)
1321     -> Result<WorkItemResult, FatalError>
1322 {
1323     let module_config = cgcx.config(work_item.module_kind());
1324
1325     match work_item {
1326         WorkItem::Optimize(module) => {
1327             execute_optimize_work_item(cgcx, module, module_config, timeline)
1328         }
1329         WorkItem::CopyPostLtoArtifacts(module) => {
1330             execute_copy_from_cache_work_item(cgcx, module, module_config, timeline)
1331         }
1332         WorkItem::LTO(module) => {
1333             execute_lto_work_item(cgcx, module, module_config, timeline)
1334         }
1335     }
1336 }
1337
1338 fn execute_optimize_work_item(cgcx: &CodegenContext,
1339                               module: ModuleCodegen,
1340                               module_config: &ModuleConfig,
1341                               timeline: &mut Timeline)
1342     -> Result<WorkItemResult, FatalError>
1343 {
1344     let diag_handler = cgcx.create_diag_handler();
1345
1346     unsafe {
1347         optimize(cgcx, &diag_handler, &module, module_config, timeline)?;
1348     }
1349
1350     let linker_does_lto = cgcx.opts.debugging_opts.cross_lang_lto.enabled();
1351
1352     // After we've done the initial round of optimizations we need to
1353     // decide whether to synchronously codegen this module or ship it
1354     // back to the coordinator thread for further LTO processing (which
1355     // has to wait for all the initial modules to be optimized).
1356     //
1357     // Here we dispatch based on the `cgcx.lto` and kind of module we're
1358     // codegenning...
1359     let needs_lto = match cgcx.lto {
1360         Lto::No => false,
1361
1362         // If the linker does LTO, we don't have to do it. Note that we
1363         // keep doing full LTO, if it is requested, as not to break the
1364         // assumption that the output will be a single module.
1365         Lto::Thin | Lto::ThinLocal if linker_does_lto => false,
1366
1367         // Here we've got a full crate graph LTO requested. We ignore
1368         // this, however, if the crate type is only an rlib as there's
1369         // no full crate graph to process, that'll happen later.
1370         //
1371         // This use case currently comes up primarily for targets that
1372         // require LTO so the request for LTO is always unconditionally
1373         // passed down to the backend, but we don't actually want to do
1374         // anything about it yet until we've got a final product.
1375         Lto::Yes | Lto::Fat | Lto::Thin => {
1376             cgcx.crate_types.len() != 1 ||
1377                 cgcx.crate_types[0] != config::CrateType::Rlib
1378         }
1379
1380         // When we're automatically doing ThinLTO for multi-codegen-unit
1381         // builds we don't actually want to LTO the allocator modules if
1382         // it shows up. This is due to various linker shenanigans that
1383         // we'll encounter later.
1384         //
1385         // Additionally here's where we also factor in the current LLVM
1386         // version. If it doesn't support ThinLTO we skip this.
1387         Lto::ThinLocal => {
1388             module.kind != ModuleKind::Allocator &&
1389                 unsafe { llvm::LLVMRustThinLTOAvailable() }
1390         }
1391     };
1392
1393     // Metadata modules never participate in LTO regardless of the lto
1394     // settings.
1395     let needs_lto = needs_lto && module.kind != ModuleKind::Metadata;
1396
1397     if needs_lto {
1398         Ok(WorkItemResult::NeedsLTO(module))
1399     } else {
1400         let module = unsafe {
1401             codegen(cgcx, &diag_handler, module, module_config, timeline)?
1402         };
1403         Ok(WorkItemResult::Compiled(module))
1404     }
1405 }
1406
1407 fn execute_copy_from_cache_work_item(cgcx: &CodegenContext,
1408                                      module: CachedModuleCodegen,
1409                                      module_config: &ModuleConfig,
1410                                      _: &mut Timeline)
1411     -> Result<WorkItemResult, FatalError>
1412 {
1413     let incr_comp_session_dir = cgcx.incr_comp_session_dir
1414                                     .as_ref()
1415                                     .unwrap();
1416     let mut object = None;
1417     let mut bytecode = None;
1418     let mut bytecode_compressed = None;
1419     for (kind, saved_file) in &module.source.saved_files {
1420         let obj_out = match kind {
1421             WorkProductFileKind::Object => {
1422                 let path = cgcx.output_filenames.temp_path(OutputType::Object,
1423                                                            Some(&module.name));
1424                 object = Some(path.clone());
1425                 path
1426             }
1427             WorkProductFileKind::Bytecode => {
1428                 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1429                                                            Some(&module.name));
1430                 bytecode = Some(path.clone());
1431                 path
1432             }
1433             WorkProductFileKind::BytecodeCompressed => {
1434                 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1435                                                            Some(&module.name))
1436                     .with_extension(RLIB_BYTECODE_EXTENSION);
1437                 bytecode_compressed = Some(path.clone());
1438                 path
1439             }
1440         };
1441         let source_file = in_incr_comp_dir(&incr_comp_session_dir,
1442                                            &saved_file);
1443         debug!("copying pre-existing module `{}` from {:?} to {}",
1444                module.name,
1445                source_file,
1446                obj_out.display());
1447         match link_or_copy(&source_file, &obj_out) {
1448             Ok(_) => { }
1449             Err(err) => {
1450                 let diag_handler = cgcx.create_diag_handler();
1451                 diag_handler.err(&format!("unable to copy {} to {}: {}",
1452                                           source_file.display(),
1453                                           obj_out.display(),
1454                                           err));
1455             }
1456         }
1457     }
1458
1459     assert_eq!(object.is_some(), module_config.emit_obj);
1460     assert_eq!(bytecode.is_some(), module_config.emit_bc);
1461     assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
1462
1463     Ok(WorkItemResult::Compiled(CompiledModule {
1464         name: module.name,
1465         kind: ModuleKind::Regular,
1466         object,
1467         bytecode,
1468         bytecode_compressed,
1469     }))
1470 }
1471
1472 fn execute_lto_work_item(cgcx: &CodegenContext,
1473                          mut module: lto::LtoModuleCodegen,
1474                          module_config: &ModuleConfig,
1475                          timeline: &mut Timeline)
1476     -> Result<WorkItemResult, FatalError>
1477 {
1478     let diag_handler = cgcx.create_diag_handler();
1479
1480     unsafe {
1481         let module = module.optimize(cgcx, timeline)?;
1482         let module = codegen(cgcx, &diag_handler, module, module_config, timeline)?;
1483         Ok(WorkItemResult::Compiled(module))
1484     }
1485 }
1486
1487 enum Message {
1488     Token(io::Result<Acquired>),
1489     NeedsLTO {
1490         result: ModuleCodegen,
1491         worker_id: usize,
1492     },
1493     Done {
1494         result: Result<CompiledModule, ()>,
1495         worker_id: usize,
1496     },
1497     CodegenDone {
1498         llvm_work_item: WorkItem,
1499         cost: u64,
1500     },
1501     AddImportOnlyModule {
1502         module_data: SerializedModule,
1503         work_product: WorkProduct,
1504     },
1505     CodegenComplete,
1506     CodegenItem,
1507 }
1508
1509 struct Diagnostic {
1510     msg: String,
1511     code: Option<DiagnosticId>,
1512     lvl: Level,
1513 }
1514
1515 #[derive(PartialEq, Clone, Copy, Debug)]
1516 enum MainThreadWorkerState {
1517     Idle,
1518     Codegenning,
1519     LLVMing,
1520 }
1521
1522 fn start_executing_work(tcx: TyCtxt,
1523                         crate_info: &CrateInfo,
1524                         shared_emitter: SharedEmitter,
1525                         codegen_worker_send: Sender<Message>,
1526                         coordinator_receive: Receiver<Box<dyn Any + Send>>,
1527                         total_cgus: usize,
1528                         jobserver: Client,
1529                         time_graph: Option<TimeGraph>,
1530                         modules_config: Arc<ModuleConfig>,
1531                         metadata_config: Arc<ModuleConfig>,
1532                         allocator_config: Arc<ModuleConfig>)
1533                         -> thread::JoinHandle<Result<CompiledModules, ()>> {
1534     let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1535     let sess = tcx.sess;
1536
1537     // Compute the set of symbols we need to retain when doing LTO (if we need to)
1538     let exported_symbols = {
1539         let mut exported_symbols = FxHashMap();
1540
1541         let copy_symbols = |cnum| {
1542             let symbols = tcx.exported_symbols(cnum)
1543                              .iter()
1544                              .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1545                              .collect();
1546             Arc::new(symbols)
1547         };
1548
1549         match sess.lto() {
1550             Lto::No => None,
1551             Lto::ThinLocal => {
1552                 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1553                 Some(Arc::new(exported_symbols))
1554             }
1555             Lto::Yes | Lto::Fat | Lto::Thin => {
1556                 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1557                 for &cnum in tcx.crates().iter() {
1558                     exported_symbols.insert(cnum, copy_symbols(cnum));
1559                 }
1560                 Some(Arc::new(exported_symbols))
1561             }
1562         }
1563     };
1564
1565     // First up, convert our jobserver into a helper thread so we can use normal
1566     // mpsc channels to manage our messages and such.
1567     // After we've requested tokens then we'll, when we can,
1568     // get tokens on `coordinator_receive` which will
1569     // get managed in the main loop below.
1570     let coordinator_send2 = coordinator_send.clone();
1571     let helper = jobserver.into_helper_thread(move |token| {
1572         drop(coordinator_send2.send(Box::new(Message::Token(token))));
1573     }).expect("failed to spawn helper thread");
1574
1575     let mut each_linked_rlib_for_lto = Vec::new();
1576     drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1577         if link::ignored_for_lto(sess, crate_info, cnum) {
1578             return
1579         }
1580         each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1581     }));
1582
1583     let assembler_cmd = if modules_config.no_integrated_as {
1584         // HACK: currently we use linker (gcc) as our assembler
1585         let (linker, flavor) = link::linker_and_flavor(sess);
1586
1587         let (name, mut cmd) = get_linker(sess, &linker, flavor);
1588         cmd.args(&sess.target.target.options.asm_args);
1589         Some(Arc::new(AssemblerCommand {
1590             name,
1591             cmd,
1592         }))
1593     } else {
1594         None
1595     };
1596
1597     let cgcx = CodegenContext {
1598         crate_types: sess.crate_types.borrow().clone(),
1599         each_linked_rlib_for_lto,
1600         lto: sess.lto(),
1601         no_landing_pads: sess.no_landing_pads(),
1602         fewer_names: sess.fewer_names(),
1603         save_temps: sess.opts.cg.save_temps,
1604         opts: Arc::new(sess.opts.clone()),
1605         time_passes: sess.time_passes(),
1606         exported_symbols,
1607         plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1608         remark: sess.opts.cg.remark.clone(),
1609         worker: 0,
1610         incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1611         coordinator_send,
1612         diag_emitter: shared_emitter.clone(),
1613         time_graph,
1614         output_filenames: tcx.output_filenames(LOCAL_CRATE),
1615         regular_module_config: modules_config,
1616         metadata_module_config: metadata_config,
1617         allocator_module_config: allocator_config,
1618         tm_factory: target_machine_factory(tcx.sess, false),
1619         total_cgus,
1620         msvc_imps_needed: msvc_imps_needed(tcx),
1621         target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1622         debuginfo: tcx.sess.opts.debuginfo,
1623         assembler_cmd,
1624     };
1625
1626     // This is the "main loop" of parallel work happening for parallel codegen.
1627     // It's here that we manage parallelism, schedule work, and work with
1628     // messages coming from clients.
1629     //
1630     // There are a few environmental pre-conditions that shape how the system
1631     // is set up:
1632     //
1633     // - Error reporting only can happen on the main thread because that's the
1634     //   only place where we have access to the compiler `Session`.
1635     // - LLVM work can be done on any thread.
1636     // - Codegen can only happen on the main thread.
1637     // - Each thread doing substantial work most be in possession of a `Token`
1638     //   from the `Jobserver`.
1639     // - The compiler process always holds one `Token`. Any additional `Tokens`
1640     //   have to be requested from the `Jobserver`.
1641     //
1642     // Error Reporting
1643     // ===============
1644     // The error reporting restriction is handled separately from the rest: We
1645     // set up a `SharedEmitter` the holds an open channel to the main thread.
1646     // When an error occurs on any thread, the shared emitter will send the
1647     // error message to the receiver main thread (`SharedEmitterMain`). The
1648     // main thread will periodically query this error message queue and emit
1649     // any error messages it has received. It might even abort compilation if
1650     // has received a fatal error. In this case we rely on all other threads
1651     // being torn down automatically with the main thread.
1652     // Since the main thread will often be busy doing codegen work, error
1653     // reporting will be somewhat delayed, since the message queue can only be
1654     // checked in between to work packages.
1655     //
1656     // Work Processing Infrastructure
1657     // ==============================
1658     // The work processing infrastructure knows three major actors:
1659     //
1660     // - the coordinator thread,
1661     // - the main thread, and
1662     // - LLVM worker threads
1663     //
1664     // The coordinator thread is running a message loop. It instructs the main
1665     // thread about what work to do when, and it will spawn off LLVM worker
1666     // threads as open LLVM WorkItems become available.
1667     //
1668     // The job of the main thread is to codegen CGUs into LLVM work package
1669     // (since the main thread is the only thread that can do this). The main
1670     // thread will block until it receives a message from the coordinator, upon
1671     // which it will codegen one CGU, send it to the coordinator and block
1672     // again. This way the coordinator can control what the main thread is
1673     // doing.
1674     //
1675     // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1676     // available, it will spawn off a new LLVM worker thread and let it process
1677     // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1678     // it will just shut down, which also frees all resources associated with
1679     // the given LLVM module, and sends a message to the coordinator that the
1680     // has been completed.
1681     //
1682     // Work Scheduling
1683     // ===============
1684     // The scheduler's goal is to minimize the time it takes to complete all
1685     // work there is, however, we also want to keep memory consumption low
1686     // if possible. These two goals are at odds with each other: If memory
1687     // consumption were not an issue, we could just let the main thread produce
1688     // LLVM WorkItems at full speed, assuring maximal utilization of
1689     // Tokens/LLVM worker threads. However, since codegen usual is faster
1690     // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1691     // WorkItem potentially holds on to a substantial amount of memory.
1692     //
1693     // So the actual goal is to always produce just enough LLVM WorkItems as
1694     // not to starve our LLVM worker threads. That means, once we have enough
1695     // WorkItems in our queue, we can block the main thread, so it does not
1696     // produce more until we need them.
1697     //
1698     // Doing LLVM Work on the Main Thread
1699     // ----------------------------------
1700     // Since the main thread owns the compiler processes implicit `Token`, it is
1701     // wasteful to keep it blocked without doing any work. Therefore, what we do
1702     // in this case is: We spawn off an additional LLVM worker thread that helps
1703     // reduce the queue. The work it is doing corresponds to the implicit
1704     // `Token`. The coordinator will mark the main thread as being busy with
1705     // LLVM work. (The actual work happens on another OS thread but we just care
1706     // about `Tokens`, not actual threads).
1707     //
1708     // When any LLVM worker thread finishes while the main thread is marked as
1709     // "busy with LLVM work", we can do a little switcheroo: We give the Token
1710     // of the just finished thread to the LLVM worker thread that is working on
1711     // behalf of the main thread's implicit Token, thus freeing up the main
1712     // thread again. The coordinator can then again decide what the main thread
1713     // should do. This allows the coordinator to make decisions at more points
1714     // in time.
1715     //
1716     // Striking a Balance between Throughput and Memory Consumption
1717     // ------------------------------------------------------------
1718     // Since our two goals, (1) use as many Tokens as possible and (2) keep
1719     // memory consumption as low as possible, are in conflict with each other,
1720     // we have to find a trade off between them. Right now, the goal is to keep
1721     // all workers busy, which means that no worker should find the queue empty
1722     // when it is ready to start.
1723     // How do we do achieve this? Good question :) We actually never know how
1724     // many `Tokens` are potentially available so it's hard to say how much to
1725     // fill up the queue before switching the main thread to LLVM work. Also we
1726     // currently don't have a means to estimate how long a running LLVM worker
1727     // will still be busy with it's current WorkItem. However, we know the
1728     // maximal count of available Tokens that makes sense (=the number of CPU
1729     // cores), so we can take a conservative guess. The heuristic we use here
1730     // is implemented in the `queue_full_enough()` function.
1731     //
1732     // Some Background on Jobservers
1733     // -----------------------------
1734     // It's worth also touching on the management of parallelism here. We don't
1735     // want to just spawn a thread per work item because while that's optimal
1736     // parallelism it may overload a system with too many threads or violate our
1737     // configuration for the maximum amount of cpu to use for this process. To
1738     // manage this we use the `jobserver` crate.
1739     //
1740     // Job servers are an artifact of GNU make and are used to manage
1741     // parallelism between processes. A jobserver is a glorified IPC semaphore
1742     // basically. Whenever we want to run some work we acquire the semaphore,
1743     // and whenever we're done with that work we release the semaphore. In this
1744     // manner we can ensure that the maximum number of parallel workers is
1745     // capped at any one point in time.
1746     //
1747     // LTO and the coordinator thread
1748     // ------------------------------
1749     //
1750     // The final job the coordinator thread is responsible for is managing LTO
1751     // and how that works. When LTO is requested what we'll to is collect all
1752     // optimized LLVM modules into a local vector on the coordinator. Once all
1753     // modules have been codegened and optimized we hand this to the `lto`
1754     // module for further optimization. The `lto` module will return back a list
1755     // of more modules to work on, which the coordinator will continue to spawn
1756     // work for.
1757     //
1758     // Each LLVM module is automatically sent back to the coordinator for LTO if
1759     // necessary. There's already optimizations in place to avoid sending work
1760     // back to the coordinator if LTO isn't requested.
1761     return thread::spawn(move || {
1762         // We pretend to be within the top-level LLVM time-passes task here:
1763         set_time_depth(1);
1764
1765         let max_workers = ::num_cpus::get();
1766         let mut worker_id_counter = 0;
1767         let mut free_worker_ids = Vec::new();
1768         let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1769             if let Some(id) = free_worker_ids.pop() {
1770                 id
1771             } else {
1772                 let id = worker_id_counter;
1773                 worker_id_counter += 1;
1774                 id
1775             }
1776         };
1777
1778         // This is where we collect codegen units that have gone all the way
1779         // through codegen and LLVM.
1780         let mut compiled_modules = vec![];
1781         let mut compiled_metadata_module = None;
1782         let mut compiled_allocator_module = None;
1783         let mut needs_lto = Vec::new();
1784         let mut lto_import_only_modules = Vec::new();
1785         let mut started_lto = false;
1786
1787         // This flag tracks whether all items have gone through codegens
1788         let mut codegen_done = false;
1789
1790         // This is the queue of LLVM work items that still need processing.
1791         let mut work_items = Vec::<(WorkItem, u64)>::new();
1792
1793         // This are the Jobserver Tokens we currently hold. Does not include
1794         // the implicit Token the compiler process owns no matter what.
1795         let mut tokens = Vec::new();
1796
1797         let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1798         let mut running = 0;
1799
1800         let mut llvm_start_time = None;
1801
1802         // Run the message loop while there's still anything that needs message
1803         // processing:
1804         while !codegen_done ||
1805               work_items.len() > 0 ||
1806               running > 0 ||
1807               needs_lto.len() > 0 ||
1808               lto_import_only_modules.len() > 0 ||
1809               main_thread_worker_state != MainThreadWorkerState::Idle {
1810
1811             // While there are still CGUs to be codegened, the coordinator has
1812             // to decide how to utilize the compiler processes implicit Token:
1813             // For codegenning more CGU or for running them through LLVM.
1814             if !codegen_done {
1815                 if main_thread_worker_state == MainThreadWorkerState::Idle {
1816                     if !queue_full_enough(work_items.len(), running, max_workers) {
1817                         // The queue is not full enough, codegen more items:
1818                         if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1819                             panic!("Could not send Message::CodegenItem to main thread")
1820                         }
1821                         main_thread_worker_state = MainThreadWorkerState::Codegenning;
1822                     } else {
1823                         // The queue is full enough to not let the worker
1824                         // threads starve. Use the implicit Token to do some
1825                         // LLVM work too.
1826                         let (item, _) = work_items.pop()
1827                             .expect("queue empty - queue_full_enough() broken?");
1828                         let cgcx = CodegenContext {
1829                             worker: get_worker_id(&mut free_worker_ids),
1830                             .. cgcx.clone()
1831                         };
1832                         maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1833                                                &mut llvm_start_time);
1834                         main_thread_worker_state = MainThreadWorkerState::LLVMing;
1835                         spawn_work(cgcx, item);
1836                     }
1837                 }
1838             } else {
1839                 // If we've finished everything related to normal codegen
1840                 // then it must be the case that we've got some LTO work to do.
1841                 // Perform the serial work here of figuring out what we're
1842                 // going to LTO and then push a bunch of work items onto our
1843                 // queue to do LTO
1844                 if work_items.len() == 0 &&
1845                    running == 0 &&
1846                    main_thread_worker_state == MainThreadWorkerState::Idle {
1847                     assert!(!started_lto);
1848                     assert!(needs_lto.len() + lto_import_only_modules.len() > 0);
1849                     started_lto = true;
1850                     let modules = mem::replace(&mut needs_lto, Vec::new());
1851                     let import_only_modules =
1852                         mem::replace(&mut lto_import_only_modules, Vec::new());
1853                     for (work, cost) in generate_lto_work(&cgcx, modules, import_only_modules) {
1854                         let insertion_index = work_items
1855                             .binary_search_by_key(&cost, |&(_, cost)| cost)
1856                             .unwrap_or_else(|e| e);
1857                         work_items.insert(insertion_index, (work, cost));
1858                         if !cgcx.opts.debugging_opts.no_parallel_llvm {
1859                             helper.request_token();
1860                         }
1861                     }
1862                 }
1863
1864                 // In this branch, we know that everything has been codegened,
1865                 // so it's just a matter of determining whether the implicit
1866                 // Token is free to use for LLVM work.
1867                 match main_thread_worker_state {
1868                     MainThreadWorkerState::Idle => {
1869                         if let Some((item, _)) = work_items.pop() {
1870                             let cgcx = CodegenContext {
1871                                 worker: get_worker_id(&mut free_worker_ids),
1872                                 .. cgcx.clone()
1873                             };
1874                             maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1875                                                    &mut llvm_start_time);
1876                             main_thread_worker_state = MainThreadWorkerState::LLVMing;
1877                             spawn_work(cgcx, item);
1878                         } else {
1879                             // There is no unstarted work, so let the main thread
1880                             // take over for a running worker. Otherwise the
1881                             // implicit token would just go to waste.
1882                             // We reduce the `running` counter by one. The
1883                             // `tokens.truncate()` below will take care of
1884                             // giving the Token back.
1885                             debug_assert!(running > 0);
1886                             running -= 1;
1887                             main_thread_worker_state = MainThreadWorkerState::LLVMing;
1888                         }
1889                     }
1890                     MainThreadWorkerState::Codegenning => {
1891                         bug!("codegen worker should not be codegenning after \
1892                               codegen was already completed")
1893                     }
1894                     MainThreadWorkerState::LLVMing => {
1895                         // Already making good use of that token
1896                     }
1897                 }
1898             }
1899
1900             // Spin up what work we can, only doing this while we've got available
1901             // parallelism slots and work left to spawn.
1902             while work_items.len() > 0 && running < tokens.len() {
1903                 let (item, _) = work_items.pop().unwrap();
1904
1905                 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1906                                        &mut llvm_start_time);
1907
1908                 let cgcx = CodegenContext {
1909                     worker: get_worker_id(&mut free_worker_ids),
1910                     .. cgcx.clone()
1911                 };
1912
1913                 spawn_work(cgcx, item);
1914                 running += 1;
1915             }
1916
1917             // Relinquish accidentally acquired extra tokens
1918             tokens.truncate(running);
1919
1920             let msg = coordinator_receive.recv().unwrap();
1921             match *msg.downcast::<Message>().ok().unwrap() {
1922                 // Save the token locally and the next turn of the loop will use
1923                 // this to spawn a new unit of work, or it may get dropped
1924                 // immediately if we have no more work to spawn.
1925                 Message::Token(token) => {
1926                     match token {
1927                         Ok(token) => {
1928                             tokens.push(token);
1929
1930                             if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1931                                 // If the main thread token is used for LLVM work
1932                                 // at the moment, we turn that thread into a regular
1933                                 // LLVM worker thread, so the main thread is free
1934                                 // to react to codegen demand.
1935                                 main_thread_worker_state = MainThreadWorkerState::Idle;
1936                                 running += 1;
1937                             }
1938                         }
1939                         Err(e) => {
1940                             let msg = &format!("failed to acquire jobserver token: {}", e);
1941                             shared_emitter.fatal(msg);
1942                             // Exit the coordinator thread
1943                             panic!("{}", msg)
1944                         }
1945                     }
1946                 }
1947
1948                 Message::CodegenDone { llvm_work_item, cost } => {
1949                     // We keep the queue sorted by estimated processing cost,
1950                     // so that more expensive items are processed earlier. This
1951                     // is good for throughput as it gives the main thread more
1952                     // time to fill up the queue and it avoids scheduling
1953                     // expensive items to the end.
1954                     // Note, however, that this is not ideal for memory
1955                     // consumption, as LLVM module sizes are not evenly
1956                     // distributed.
1957                     let insertion_index =
1958                         work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1959                     let insertion_index = match insertion_index {
1960                         Ok(idx) | Err(idx) => idx
1961                     };
1962                     work_items.insert(insertion_index, (llvm_work_item, cost));
1963
1964                     if !cgcx.opts.debugging_opts.no_parallel_llvm {
1965                         helper.request_token();
1966                     }
1967                     assert_eq!(main_thread_worker_state,
1968                                MainThreadWorkerState::Codegenning);
1969                     main_thread_worker_state = MainThreadWorkerState::Idle;
1970                 }
1971
1972                 Message::CodegenComplete => {
1973                     codegen_done = true;
1974                     assert_eq!(main_thread_worker_state,
1975                                MainThreadWorkerState::Codegenning);
1976                     main_thread_worker_state = MainThreadWorkerState::Idle;
1977                 }
1978
1979                 // If a thread exits successfully then we drop a token associated
1980                 // with that worker and update our `running` count. We may later
1981                 // re-acquire a token to continue running more work. We may also not
1982                 // actually drop a token here if the worker was running with an
1983                 // "ephemeral token"
1984                 //
1985                 // Note that if the thread failed that means it panicked, so we
1986                 // abort immediately.
1987                 Message::Done { result: Ok(compiled_module), worker_id } => {
1988                     if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1989                         main_thread_worker_state = MainThreadWorkerState::Idle;
1990                     } else {
1991                         running -= 1;
1992                     }
1993
1994                     free_worker_ids.push(worker_id);
1995
1996                     match compiled_module.kind {
1997                         ModuleKind::Regular => {
1998                             compiled_modules.push(compiled_module);
1999                         }
2000                         ModuleKind::Metadata => {
2001                             assert!(compiled_metadata_module.is_none());
2002                             compiled_metadata_module = Some(compiled_module);
2003                         }
2004                         ModuleKind::Allocator => {
2005                             assert!(compiled_allocator_module.is_none());
2006                             compiled_allocator_module = Some(compiled_module);
2007                         }
2008                     }
2009                 }
2010                 Message::NeedsLTO { result, worker_id } => {
2011                     assert!(!started_lto);
2012                     if main_thread_worker_state == MainThreadWorkerState::LLVMing {
2013                         main_thread_worker_state = MainThreadWorkerState::Idle;
2014                     } else {
2015                         running -= 1;
2016                     }
2017                     free_worker_ids.push(worker_id);
2018                     needs_lto.push(result);
2019                 }
2020                 Message::AddImportOnlyModule { module_data, work_product } => {
2021                     assert!(!started_lto);
2022                     assert!(!codegen_done);
2023                     assert_eq!(main_thread_worker_state,
2024                                MainThreadWorkerState::Codegenning);
2025                     lto_import_only_modules.push((module_data, work_product));
2026                     main_thread_worker_state = MainThreadWorkerState::Idle;
2027                 }
2028                 Message::Done { result: Err(()), worker_id: _ } => {
2029                     shared_emitter.fatal("aborting due to worker thread failure");
2030                     // Exit the coordinator thread
2031                     return Err(())
2032                 }
2033                 Message::CodegenItem => {
2034                     bug!("the coordinator should not receive codegen requests")
2035                 }
2036             }
2037         }
2038
2039         if let Some(llvm_start_time) = llvm_start_time {
2040             let total_llvm_time = Instant::now().duration_since(llvm_start_time);
2041             // This is the top-level timing for all of LLVM, set the time-depth
2042             // to zero.
2043             set_time_depth(0);
2044             print_time_passes_entry(cgcx.time_passes,
2045                                     "LLVM passes",
2046                                     total_llvm_time);
2047         }
2048
2049         // Regardless of what order these modules completed in, report them to
2050         // the backend in the same order every time to ensure that we're handing
2051         // out deterministic results.
2052         compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
2053
2054         let compiled_metadata_module = compiled_metadata_module
2055             .expect("Metadata module not compiled?");
2056
2057         Ok(CompiledModules {
2058             modules: compiled_modules,
2059             metadata_module: compiled_metadata_module,
2060             allocator_module: compiled_allocator_module,
2061         })
2062     });
2063
2064     // A heuristic that determines if we have enough LLVM WorkItems in the
2065     // queue so that the main thread can do LLVM work instead of codegen
2066     fn queue_full_enough(items_in_queue: usize,
2067                          workers_running: usize,
2068                          max_workers: usize) -> bool {
2069         // Tune me, plz.
2070         items_in_queue > 0 &&
2071         items_in_queue >= max_workers.saturating_sub(workers_running / 2)
2072     }
2073
2074     fn maybe_start_llvm_timer(config: &ModuleConfig,
2075                               llvm_start_time: &mut Option<Instant>) {
2076         // We keep track of the -Ztime-passes output manually,
2077         // since the closure-based interface does not fit well here.
2078         if config.time_passes {
2079             if llvm_start_time.is_none() {
2080                 *llvm_start_time = Some(Instant::now());
2081             }
2082         }
2083     }
2084 }
2085
2086 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
2087 pub const CODEGEN_WORKER_TIMELINE: time_graph::TimelineId =
2088     time_graph::TimelineId(CODEGEN_WORKER_ID);
2089 pub const CODEGEN_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2090     time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
2091 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2092     time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
2093
2094 fn spawn_work(cgcx: CodegenContext, work: WorkItem) {
2095     let depth = time_depth();
2096
2097     thread::spawn(move || {
2098         set_time_depth(depth);
2099
2100         // Set up a destructor which will fire off a message that we're done as
2101         // we exit.
2102         struct Bomb {
2103             coordinator_send: Sender<Box<dyn Any + Send>>,
2104             result: Option<WorkItemResult>,
2105             worker_id: usize,
2106         }
2107         impl Drop for Bomb {
2108             fn drop(&mut self) {
2109                 let worker_id = self.worker_id;
2110                 let msg = match self.result.take() {
2111                     Some(WorkItemResult::Compiled(m)) => {
2112                         Message::Done { result: Ok(m), worker_id }
2113                     }
2114                     Some(WorkItemResult::NeedsLTO(m)) => {
2115                         Message::NeedsLTO { result: m, worker_id }
2116                     }
2117                     None => Message::Done { result: Err(()), worker_id }
2118                 };
2119                 drop(self.coordinator_send.send(Box::new(msg)));
2120             }
2121         }
2122
2123         let mut bomb = Bomb {
2124             coordinator_send: cgcx.coordinator_send.clone(),
2125             result: None,
2126             worker_id: cgcx.worker,
2127         };
2128
2129         // Execute the work itself, and if it finishes successfully then flag
2130         // ourselves as a success as well.
2131         //
2132         // Note that we ignore any `FatalError` coming out of `execute_work_item`,
2133         // as a diagnostic was already sent off to the main thread - just
2134         // surface that there was an error in this worker.
2135         bomb.result = {
2136             let timeline = cgcx.time_graph.as_ref().map(|tg| {
2137                 tg.start(time_graph::TimelineId(cgcx.worker),
2138                          LLVM_WORK_PACKAGE_KIND,
2139                          &work.name())
2140             });
2141             let mut timeline = timeline.unwrap_or(Timeline::noop());
2142             execute_work_item(&cgcx, work, &mut timeline).ok()
2143         };
2144     });
2145 }
2146
2147 pub fn run_assembler(cgcx: &CodegenContext, handler: &Handler, assembly: &Path, object: &Path) {
2148     let assembler = cgcx.assembler_cmd
2149         .as_ref()
2150         .expect("cgcx.assembler_cmd is missing?");
2151
2152     let pname = &assembler.name;
2153     let mut cmd = assembler.cmd.clone();
2154     cmd.arg("-c").arg("-o").arg(object).arg(assembly);
2155     debug!("{:?}", cmd);
2156
2157     match cmd.output() {
2158         Ok(prog) => {
2159             if !prog.status.success() {
2160                 let mut note = prog.stderr.clone();
2161                 note.extend_from_slice(&prog.stdout);
2162
2163                 handler.struct_err(&format!("linking with `{}` failed: {}",
2164                                             pname.display(),
2165                                             prog.status))
2166                     .note(&format!("{:?}", &cmd))
2167                     .note(str::from_utf8(&note[..]).unwrap())
2168                     .emit();
2169                 handler.abort_if_errors();
2170             }
2171         },
2172         Err(e) => {
2173             handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
2174             handler.abort_if_errors();
2175         }
2176     }
2177 }
2178
2179 pub unsafe fn with_llvm_pmb(llmod: &llvm::Module,
2180                             config: &ModuleConfig,
2181                             opt_level: llvm::CodeGenOptLevel,
2182                             prepare_for_thin_lto: bool,
2183                             f: &mut dyn FnMut(&llvm::PassManagerBuilder)) {
2184     use std::ptr;
2185
2186     // Create the PassManagerBuilder for LLVM. We configure it with
2187     // reasonable defaults and prepare it to actually populate the pass
2188     // manager.
2189     let builder = llvm::LLVMPassManagerBuilderCreate();
2190     let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
2191     let inline_threshold = config.inline_threshold;
2192
2193     let pgo_gen_path = config.pgo_gen.as_ref().map(|s| {
2194         let s = if s.is_empty() { "default_%m.profraw" } else { s };
2195         CString::new(s.as_bytes()).unwrap()
2196     });
2197
2198     let pgo_use_path = if config.pgo_use.is_empty() {
2199         None
2200     } else {
2201         Some(CString::new(config.pgo_use.as_bytes()).unwrap())
2202     };
2203
2204     llvm::LLVMRustConfigurePassManagerBuilder(
2205         builder,
2206         opt_level,
2207         config.merge_functions,
2208         config.vectorize_slp,
2209         config.vectorize_loop,
2210         prepare_for_thin_lto,
2211         pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2212         pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2213     );
2214
2215     llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
2216
2217     if opt_size != llvm::CodeGenOptSizeNone {
2218         llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
2219     }
2220
2221     llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
2222
2223     // Here we match what clang does (kinda). For O0 we only inline
2224     // always-inline functions (but don't add lifetime intrinsics), at O1 we
2225     // inline with lifetime intrinsics, and O2+ we add an inliner with a
2226     // thresholds copied from clang.
2227     match (opt_level, opt_size, inline_threshold) {
2228         (.., Some(t)) => {
2229             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
2230         }
2231         (llvm::CodeGenOptLevel::Aggressive, ..) => {
2232             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
2233         }
2234         (_, llvm::CodeGenOptSizeDefault, _) => {
2235             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
2236         }
2237         (_, llvm::CodeGenOptSizeAggressive, _) => {
2238             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
2239         }
2240         (llvm::CodeGenOptLevel::None, ..) => {
2241             llvm::LLVMRustAddAlwaysInlinePass(builder, false);
2242         }
2243         (llvm::CodeGenOptLevel::Less, ..) => {
2244             llvm::LLVMRustAddAlwaysInlinePass(builder, true);
2245         }
2246         (llvm::CodeGenOptLevel::Default, ..) => {
2247             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
2248         }
2249         (llvm::CodeGenOptLevel::Other, ..) => {
2250             bug!("CodeGenOptLevel::Other selected")
2251         }
2252     }
2253
2254     f(builder);
2255     llvm::LLVMPassManagerBuilderDispose(builder);
2256 }
2257
2258
2259 enum SharedEmitterMessage {
2260     Diagnostic(Diagnostic),
2261     InlineAsmError(u32, String),
2262     AbortIfErrors,
2263     Fatal(String),
2264 }
2265
2266 #[derive(Clone)]
2267 pub struct SharedEmitter {
2268     sender: Sender<SharedEmitterMessage>,
2269 }
2270
2271 pub struct SharedEmitterMain {
2272     receiver: Receiver<SharedEmitterMessage>,
2273 }
2274
2275 impl SharedEmitter {
2276     pub fn new() -> (SharedEmitter, SharedEmitterMain) {
2277         let (sender, receiver) = channel();
2278
2279         (SharedEmitter { sender }, SharedEmitterMain { receiver })
2280     }
2281
2282     fn inline_asm_error(&self, cookie: u32, msg: String) {
2283         drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
2284     }
2285
2286     fn fatal(&self, msg: &str) {
2287         drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2288     }
2289 }
2290
2291 impl Emitter for SharedEmitter {
2292     fn emit(&mut self, db: &DiagnosticBuilder) {
2293         drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2294             msg: db.message(),
2295             code: db.code.clone(),
2296             lvl: db.level,
2297         })));
2298         for child in &db.children {
2299             drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2300                 msg: child.message(),
2301                 code: None,
2302                 lvl: child.level,
2303             })));
2304         }
2305         drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
2306     }
2307 }
2308
2309 impl SharedEmitterMain {
2310     pub fn check(&self, sess: &Session, blocking: bool) {
2311         loop {
2312             let message = if blocking {
2313                 match self.receiver.recv() {
2314                     Ok(message) => Ok(message),
2315                     Err(_) => Err(()),
2316                 }
2317             } else {
2318                 match self.receiver.try_recv() {
2319                     Ok(message) => Ok(message),
2320                     Err(_) => Err(()),
2321                 }
2322             };
2323
2324             match message {
2325                 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2326                     let handler = sess.diagnostic();
2327                     match diag.code {
2328                         Some(ref code) => {
2329                             handler.emit_with_code(&MultiSpan::new(),
2330                                                    &diag.msg,
2331                                                    code.clone(),
2332                                                    diag.lvl);
2333                         }
2334                         None => {
2335                             handler.emit(&MultiSpan::new(),
2336                                          &diag.msg,
2337                                          diag.lvl);
2338                         }
2339                     }
2340                 }
2341                 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
2342                     match Mark::from_u32(cookie).expn_info() {
2343                         Some(ei) => sess.span_err(ei.call_site, &msg),
2344                         None     => sess.err(&msg),
2345                     }
2346                 }
2347                 Ok(SharedEmitterMessage::AbortIfErrors) => {
2348                     sess.abort_if_errors();
2349                 }
2350                 Ok(SharedEmitterMessage::Fatal(msg)) => {
2351                     sess.fatal(&msg);
2352                 }
2353                 Err(_) => {
2354                     break;
2355                 }
2356             }
2357
2358         }
2359     }
2360 }
2361
2362 pub struct OngoingCodegen {
2363     crate_name: Symbol,
2364     crate_hash: Svh,
2365     metadata: EncodedMetadata,
2366     windows_subsystem: Option<String>,
2367     linker_info: LinkerInfo,
2368     crate_info: CrateInfo,
2369     time_graph: Option<TimeGraph>,
2370     coordinator_send: Sender<Box<dyn Any + Send>>,
2371     codegen_worker_receive: Receiver<Message>,
2372     shared_emitter_main: SharedEmitterMain,
2373     future: thread::JoinHandle<Result<CompiledModules, ()>>,
2374     output_filenames: Arc<OutputFilenames>,
2375 }
2376
2377 impl OngoingCodegen {
2378     pub(crate) fn join(
2379         self,
2380         sess: &Session
2381     ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
2382         self.shared_emitter_main.check(sess, true);
2383         let compiled_modules = match self.future.join() {
2384             Ok(Ok(compiled_modules)) => compiled_modules,
2385             Ok(Err(())) => {
2386                 sess.abort_if_errors();
2387                 panic!("expected abort due to worker thread errors")
2388             },
2389             Err(_) => {
2390                 sess.fatal("Error during codegen/LLVM phase.");
2391             }
2392         };
2393
2394         sess.abort_if_errors();
2395
2396         if let Some(time_graph) = self.time_graph {
2397             time_graph.dump(&format!("{}-timings", self.crate_name));
2398         }
2399
2400         let work_products =
2401             copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
2402                                                              &compiled_modules);
2403         produce_final_output_artifacts(sess,
2404                                        &compiled_modules,
2405                                        &self.output_filenames);
2406
2407         // FIXME: time_llvm_passes support - does this use a global context or
2408         // something?
2409         if sess.codegen_units() == 1 && sess.time_llvm_passes() {
2410             unsafe { llvm::LLVMRustPrintPassTimings(); }
2411         }
2412
2413         (CodegenResults {
2414             crate_name: self.crate_name,
2415             crate_hash: self.crate_hash,
2416             metadata: self.metadata,
2417             windows_subsystem: self.windows_subsystem,
2418             linker_info: self.linker_info,
2419             crate_info: self.crate_info,
2420
2421             modules: compiled_modules.modules,
2422             allocator_module: compiled_modules.allocator_module,
2423             metadata_module: compiled_modules.metadata_module,
2424         }, work_products)
2425     }
2426
2427     pub(crate) fn submit_pre_codegened_module_to_llvm(&self,
2428                                                        tcx: TyCtxt,
2429                                                        module: ModuleCodegen) {
2430         self.wait_for_signal_to_codegen_item();
2431         self.check_for_errors(tcx.sess);
2432
2433         // These are generally cheap and won't through off scheduling.
2434         let cost = 0;
2435         submit_codegened_module_to_llvm(tcx, module, cost);
2436     }
2437
2438     pub fn codegen_finished(&self, tcx: TyCtxt) {
2439         self.wait_for_signal_to_codegen_item();
2440         self.check_for_errors(tcx.sess);
2441         drop(self.coordinator_send.send(Box::new(Message::CodegenComplete)));
2442     }
2443
2444     pub fn check_for_errors(&self, sess: &Session) {
2445         self.shared_emitter_main.check(sess, false);
2446     }
2447
2448     pub fn wait_for_signal_to_codegen_item(&self) {
2449         match self.codegen_worker_receive.recv() {
2450             Ok(Message::CodegenItem) => {
2451                 // Nothing to do
2452             }
2453             Ok(_) => panic!("unexpected message"),
2454             Err(_) => {
2455                 // One of the LLVM threads must have panicked, fall through so
2456                 // error handling can be reached.
2457             }
2458         }
2459     }
2460 }
2461
2462 pub(crate) fn submit_codegened_module_to_llvm(tcx: TyCtxt,
2463                                               module: ModuleCodegen,
2464                                               cost: u64) {
2465     let llvm_work_item = WorkItem::Optimize(module);
2466     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2467         llvm_work_item,
2468         cost,
2469     })));
2470 }
2471
2472 pub(crate) fn submit_post_lto_module_to_llvm(tcx: TyCtxt,
2473                                              module: CachedModuleCodegen) {
2474     let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2475     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2476         llvm_work_item,
2477         cost: 0,
2478     })));
2479 }
2480
2481 pub(crate) fn submit_pre_lto_module_to_llvm(tcx: TyCtxt,
2482                                             module: CachedModuleCodegen) {
2483     let filename = pre_lto_bitcode_filename(&module.name);
2484     let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2485     let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
2486         panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
2487     });
2488
2489     let mmap = unsafe {
2490         memmap::Mmap::map(&file).unwrap_or_else(|e| {
2491             panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2492         })
2493     };
2494
2495     // Schedule the module to be loaded
2496     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::AddImportOnlyModule {
2497         module_data: SerializedModule::FromUncompressedFile(mmap),
2498         work_product: module.source,
2499     })));
2500 }
2501
2502 pub(super) fn pre_lto_bitcode_filename(module_name: &str) -> String {
2503     format!("{}.{}", module_name, PRE_THIN_LTO_BC_EXT)
2504 }
2505
2506 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
2507     // This should never be true (because it's not supported). If it is true,
2508     // something is wrong with commandline arg validation.
2509     assert!(!(tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() &&
2510               tcx.sess.target.target.options.is_like_msvc &&
2511               tcx.sess.opts.cg.prefer_dynamic));
2512
2513     tcx.sess.target.target.options.is_like_msvc &&
2514         tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
2515     // ThinLTO can't handle this workaround in all cases, so we don't
2516     // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2517     // dynamic linking when cross-language LTO is enabled.
2518     !tcx.sess.opts.debugging_opts.cross_lang_lto.enabled()
2519 }
2520
2521 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2522 // This is required to satisfy `dllimport` references to static data in .rlibs
2523 // when using MSVC linker.  We do this only for data, as linker can fix up
2524 // code references on its own.
2525 // See #26591, #27438
2526 fn create_msvc_imps(cgcx: &CodegenContext, llcx: &llvm::Context, llmod: &llvm::Module) {
2527     if !cgcx.msvc_imps_needed {
2528         return
2529     }
2530     // The x86 ABI seems to require that leading underscores are added to symbol
2531     // names, so we need an extra underscore on 32-bit. There's also a leading
2532     // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2533     // underscores added in front).
2534     let prefix = if cgcx.target_pointer_width == "32" {
2535         "\x01__imp__"
2536     } else {
2537         "\x01__imp_"
2538     };
2539     unsafe {
2540         let i8p_ty = Type::i8p_llcx(llcx);
2541         let globals = base::iter_globals(llmod)
2542             .filter(|&val| {
2543                 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
2544                     llvm::LLVMIsDeclaration(val) == 0
2545             })
2546             .map(move |val| {
2547                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2548                 let mut imp_name = prefix.as_bytes().to_vec();
2549                 imp_name.extend(name.to_bytes());
2550                 let imp_name = CString::new(imp_name).unwrap();
2551                 (imp_name, val)
2552             })
2553             .collect::<Vec<_>>();
2554         for (imp_name, val) in globals {
2555             let imp = llvm::LLVMAddGlobal(llmod,
2556                                           i8p_ty,
2557                                           imp_name.as_ptr() as *const _);
2558             llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
2559             llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
2560         }
2561     }
2562 }