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