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