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.
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.
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};
24 use llvm::{ModuleRef, TargetMachineRef, PassManagerRef, DiagnosticInfoRef};
25 use llvm::{SMDiagnosticRef, ContextRef};
26 use {CrateTranslation, ModuleSource, ModuleTranslation, CompiledModule, ModuleKind};
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};
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};
43 use std::ffi::CString;
48 use std::path::{Path, PathBuf};
51 use std::sync::mpsc::{channel, Sender, Receiver};
53 use std::time::Instant;
55 use libc::{c_uint, c_void, c_char, size_t};
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),
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),
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),
82 pub fn write_output_file(
83 handler: &errors::Handler,
84 target: llvm::TargetMachineRef,
85 pm: llvm::PassManagerRef,
88 file_type: llvm::FileType) -> Result<(), FatalError> {
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))
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.
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 = [
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))
123 sess.target.target.options.features,
124 llvm_features.collect::<Vec<_>>().join(","))
127 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
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,
137 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
139 config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
140 config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
141 _ => llvm::CodeGenOptSizeNone,
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))
151 pub fn target_machine_factory(sess: &Session)
152 -> Arc<Fn() -> Result<TargetMachineRef, String> + Send + Sync>
154 let reloc_model = get_reloc_model(sess);
156 let opt_level = get_llvm_opt_level(sess.opts.optimize);
157 let use_softfp = sess.opts.cg.soft_float;
159 let ffunction_sections = sess.target.target.options.function_sections;
160 let fdata_sections = ffunction_sections;
162 let code_model_arg = match sess.opts.cg.code_model {
164 None => &sess.target.target.options.code_model,
167 let code_model = match CODE_GEN_MODEL_ARGS.iter().find(
168 |&&arg| arg.0 == code_model_arg) {
171 sess.err(&format!("{:?} is not a valid code model",
175 sess.abort_if_errors();
180 let triple = &sess.target.target.llvm_target;
182 let triple = CString::new(triple.as_bytes()).unwrap();
183 let cpu = match sess.opts.cg.target_cpu {
185 None => &*sess.target.target.options.cpu
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);
193 llvm::LLVMRustCreateTargetMachine(
194 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
206 Err(format!("Could not create LLVM TargetMachine for triple: {}",
207 triple.to_str().unwrap()))
214 /// Module-specific configuration for `optimize_and_codegen`.
215 pub struct ModuleConfig {
216 /// Names of additional optimization passes to run.
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>,
222 /// Some(level) to optimize binary size, or None to not affect program size.
223 opt_size: Option<llvm::CodeGenOptSize>,
225 // Flags indicating which outputs to produce.
226 emit_no_opt_bc: bool,
232 // Miscellaneous flags. These are mostly copied from command-line
235 no_prepopulate_passes: bool,
238 vectorize_loop: 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,
249 fn new(passes: Vec<String>) -> ModuleConfig {
255 emit_no_opt_bc: false,
261 obj_is_bitcode: false,
264 no_prepopulate_passes: false,
267 vectorize_loop: false,
268 vectorize_slp: false,
269 merge_functions: false,
270 inline_threshold: None
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;
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;
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;
295 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
296 sess.opts.optimize == config::OptLevel::Aggressive;
300 /// Additional resources used by optimize_and_codegen (not module specific)
302 pub struct CodegenContext {
303 // Resouces needed when running LTO
304 pub time_passes: 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>,
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.
324 // Worker thread number
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>,
336 impl CodegenContext {
337 pub fn create_diag_handler(&self) -> Handler {
338 Handler::with_emitter(true, false, Box::new(self.diag_emitter.clone()))
341 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
343 ModuleKind::Regular => &self.regular_module_config,
344 ModuleKind::Metadata => &self.metadata_module_config,
345 ModuleKind::Allocator => &self.allocator_module_config,
349 pub fn save_temp_bitcode(&self, trans: &ModuleTranslation, name: &str) {
350 if !self.save_temps {
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());
364 struct DiagnosticHandlers<'a> {
365 inner: Box<(&'a CodegenContext, &'a Handler)>,
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));
375 let arg = &*data as &(_, _) as *const _ as *mut _;
376 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, arg);
377 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, arg);
386 impl<'a> Drop for DiagnosticHandlers<'a> {
389 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, 0 as *mut _);
390 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, 0 as *mut _);
395 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext,
398 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_string());
401 unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
407 let (cgcx, _) = *(user as *const (&CodegenContext, &Handler));
409 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
410 .expect("non-UTF8 SMDiagnostic");
412 report_inline_asm(cgcx, &msg, cookie);
415 unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
419 let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler));
421 match llvm::diagnostic::Diagnostic::unpack(info) {
422 llvm::diagnostic::InlineAsm(inline) => {
423 report_inline_asm(cgcx,
424 &llvm::twine_to_string(inline.message),
428 llvm::diagnostic::Optimization(opt) => {
429 let enabled = match cgcx.remark {
431 SomePasses(ref v) => v.iter().any(|s| *s == opt.pass_name),
435 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
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>
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")
463 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
465 let module_name = mtrans.name.clone();
466 let module_name = Some(&module_name[..]);
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());
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();
482 // If we're verifying or linting, add them to the function pass
484 let addpass = |pass_name: &str| {
485 let pass_name = CString::new(pass_name).unwrap();
486 let pass = llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr());
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");
498 llvm::LLVMRustAddPass(pass_manager, pass);
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);
512 for pass in &config.passes {
514 diag_handler.warn(&format!("unknown pass `{}`, ignoring",
519 for pass in &cgcx.plugin_passes {
521 diag_handler.err(&format!("a plugin asked for LLVM pass \
522 `{}` but LLVM does not \
523 recognize it", pass));
527 diag_handler.abort_if_errors();
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));
535 // Deallocate managers that we're now done with
536 llvm::LLVMDisposePassManager(fpm);
537 llvm::LLVMDisposePassManager(mpm);
542 fn generate_lto_work(cgcx: &CodegenContext,
543 modules: Vec<ModuleTranslation>)
544 -> Vec<(WorkItem, u64)>
546 let lto_modules = lto::run(cgcx, modules).unwrap_or_else(|e| panic!(e));
548 lto_modules.into_iter().map(|module| {
549 let cost = module.cost();
550 (WorkItem::LTO(module), cost)
554 unsafe fn codegen(cgcx: &CodegenContext,
555 diag_handler: &Handler,
556 mtrans: ModuleTranslation,
557 config: &ModuleConfig)
558 -> Result<CompiledModule, FatalError>
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")
566 let module_name = mtrans.name.clone();
567 let module_name = Some(&module_name[..]);
568 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
570 // A codegen-specific pass manager is used to generate object
571 // files for an LLVM module.
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
578 unsafe fn with_codegen<F, R>(tm: TargetMachineRef,
582 where F: FnOnce(PassManagerRef) -> R,
584 let cpm = llvm::LLVMCreatePassManager();
585 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
586 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
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;
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);
603 let bc_out_c = path2cstr(&bc_out);
604 llvm::LLVMWriteBitcodeToFile(llmod, bc_out_c.as_ptr());
607 time(config.time_passes, &format!("codegen passes [{}]", module_name.unwrap()),
608 || -> Result<(), FatalError> {
610 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
611 let out = path2cstr(&out);
613 extern "C" fn demangle_callback(input_ptr: *const c_char,
615 output_ptr: *mut c_char,
616 output_len: size_t) -> size_t {
618 slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
621 let input = match str::from_utf8(input) {
626 let output = unsafe {
627 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
629 let mut cursor = io::Cursor::new(output);
631 let demangled = match rustc_demangle::try_demangle(input) {
636 if let Err(_) = write!(cursor, "{:#}", demangled) {
637 // Possible only if provided buffer is not big enough
641 cursor.position() as size_t
644 with_codegen(tm, llmod, config.no_builtins, |cpm| {
645 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
646 llvm::LLVMDisposePassManager(cpm);
651 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
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)
661 with_codegen(tm, llmod, config.no_builtins, |cpm| {
662 write_output_file(diag_handler, tm, cpm, llmod, &path,
663 llvm::FileType::AssemblyFile)
666 llvm::LLVMDisposeModule(llmod);
671 with_codegen(tm, llmod, config.no_builtins, |cpm| {
672 write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
673 llvm::FileType::ObjectFile)
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));
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));
695 Ok(mtrans.into_compiled_module(config.emit_obj,
697 &cgcx.output_filenames))
700 pub struct CompiledModules {
701 pub modules: Vec<CompiledModule>,
702 pub metadata_module: CompiledModule,
703 pub allocator_module: Option<CompiledModule>,
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)
711 pub fn start_async_translation(tcx: TyCtxt,
712 time_graph: Option<TimeGraph>,
714 metadata: EncodedMetadata,
715 coordinator_receive: Receiver<Box<Any + Send>>)
716 -> OngoingCrateTranslation {
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",
729 subsystem.to_string()
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);
739 let output_types_override = if no_integrated_as {
740 OutputTypes::new(&[(OutputType::Assembly, None)])
742 sess.opts.output_types.clone()
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![]);
750 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
752 Sanitizer::Address => {
753 modules_config.passes.push("asan".to_owned());
754 modules_config.passes.push("asan-module".to_owned());
756 Sanitizer::Memory => {
757 modules_config.passes.push("msan".to_owned())
759 Sanitizer::Thread => {
760 modules_config.passes.push("tsan".to_owned())
766 if sess.opts.debugging_opts.profile {
767 modules_config.passes.push("insert-gcov-profiling".to_owned())
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));
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;
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;
789 for output_type in output_types_override.keys() {
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;
803 OutputType::Object => { modules_config.emit_obj = true; }
804 OutputType::Metadata => { metadata_config.emit_obj = true; }
806 modules_config.emit_obj = true;
807 metadata_config.emit_obj = true;
808 allocator_config.emit_obj = true;
810 OutputType::Mir => {}
811 OutputType::DepInfo => {}
815 modules_config.set_flags(sess, no_builtins);
816 metadata_config.set_flags(sess, no_builtins);
817 allocator_config.set_flags(sess, no_builtins);
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;
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")
831 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
832 let (trans_worker_send, trans_worker_receive) = channel();
834 let coordinator_thread = start_executing_work(tcx,
841 Arc::new(modules_config),
842 Arc::new(metadata_config),
843 Arc::new(allocator_config));
845 OngoingCrateTranslation {
855 coordinator_send: tcx.tx_to_llvm_workers.clone(),
856 trans_worker_receive,
858 future: coordinator_thread,
859 output_filenames: tcx.output_filenames(LOCAL_CRATE),
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() {
871 for module in compiled_modules.modules.iter() {
872 let mut files = vec![];
875 let path = crate_output.temp_path(OutputType::Object, Some(&module.name));
876 files.push((OutputType::Object, path));
880 let path = crate_output.temp_path(OutputType::Bitcode, Some(&module.name));
881 files.push((OutputType::Bitcode, path));
884 save_trans_partition(sess,
887 module.symbol_name_hash,
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;
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));
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`.
919 let ext = crate_output.temp_path(output_type, None)
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));
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.)
944 // Flag to indicate whether the user explicitly requested bitcode.
945 // Otherwise, we produced it only as a temporary output, and will need
947 for output_type in crate_output.outputs.keys() {
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);
956 OutputType::LlvmAssembly => {
957 copy_if_one_unit(OutputType::LlvmAssembly, false);
959 OutputType::Assembly => {
960 copy_if_one_unit(OutputType::Assembly, false);
962 OutputType::Object => {
963 user_wants_objects = true;
964 copy_if_one_unit(OutputType::Object, true);
967 OutputType::Metadata |
969 OutputType::DepInfo => {}
973 // Clean up unwanted temporary files.
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).
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
991 // Specific rules for keeping .#module-name#.bc:
992 // - If we're building an rlib (`needs_crate_bitcode`), then keep
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
1003 let needs_crate_bitcode = need_crate_bitcode_for_rlib(sess);
1004 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
1006 let keep_numbered_bitcode = needs_crate_bitcode ||
1007 (user_wants_bitcode && sess.opts.codegen_units > 1);
1009 let keep_numbered_objects = needs_crate_object ||
1010 (user_wants_objects && sess.opts.codegen_units > 1);
1012 for module in compiled_modules.modules.iter() {
1013 let module_name = Some(&module.name[..]);
1015 if module.emit_obj && !keep_numbered_objects {
1016 let path = crate_output.temp_path(OutputType::Object, module_name);
1017 remove(sess, &path);
1020 if module.emit_bc && !keep_numbered_bitcode {
1021 let path = crate_output.temp_path(OutputType::Bitcode, module_name);
1022 remove(sess, &path);
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);
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);
1041 // We leave the following files around by default:
1043 // - #crate#.crate.metadata.o
1045 // These are used in linking steps and will be cleaned up afterward.
1048 pub fn dump_incremental_data(trans: &CrateTranslation) {
1050 for mtrans in trans.modules.iter() {
1051 if mtrans.pre_existing {
1055 eprintln!("incremental: re-using {} out of {} modules", reuse, trans.modules.len());
1059 Optimize(ModuleTranslation),
1060 LTO(lto::LtoModuleTranslation),
1064 fn kind(&self) -> ModuleKind {
1066 WorkItem::Optimize(ref m) => m.kind,
1067 WorkItem::LTO(_) => ModuleKind::Regular,
1071 fn name(&self) -> String {
1073 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
1074 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
1079 enum WorkItemResult {
1080 Compiled(CompiledModule),
1081 NeedsLTO(ModuleTranslation),
1084 fn execute_work_item(cgcx: &CodegenContext, work_item: WorkItem)
1085 -> Result<WorkItemResult, FatalError>
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) => {
1093 let module = lto.optimize(cgcx)?;
1094 let module = codegen(cgcx, &diag_handler, module, config)?;
1095 return Ok(WorkItemResult::Compiled(module))
1099 let module_name = mtrans.name.clone();
1101 let pre_existing = match mtrans.source {
1102 ModuleSource::Translated(_) => None,
1103 ModuleSource::Preexisting(ref wp) => Some(wp.clone()),
1106 if let Some(wp) = pre_existing {
1107 let incr_comp_session_dir = cgcx.incr_comp_session_dir
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,
1115 debug!("copying pre-existing module `{}` from {:?} to {}",
1119 match link_or_copy(&source_file, &obj_out) {
1122 diag_handler.err(&format!("unable to copy {} to {}: {}",
1123 source_file.display(),
1129 let object = cgcx.output_filenames.temp_path(OutputType::Object, Some(name));
1131 Ok(WorkItemResult::Compiled(CompiledModule {
1133 llmod_id: mtrans.llmod_id.clone(),
1135 kind: ModuleKind::Regular,
1137 symbol_name_hash: mtrans.symbol_name_hash,
1138 emit_bc: config.emit_bc,
1139 emit_obj: config.emit_obj,
1142 debug!("llvm-optimizing {:?}", module_name);
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))
1150 Ok(WorkItemResult::NeedsLTO(mtrans))
1157 Token(io::Result<Acquired>),
1159 result: ModuleTranslation,
1163 result: Result<CompiledModule, ()>,
1167 llvm_work_item: WorkItem,
1170 TranslationComplete,
1176 code: Option<String>,
1180 #[derive(PartialEq, Clone, Copy, Debug)]
1181 enum MainThreadWorkerState {
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>>,
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));
1204 let exported_symbols = Arc::new(exported_symbols);
1205 let sess = tcx.sess;
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
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.
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");
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) {
1227 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1230 let cgcx = CodegenContext {
1231 crate_types: sess.crate_types.borrow().clone(),
1232 each_linked_rlib_for_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(),
1239 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1240 remark: sess.opts.cg.remark.clone(),
1242 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1244 diag_emitter: shared_emitter.clone(),
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),
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.
1257 // There are a few environmental pre-conditions that shape how the system
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`.
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.
1283 // Work Processing Infrastructure
1284 // ==============================
1285 // The work processing infrastructure knows three major actors:
1287 // - the coordinator thread,
1288 // - the main thread, and
1289 // - LLVM worker threads
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.
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
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.
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.
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.
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).
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
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.
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.
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.
1374 // LTO and the coordinator thread
1375 // ------------------------------
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
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:
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() {
1399 let id = worker_id_counter;
1400 worker_id_counter += 1;
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;
1413 // This flag tracks whether all items have gone through translations
1414 let mut translation_done = false;
1416 // This is the queue of LLVM work items that still need processing.
1417 let mut work_items = Vec::<(WorkItem, u64)>::new();
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();
1423 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1424 let mut running = 0;
1426 let mut llvm_start_time = None;
1428 // Run the message loop while there's still anything that needs message
1430 while !translation_done ||
1431 work_items.len() > 0 ||
1433 needs_lto.len() > 0 ||
1434 main_thread_worker_state != MainThreadWorkerState::Idle {
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")
1446 main_thread_worker_state = MainThreadWorkerState::Translating;
1448 // The queue is full enough to not let the worker
1449 // threads starve. Use the implicit Token to do some
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),
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);
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
1469 if work_items.len() == 0 &&
1471 main_thread_worker_state == MainThreadWorkerState::Idle {
1472 assert!(!started_lto);
1473 assert!(needs_lto.len() > 0);
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();
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),
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);
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);
1508 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1511 MainThreadWorkerState::Translating => {
1512 bug!("trans worker should not be translating after \
1513 translation was already completed")
1515 MainThreadWorkerState::LLVMing => {
1516 // Already making good use of that token
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();
1526 maybe_start_llvm_timer(cgcx.config(item.kind()),
1527 &mut llvm_start_time);
1529 let cgcx = CodegenContext {
1530 worker: get_worker_id(&mut free_worker_ids),
1534 spawn_work(cgcx, item);
1538 // Relinquish accidentally acquired extra tokens
1539 tokens.truncate(running);
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) => {
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;
1561 let msg = &format!("failed to acquire jobserver token: {}", e);
1562 shared_emitter.fatal(msg);
1563 // Exit the coordinator thread
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
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
1583 work_items.insert(insertion_index, (llvm_work_item, cost));
1585 helper.request_token();
1586 assert_eq!(main_thread_worker_state,
1587 MainThreadWorkerState::Translating);
1588 main_thread_worker_state = MainThreadWorkerState::Idle;
1591 Message::TranslationComplete => {
1592 translation_done = true;
1593 assert_eq!(main_thread_worker_state,
1594 MainThreadWorkerState::Translating);
1595 main_thread_worker_state = MainThreadWorkerState::Idle;
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"
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;
1613 free_worker_ids.push(worker_id);
1615 match compiled_module.kind {
1616 ModuleKind::Regular => {
1617 compiled_modules.push(compiled_module);
1619 ModuleKind::Metadata => {
1620 assert!(compiled_metadata_module.is_none());
1621 compiled_metadata_module = Some(compiled_module);
1623 ModuleKind::Allocator => {
1624 assert!(compiled_allocator_module.is_none());
1625 compiled_allocator_module = Some(compiled_module);
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;
1637 free_worker_ids.push(worker_id);
1638 needs_lto.push(result);
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")
1645 Message::TranslateItem => {
1646 bug!("the coordinator should not receive translation requests")
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
1656 print_time_passes_entry(cgcx.time_passes,
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));
1666 let compiled_metadata_module = compiled_metadata_module
1667 .expect("Metadata module not compiled?");
1670 modules: compiled_modules,
1671 metadata_module: compiled_metadata_module,
1672 allocator_module: compiled_allocator_module,
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 {
1682 items_in_queue > 0 &&
1683 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
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());
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"]);
1706 fn spawn_work(cgcx: CodegenContext, work: WorkItem) {
1707 let depth = time_depth();
1709 thread::spawn(move || {
1710 set_time_depth(depth);
1712 // Set up a destructor which will fire off a message that we're done as
1715 coordinator_send: Sender<Box<Any + Send>>,
1716 result: Option<WorkItemResult>,
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 }
1726 Some(WorkItemResult::NeedsLTO(m)) => {
1727 Message::NeedsLTO { result: m, worker_id }
1729 None => Message::Done { result: Err(()), worker_id }
1731 drop(self.coordinator_send.send(Box::new(msg)));
1735 let mut bomb = Bomb {
1736 coordinator_send: cgcx.coordinator_send.clone(),
1738 worker_id: cgcx.worker,
1741 // Execute the work itself, and if it finishes successfully then flag
1742 // ourselves as a success as well.
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.
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.
1755 let _timing_guard = cgcx.time_graph.as_ref().map(|tg| {
1756 tg.start(time_graph::TimelineId(cgcx.worker),
1757 LLVM_WORK_PACKAGE_KIND,
1760 Some(execute_work_item(&cgcx, work).unwrap())
1765 pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
1766 let (pname, mut cmd, _) = get_linker(sess);
1768 for arg in &sess.target.target.options.asm_args {
1772 cmd.arg("-c").arg("-o").arg(&outputs.path(OutputType::Object))
1773 .arg(&outputs.temp_path(OutputType::Assembly, None));
1774 debug!("{:?}", cmd);
1776 match cmd.output() {
1778 if !prog.status.success() {
1779 let mut note = prog.stderr.clone();
1780 note.extend_from_slice(&prog.stdout);
1782 sess.struct_err(&format!("linking with `{}` failed: {}",
1785 .note(&format!("{:?}", &cmd))
1786 .note(str::from_utf8(¬e[..]).unwrap())
1788 sess.abort_if_errors();
1792 sess.err(&format!("could not exec the linker `{}`: {}", pname, e));
1793 sess.abort_if_errors();
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
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;
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);
1815 if opt_size != llvm::CodeGenOptSizeNone {
1816 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
1819 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
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) {
1827 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
1829 (llvm::CodeGenOptLevel::Aggressive, ..) => {
1830 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
1832 (_, llvm::CodeGenOptSizeDefault, _) => {
1833 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
1835 (_, llvm::CodeGenOptSizeAggressive, _) => {
1836 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
1838 (llvm::CodeGenOptLevel::None, ..) => {
1839 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
1841 (llvm::CodeGenOptLevel::Less, ..) => {
1842 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
1844 (llvm::CodeGenOptLevel::Default, ..) => {
1845 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1847 (llvm::CodeGenOptLevel::Other, ..) => {
1848 bug!("CodeGenOptLevel::Other selected")
1853 llvm::LLVMPassManagerBuilderDispose(builder);
1857 enum SharedEmitterMessage {
1858 Diagnostic(Diagnostic),
1859 InlineAsmError(u32, String),
1865 pub struct SharedEmitter {
1866 sender: Sender<SharedEmitterMessage>,
1869 pub struct SharedEmitterMain {
1870 receiver: Receiver<SharedEmitterMessage>,
1873 impl SharedEmitter {
1874 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1875 let (sender, receiver) = channel();
1877 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1880 fn inline_asm_error(&self, cookie: u32, msg: String) {
1881 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
1884 fn fatal(&self, msg: &str) {
1885 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1889 impl Emitter for SharedEmitter {
1890 fn emit(&mut self, db: &DiagnosticBuilder) {
1891 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1893 code: db.code.clone(),
1896 for child in &db.children {
1897 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1898 msg: child.message(),
1903 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1907 impl SharedEmitterMain {
1908 pub fn check(&self, sess: &Session, blocking: bool) {
1910 let message = if blocking {
1911 match self.receiver.recv() {
1912 Ok(message) => Ok(message),
1916 match self.receiver.try_recv() {
1917 Ok(message) => Ok(message),
1923 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1924 let handler = sess.diagnostic();
1927 handler.emit_with_code(&MultiSpan::new(),
1933 handler.emit(&MultiSpan::new(),
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),
1945 Ok(SharedEmitterMessage::AbortIfErrors) => {
1946 sess.abort_if_errors();
1948 Ok(SharedEmitterMessage::Fatal(msg)) => {
1960 pub struct OngoingCrateTranslation {
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>,
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,
1982 sess.fatal("Error during translation/LLVM phase.");
1986 sess.abort_if_errors();
1988 if let Some(time_graph) = self.time_graph {
1989 time_graph.dump(&format!("{}-timings", self.crate_name));
1992 copy_module_artifacts_into_incr_comp_cache(sess,
1995 &self.output_filenames);
1996 produce_final_output_artifacts(sess,
1998 &self.output_filenames);
2000 // FIXME: time_llvm_passes support - does this use a global context or
2002 if sess.opts.codegen_units == 1 && sess.time_llvm_passes() {
2003 unsafe { llvm::LLVMRustPrintPassTimings(); }
2006 let trans = CrateTranslation {
2007 crate_name: self.crate_name,
2009 metadata: self.metadata,
2010 windows_subsystem: self.windows_subsystem,
2011 linker_info: self.linker_info,
2012 crate_info: self.crate_info,
2014 modules: compiled_modules.modules,
2015 allocator_module: compiled_modules.allocator_module,
2018 if self.no_integrated_as {
2019 run_assembler(sess, &self.output_filenames);
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();
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();
2041 pub fn submit_pre_translated_module_to_llvm(&self,
2043 mtrans: ModuleTranslation) {
2044 self.wait_for_signal_to_translate_item();
2045 self.check_for_errors(tcx.sess);
2047 // These are generally cheap and won't through off scheduling.
2049 submit_translated_module_to_llvm(tcx, mtrans, cost);
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)));
2058 pub fn check_for_errors(&self, sess: &Session) {
2059 self.shared_emitter_main.check(sess, false);
2062 pub fn wait_for_signal_to_translate_item(&self) {
2063 match self.trans_worker_receive.recv() {
2064 Ok(Message::TranslateItem) => {
2067 Ok(_) => panic!("unexpected message"),
2069 // One of the LLVM threads must have panicked, fall through so
2070 // error handling can be reached.
2076 pub fn submit_translated_module_to_llvm(tcx: TyCtxt,
2077 mtrans: ModuleTranslation,
2079 let llvm_work_item = WorkItem::Optimize(mtrans);
2080 drop(tcx.tx_to_llvm_workers.send(Box::new(Message::TranslationDone {