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.
11 use back::bytecode::{self, RLIB_BYTECODE_EXTENSION};
12 use back::lto::{self, ModuleBuffer, ThinBuffer};
13 use back::link::{self, get_linker, remove};
14 use back::command::Command;
15 use back::linker::LinkerInfo;
16 use back::symbol_export::ExportedSymbols;
19 use rustc_incremental::{save_trans_partition, in_incr_comp_dir};
20 use rustc::dep_graph::{DepGraph, WorkProductFileKind};
21 use rustc::middle::cstore::{LinkMeta, EncodedMetadata};
22 use rustc::session::config::{self, OutputFilenames, OutputType, Passes, SomePasses,
23 AllPasses, Sanitizer, Lto};
24 use rustc::session::Session;
25 use rustc::util::nodemap::FxHashMap;
26 use rustc_back::LinkerFlavor;
27 use time_graph::{self, TimeGraph, Timeline};
29 use llvm::{ModuleRef, TargetMachineRef, PassManagerRef, DiagnosticInfoRef};
30 use llvm::{SMDiagnosticRef, ContextRef};
31 use {CrateTranslation, ModuleSource, ModuleTranslation, CompiledModule, ModuleKind};
33 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
34 use rustc::ty::TyCtxt;
35 use rustc::util::common::{time, time_depth, set_time_depth, path2cstr, print_time_passes_entry};
36 use rustc::util::fs::{link_or_copy};
37 use errors::{self, Handler, Level, DiagnosticBuilder, FatalError, DiagnosticId};
38 use errors::emitter::{Emitter};
40 use syntax::ext::hygiene::Mark;
41 use syntax_pos::MultiSpan;
42 use syntax_pos::symbol::Symbol;
44 use context::{is_pie_binary, get_reloc_model};
45 use jobserver::{Client, Acquired};
49 use std::ffi::{CString, CStr};
51 use std::io::{self, Write};
53 use std::path::{Path, PathBuf};
56 use std::sync::mpsc::{channel, Sender, Receiver};
58 use std::time::Instant;
60 use libc::{c_uint, c_void, c_char, size_t};
62 pub const RELOC_MODEL_ARGS : [(&'static str, llvm::RelocMode); 7] = [
63 ("pic", llvm::RelocMode::PIC),
64 ("static", llvm::RelocMode::Static),
65 ("default", llvm::RelocMode::Default),
66 ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
67 ("ropi", llvm::RelocMode::ROPI),
68 ("rwpi", llvm::RelocMode::RWPI),
69 ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
72 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
73 ("small", llvm::CodeModel::Small),
74 ("kernel", llvm::CodeModel::Kernel),
75 ("medium", llvm::CodeModel::Medium),
76 ("large", llvm::CodeModel::Large),
79 pub const TLS_MODEL_ARGS : [(&'static str, llvm::ThreadLocalMode); 4] = [
80 ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
81 ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
82 ("initial-exec", llvm::ThreadLocalMode::InitialExec),
83 ("local-exec", llvm::ThreadLocalMode::LocalExec),
86 pub fn llvm_err(handler: &errors::Handler, msg: String) -> FatalError {
87 match llvm::last_error() {
88 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
89 None => handler.fatal(&msg),
93 pub fn write_output_file(
94 handler: &errors::Handler,
95 target: llvm::TargetMachineRef,
96 pm: llvm::PassManagerRef,
99 file_type: llvm::FileType) -> Result<(), FatalError> {
101 let output_c = path2cstr(output);
102 let result = llvm::LLVMRustWriteOutputFile(
103 target, pm, m, output_c.as_ptr(), file_type);
104 if result.into_result().is_err() {
105 let msg = format!("could not write output to {}", output.display());
106 Err(llvm_err(handler, msg))
113 // On android, we by default compile for armv7 processors. This enables
114 // things like double word CAS instructions (rather than emulating them)
115 // which are *far* more efficient. This is obviously undesirable in some
116 // cases, so if any sort of target feature is specified we don't append v7
117 // to the feature list.
119 // On iOS only armv7 and newer are supported. So it is useful to
120 // get all hardware potential via VFP3 (hardware floating point)
121 // and NEON (SIMD) instructions supported by LLVM.
122 // Note that without those flags various linking errors might
123 // arise as some of intrinsics are converted into function calls
124 // and nobody provides implementations those functions
125 fn target_feature(sess: &Session) -> String {
126 let rustc_features = [
129 let requested_features = sess.opts.cg.target_feature.split(',');
130 let llvm_features = requested_features.filter(|f| {
131 !rustc_features.iter().any(|s| f.contains(s))
134 sess.target.target.options.features,
135 llvm_features.collect::<Vec<_>>().join(","))
138 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
140 config::OptLevel::No => llvm::CodeGenOptLevel::None,
141 config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
142 config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
143 config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
144 _ => llvm::CodeGenOptLevel::Default,
148 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
150 config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
151 config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
152 _ => llvm::CodeGenOptSizeNone,
156 pub fn create_target_machine(sess: &Session) -> TargetMachineRef {
157 target_machine_factory(sess)().unwrap_or_else(|err| {
158 panic!(llvm_err(sess.diagnostic(), err))
162 pub fn target_machine_factory(sess: &Session)
163 -> Arc<Fn() -> Result<TargetMachineRef, String> + Send + Sync>
165 let reloc_model = get_reloc_model(sess);
167 let opt_level = get_llvm_opt_level(sess.opts.optimize);
168 let use_softfp = sess.opts.cg.soft_float;
170 let ffunction_sections = sess.target.target.options.function_sections;
171 let fdata_sections = ffunction_sections;
173 let code_model_arg = sess.opts.cg.code_model.as_ref().or(
174 sess.target.target.options.code_model.as_ref(),
177 let code_model = match code_model_arg {
179 match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
182 sess.err(&format!("{:?} is not a valid code model",
184 sess.abort_if_errors();
189 None => llvm::CodeModel::None,
192 let singlethread = sess.target.target.options.singlethread;
194 let triple = &sess.target.target.llvm_target;
196 let triple = CString::new(triple.as_bytes()).unwrap();
197 let cpu = match sess.opts.cg.target_cpu {
199 None => &*sess.target.target.options.cpu
201 let cpu = CString::new(cpu.as_bytes()).unwrap();
202 let features = CString::new(target_feature(sess).as_bytes()).unwrap();
203 let is_pie_binary = is_pie_binary(sess);
204 let trap_unreachable = sess.target.target.options.trap_unreachable;
208 llvm::LLVMRustCreateTargetMachine(
209 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
223 Err(format!("Could not create LLVM TargetMachine for triple: {}",
224 triple.to_str().unwrap()))
231 /// Module-specific configuration for `optimize_and_codegen`.
232 pub struct ModuleConfig {
233 /// Names of additional optimization passes to run.
235 /// Some(level) to optimize at a certain level, or None to run
236 /// absolutely no optimizations (used for the metadata module).
237 pub opt_level: Option<llvm::CodeGenOptLevel>,
239 /// Some(level) to optimize binary size, or None to not affect program size.
240 opt_size: Option<llvm::CodeGenOptSize>,
242 // Flags indicating which outputs to produce.
243 emit_no_opt_bc: bool,
245 emit_bc_compressed: bool,
250 // Miscellaneous flags. These are mostly copied from command-line
253 no_prepopulate_passes: bool,
256 vectorize_loop: bool,
258 merge_functions: bool,
259 inline_threshold: Option<usize>,
260 // Instead of creating an object file by doing LLVM codegen, just
261 // make the object file bitcode. Provides easy compatibility with
262 // emscripten's ecc compiler, when used as the linker.
263 obj_is_bitcode: bool,
264 no_integrated_as: bool,
268 fn new(passes: Vec<String>) -> ModuleConfig {
274 emit_no_opt_bc: false,
276 emit_bc_compressed: false,
281 obj_is_bitcode: false,
282 no_integrated_as: false,
285 no_prepopulate_passes: false,
288 vectorize_loop: false,
289 vectorize_slp: false,
290 merge_functions: false,
291 inline_threshold: None
295 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
296 self.no_verify = sess.no_verify();
297 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
298 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
299 self.time_passes = sess.time_passes();
300 self.inline_threshold = sess.opts.cg.inline_threshold;
301 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode;
303 // Copy what clang does by turning on loop vectorization at O2 and
304 // slp vectorization at O3. Otherwise configure other optimization aspects
305 // of this pass manager builder.
306 // Turn off vectorization for emscripten, as it's not very well supported.
307 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
308 (sess.opts.optimize == config::OptLevel::Default ||
309 sess.opts.optimize == config::OptLevel::Aggressive) &&
310 !sess.target.target.options.is_like_emscripten;
312 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
313 sess.opts.optimize == config::OptLevel::Aggressive &&
314 !sess.target.target.options.is_like_emscripten;
316 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
317 sess.opts.optimize == config::OptLevel::Aggressive;
321 /// Assembler name and command used by codegen when no_integrated_as is enabled
322 struct AssemblerCommand {
327 /// Additional resources used by optimize_and_codegen (not module specific)
329 pub struct CodegenContext {
330 // Resouces needed when running LTO
331 pub time_passes: bool,
333 pub no_landing_pads: bool,
334 pub save_temps: bool,
335 pub fewer_names: bool,
336 pub exported_symbols: Arc<ExportedSymbols>,
337 pub opts: Arc<config::Options>,
338 pub crate_types: Vec<config::CrateType>,
339 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
340 output_filenames: Arc<OutputFilenames>,
341 regular_module_config: Arc<ModuleConfig>,
342 metadata_module_config: Arc<ModuleConfig>,
343 allocator_module_config: Arc<ModuleConfig>,
344 pub tm_factory: Arc<Fn() -> Result<TargetMachineRef, String> + Send + Sync>,
345 pub msvc_imps_needed: bool,
346 pub target_pointer_width: String,
347 binaryen_linker: bool,
348 debuginfo: config::DebugInfoLevel,
349 wasm_import_memory: bool,
351 // Number of cgus excluding the allocator/metadata modules
352 pub total_cgus: usize,
353 // Handler to use for diagnostics produced during codegen.
354 pub diag_emitter: SharedEmitter,
355 // LLVM passes added by plugins.
356 pub plugin_passes: Vec<String>,
357 // LLVM optimizations for which we want to print remarks.
359 // Worker thread number
361 // The incremental compilation session directory, or None if we are not
362 // compiling incrementally
363 pub incr_comp_session_dir: Option<PathBuf>,
364 // Channel back to the main control thread to send messages to
365 coordinator_send: Sender<Box<Any + Send>>,
366 // A reference to the TimeGraph so we can register timings. None means that
367 // measuring is disabled.
368 time_graph: Option<TimeGraph>,
369 // The assembler command if no_integrated_as option is enabled, None otherwise
370 assembler_cmd: Option<Arc<AssemblerCommand>>,
373 impl CodegenContext {
374 pub fn create_diag_handler(&self) -> Handler {
375 Handler::with_emitter(true, false, Box::new(self.diag_emitter.clone()))
378 pub(crate) fn config(&self, kind: ModuleKind) -> &ModuleConfig {
380 ModuleKind::Regular => &self.regular_module_config,
381 ModuleKind::Metadata => &self.metadata_module_config,
382 ModuleKind::Allocator => &self.allocator_module_config,
386 pub(crate) fn save_temp_bitcode(&self, trans: &ModuleTranslation, name: &str) {
387 if !self.save_temps {
391 let ext = format!("{}.bc", name);
392 let cgu = Some(&trans.name[..]);
393 let path = self.output_filenames.temp_path_ext(&ext, cgu);
394 let cstr = path2cstr(&path);
395 let llmod = trans.llvm().unwrap().llmod;
396 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
401 struct DiagnosticHandlers<'a> {
402 inner: Box<(&'a CodegenContext, &'a Handler)>,
406 impl<'a> DiagnosticHandlers<'a> {
407 fn new(cgcx: &'a CodegenContext,
408 handler: &'a Handler,
409 llcx: ContextRef) -> DiagnosticHandlers<'a> {
410 let data = Box::new((cgcx, handler));
412 let arg = &*data as &(_, _) as *const _ as *mut _;
413 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, arg);
414 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, arg);
423 impl<'a> Drop for DiagnosticHandlers<'a> {
426 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, 0 as *mut _);
427 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, 0 as *mut _);
432 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext,
435 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_string());
438 unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
444 let (cgcx, _) = *(user as *const (&CodegenContext, &Handler));
446 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
447 .expect("non-UTF8 SMDiagnostic");
449 report_inline_asm(cgcx, &msg, cookie);
452 unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
456 let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler));
458 match llvm::diagnostic::Diagnostic::unpack(info) {
459 llvm::diagnostic::InlineAsm(inline) => {
460 report_inline_asm(cgcx,
461 &llvm::twine_to_string(inline.message),
465 llvm::diagnostic::Optimization(opt) => {
466 let enabled = match cgcx.remark {
468 SomePasses(ref v) => v.iter().any(|s| *s == opt.pass_name),
472 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
486 // Unsafe due to LLVM calls.
487 unsafe fn optimize(cgcx: &CodegenContext,
488 diag_handler: &Handler,
489 mtrans: &ModuleTranslation,
490 config: &ModuleConfig,
491 timeline: &mut Timeline)
492 -> Result<(), FatalError>
494 let (llmod, llcx, tm) = match mtrans.source {
495 ModuleSource::Translated(ref llvm) => (llvm.llmod, llvm.llcx, llvm.tm),
496 ModuleSource::Preexisting(_) => {
497 bug!("optimize_and_codegen: called with ModuleSource::Preexisting")
501 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
503 let module_name = mtrans.name.clone();
504 let module_name = Some(&module_name[..]);
506 if config.emit_no_opt_bc {
507 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
508 let out = path2cstr(&out);
509 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
512 if config.opt_level.is_some() {
513 // Create the two optimizing pass managers. These mirror what clang
514 // does, and are by populated by LLVM's default PassManagerBuilder.
515 // Each manager has a different set of passes, but they also share
516 // some common passes.
517 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
518 let mpm = llvm::LLVMCreatePassManager();
520 // If we're verifying or linting, add them to the function pass
522 let addpass = |pass_name: &str| {
523 let pass_name = CString::new(pass_name).unwrap();
524 let pass = llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr());
528 let pass_manager = match llvm::LLVMRustPassKind(pass) {
529 llvm::PassKind::Function => fpm,
530 llvm::PassKind::Module => mpm,
531 llvm::PassKind::Other => {
532 diag_handler.err("Encountered LLVM pass kind we can't handle");
536 llvm::LLVMRustAddPass(pass_manager, pass);
540 if !config.no_verify { assert!(addpass("verify")); }
541 if !config.no_prepopulate_passes {
542 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
543 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
544 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
545 with_llvm_pmb(llmod, &config, opt_level, &mut |b| {
546 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
547 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
551 for pass in &config.passes {
553 diag_handler.warn(&format!("unknown pass `{}`, ignoring",
558 for pass in &cgcx.plugin_passes {
560 diag_handler.err(&format!("a plugin asked for LLVM pass \
561 `{}` but LLVM does not \
562 recognize it", pass));
566 diag_handler.abort_if_errors();
568 // Finally, run the actual optimization passes
569 time(config.time_passes, &format!("llvm function passes [{}]", module_name.unwrap()), ||
570 llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
571 timeline.record("fpm");
572 time(config.time_passes, &format!("llvm module passes [{}]", module_name.unwrap()), ||
573 llvm::LLVMRunPassManager(mpm, llmod));
575 // Deallocate managers that we're now done with
576 llvm::LLVMDisposePassManager(fpm);
577 llvm::LLVMDisposePassManager(mpm);
582 fn generate_lto_work(cgcx: &CodegenContext,
583 modules: Vec<ModuleTranslation>)
584 -> Vec<(WorkItem, u64)>
586 let mut timeline = cgcx.time_graph.as_ref().map(|tg| {
587 tg.start(TRANS_WORKER_TIMELINE,
588 TRANS_WORK_PACKAGE_KIND,
590 }).unwrap_or(Timeline::noop());
591 let lto_modules = lto::run(cgcx, modules, &mut timeline)
592 .unwrap_or_else(|e| panic!(e));
594 lto_modules.into_iter().map(|module| {
595 let cost = module.cost();
596 (WorkItem::LTO(module), cost)
600 unsafe fn codegen(cgcx: &CodegenContext,
601 diag_handler: &Handler,
602 mtrans: ModuleTranslation,
603 config: &ModuleConfig,
604 timeline: &mut Timeline)
605 -> Result<CompiledModule, FatalError>
607 timeline.record("codegen");
608 let (llmod, llcx, tm) = match mtrans.source {
609 ModuleSource::Translated(ref llvm) => (llvm.llmod, llvm.llcx, llvm.tm),
610 ModuleSource::Preexisting(_) => {
611 bug!("codegen: called with ModuleSource::Preexisting")
614 let module_name = mtrans.name.clone();
615 let module_name = Some(&module_name[..]);
616 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
618 if cgcx.msvc_imps_needed {
619 create_msvc_imps(cgcx, llcx, llmod);
622 // A codegen-specific pass manager is used to generate object
623 // files for an LLVM module.
625 // Apparently each of these pass managers is a one-shot kind of
626 // thing, so we create a new one for each type of output. The
627 // pass manager passed to the closure should be ensured to not
628 // escape the closure itself, and the manager should only be
630 unsafe fn with_codegen<F, R>(tm: TargetMachineRef,
634 where F: FnOnce(PassManagerRef) -> R,
636 let cpm = llvm::LLVMCreatePassManager();
637 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
638 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
642 // If we're going to generate wasm code from the assembly that llvm
643 // generates then we'll be transitively affecting a ton of options below.
644 // This only happens on the wasm target now.
645 let asm2wasm = cgcx.binaryen_linker &&
646 !cgcx.crate_types.contains(&config::CrateTypeRlib) &&
647 mtrans.kind == ModuleKind::Regular;
649 // If we don't have the integrated assembler, then we need to emit asm
650 // from LLVM and use `gcc` to create the object file.
651 let asm_to_obj = config.emit_obj && config.no_integrated_as;
653 // Change what we write and cleanup based on whether obj files are
654 // just llvm bitcode. In that case write bitcode, and possibly
655 // delete the bitcode if it wasn't requested. Don't generate the
656 // machine code, instead copy the .o file from the .bc
657 let write_bc = config.emit_bc || (config.obj_is_bitcode && !asm2wasm);
658 let rm_bc = !config.emit_bc && config.obj_is_bitcode && !asm2wasm;
659 let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm2wasm && !asm_to_obj;
660 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode && !asm2wasm;
662 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
663 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
666 if write_bc || config.emit_bc_compressed {
669 let data = if llvm::LLVMRustThinLTOAvailable() {
670 thin = ThinBuffer::new(llmod);
673 old = ModuleBuffer::new(llmod);
676 timeline.record("make-bc");
679 if let Err(e) = fs::write(&bc_out, data) {
680 diag_handler.err(&format!("failed to write bytecode: {}", e));
682 timeline.record("write-bc");
685 if config.emit_bc_compressed {
686 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
687 let data = bytecode::encode(&mtrans.llmod_id, data);
688 if let Err(e) = fs::write(&dst, data) {
689 diag_handler.err(&format!("failed to write bytecode: {}", e));
691 timeline.record("compress-bc");
695 time(config.time_passes, &format!("codegen passes [{}]", module_name.unwrap()),
696 || -> Result<(), FatalError> {
698 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
699 let out = path2cstr(&out);
701 extern "C" fn demangle_callback(input_ptr: *const c_char,
703 output_ptr: *mut c_char,
704 output_len: size_t) -> size_t {
706 slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
709 let input = match str::from_utf8(input) {
714 let output = unsafe {
715 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
717 let mut cursor = io::Cursor::new(output);
719 let demangled = match rustc_demangle::try_demangle(input) {
724 if let Err(_) = write!(cursor, "{:#}", demangled) {
725 // Possible only if provided buffer is not big enough
729 cursor.position() as size_t
732 with_codegen(tm, llmod, config.no_builtins, |cpm| {
733 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
734 llvm::LLVMDisposePassManager(cpm);
736 timeline.record("ir");
739 if config.emit_asm || (asm2wasm && config.emit_obj) || asm_to_obj {
740 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
742 // We can't use the same module for asm and binary output, because that triggers
743 // various errors like invalid IR or broken binaries, so we might have to clone the
744 // module to produce the asm output
745 let llmod = if config.emit_obj && !asm2wasm {
746 llvm::LLVMCloneModule(llmod)
750 with_codegen(tm, llmod, config.no_builtins, |cpm| {
751 write_output_file(diag_handler, tm, cpm, llmod, &path,
752 llvm::FileType::AssemblyFile)
754 if config.emit_obj && !asm2wasm {
755 llvm::LLVMDisposeModule(llmod);
757 timeline.record("asm");
760 if asm2wasm && config.emit_obj {
761 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
762 binaryen_assemble(cgcx, diag_handler, &assembly, &obj_out);
763 timeline.record("binaryen");
765 if !config.emit_asm {
766 drop(fs::remove_file(&assembly));
768 } else if write_obj {
769 with_codegen(tm, llmod, config.no_builtins, |cpm| {
770 write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
771 llvm::FileType::ObjectFile)
773 timeline.record("obj");
774 } else if asm_to_obj {
775 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
776 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
777 timeline.record("asm_to_obj");
779 if !config.emit_asm && !cgcx.save_temps {
780 drop(fs::remove_file(&assembly));
788 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
789 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
790 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
795 debug!("removing_bitcode {:?}", bc_out);
796 if let Err(e) = fs::remove_file(&bc_out) {
797 diag_handler.err(&format!("failed to remove bitcode: {}", e));
802 Ok(mtrans.into_compiled_module(config.emit_obj,
804 config.emit_bc_compressed,
805 &cgcx.output_filenames))
808 /// Translates the LLVM-generated `assembly` on the filesystem into a wasm
809 /// module using binaryen, placing the output at `object`.
811 /// In this case the "object" is actually a full and complete wasm module. We
812 /// won't actually be doing anything else to the output for now. This is all
813 /// pretty janky and will get removed as soon as a linker for wasm exists.
814 fn binaryen_assemble(cgcx: &CodegenContext,
818 use rustc_binaryen::{Module, ModuleOptions};
820 let input = fs::read(&assembly).and_then(|contents| {
821 Ok(CString::new(contents)?)
823 let mut options = ModuleOptions::new();
824 if cgcx.debuginfo != config::NoDebugInfo {
825 options.debuginfo(true);
827 if cgcx.crate_types.contains(&config::CrateTypeExecutable) {
828 options.start("main");
830 options.stack(1024 * 1024);
831 options.import_memory(cgcx.wasm_import_memory);
832 let assembled = input.and_then(|input| {
833 Module::new(&input, &options)
834 .map_err(|e| io::Error::new(io::ErrorKind::Other, e))
836 let err = assembled.and_then(|binary| {
837 fs::write(&object, binary.data())
839 if let Err(e) = err {
840 handler.err(&format!("failed to run binaryen assembler: {}", e));
844 pub(crate) struct CompiledModules {
845 pub modules: Vec<CompiledModule>,
846 pub metadata_module: CompiledModule,
847 pub allocator_module: Option<CompiledModule>,
850 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
851 sess.crate_types.borrow().contains(&config::CrateTypeRlib) &&
852 sess.opts.output_types.contains_key(&OutputType::Exe)
855 pub fn start_async_translation(tcx: TyCtxt,
856 time_graph: Option<TimeGraph>,
858 metadata: EncodedMetadata,
859 coordinator_receive: Receiver<Box<Any + Send>>,
861 -> OngoingCrateTranslation {
863 let crate_name = tcx.crate_name(LOCAL_CRATE);
864 let no_builtins = attr::contains_name(&tcx.hir.krate().attrs, "no_builtins");
865 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir.krate().attrs,
866 "windows_subsystem");
867 let windows_subsystem = subsystem.map(|subsystem| {
868 if subsystem != "windows" && subsystem != "console" {
869 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
870 `windows` and `console` are allowed",
873 subsystem.to_string()
876 let linker_info = LinkerInfo::new(tcx);
877 let crate_info = CrateInfo::new(tcx);
879 // Figure out what we actually need to build.
880 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
881 let mut metadata_config = ModuleConfig::new(vec![]);
882 let mut allocator_config = ModuleConfig::new(vec![]);
884 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
886 Sanitizer::Address => {
887 modules_config.passes.push("asan".to_owned());
888 modules_config.passes.push("asan-module".to_owned());
890 Sanitizer::Memory => {
891 modules_config.passes.push("msan".to_owned())
893 Sanitizer::Thread => {
894 modules_config.passes.push("tsan".to_owned())
900 if sess.opts.debugging_opts.profile {
901 modules_config.passes.push("insert-gcov-profiling".to_owned())
904 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
905 modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
907 // Save all versions of the bytecode if we're saving our temporaries.
908 if sess.opts.cg.save_temps {
909 modules_config.emit_no_opt_bc = true;
910 modules_config.emit_bc = true;
911 modules_config.emit_lto_bc = true;
912 metadata_config.emit_bc = true;
913 allocator_config.emit_bc = true;
916 // Emit compressed bitcode files for the crate if we're emitting an rlib.
917 // Whenever an rlib is created, the bitcode is inserted into the archive in
918 // order to allow LTO against it.
919 if need_crate_bitcode_for_rlib(sess) {
920 modules_config.emit_bc_compressed = true;
921 allocator_config.emit_bc_compressed = true;
924 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
925 tcx.sess.target.target.options.no_integrated_as;
927 for output_type in sess.opts.output_types.keys() {
929 OutputType::Bitcode => { modules_config.emit_bc = true; }
930 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
931 OutputType::Assembly => {
932 modules_config.emit_asm = true;
933 // If we're not using the LLVM assembler, this function
934 // could be invoked specially with output_type_assembly, so
935 // in this case we still want the metadata object file.
936 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
937 metadata_config.emit_obj = true;
938 allocator_config.emit_obj = true;
941 OutputType::Object => { modules_config.emit_obj = true; }
942 OutputType::Metadata => { metadata_config.emit_obj = true; }
944 modules_config.emit_obj = true;
945 metadata_config.emit_obj = true;
946 allocator_config.emit_obj = true;
948 OutputType::Mir => {}
949 OutputType::DepInfo => {}
953 modules_config.set_flags(sess, no_builtins);
954 metadata_config.set_flags(sess, no_builtins);
955 allocator_config.set_flags(sess, no_builtins);
957 // Exclude metadata and allocator modules from time_passes output, since
958 // they throw off the "LLVM passes" measurement.
959 metadata_config.time_passes = false;
960 allocator_config.time_passes = false;
962 let client = sess.jobserver_from_env.clone().unwrap_or_else(|| {
963 // Pick a "reasonable maximum" if we don't otherwise have a jobserver in
964 // our environment, capping out at 32 so we don't take everything down
965 // by hogging the process run queue.
966 Client::new(32).expect("failed to create jobserver")
969 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
970 let (trans_worker_send, trans_worker_receive) = channel();
972 let coordinator_thread = start_executing_work(tcx,
980 Arc::new(modules_config),
981 Arc::new(metadata_config),
982 Arc::new(allocator_config));
984 OngoingCrateTranslation {
993 coordinator_send: tcx.tx_to_llvm_workers.clone(),
994 trans_worker_receive,
996 future: coordinator_thread,
997 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1001 fn copy_module_artifacts_into_incr_comp_cache(sess: &Session,
1002 dep_graph: &DepGraph,
1003 compiled_modules: &CompiledModules) {
1004 if sess.opts.incremental.is_none() {
1008 for module in compiled_modules.modules.iter() {
1009 let mut files = vec![];
1011 if let Some(ref path) = module.object {
1012 files.push((WorkProductFileKind::Object, path.clone()));
1014 if let Some(ref path) = module.bytecode {
1015 files.push((WorkProductFileKind::Bytecode, path.clone()));
1017 if let Some(ref path) = module.bytecode_compressed {
1018 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
1021 save_trans_partition(sess, dep_graph, &module.name, &files);
1025 fn produce_final_output_artifacts(sess: &Session,
1026 compiled_modules: &CompiledModules,
1027 crate_output: &OutputFilenames) {
1028 let mut user_wants_bitcode = false;
1029 let mut user_wants_objects = false;
1031 // Produce final compile outputs.
1032 let copy_gracefully = |from: &Path, to: &Path| {
1033 if let Err(e) = fs::copy(from, to) {
1034 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
1038 let copy_if_one_unit = |output_type: OutputType,
1039 keep_numbered: bool| {
1040 if compiled_modules.modules.len() == 1 {
1041 // 1) Only one codegen unit. In this case it's no difficulty
1042 // to copy `foo.0.x` to `foo.x`.
1043 let module_name = Some(&compiled_modules.modules[0].name[..]);
1044 let path = crate_output.temp_path(output_type, module_name);
1045 copy_gracefully(&path,
1046 &crate_output.path(output_type));
1047 if !sess.opts.cg.save_temps && !keep_numbered {
1048 // The user just wants `foo.x`, not `foo.#module-name#.x`.
1049 remove(sess, &path);
1052 let ext = crate_output.temp_path(output_type, None)
1059 if crate_output.outputs.contains_key(&output_type) {
1060 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
1061 // no good solution for this case, so warn the user.
1062 sess.warn(&format!("ignoring emit path because multiple .{} files \
1063 were produced", ext));
1064 } else if crate_output.single_output_file.is_some() {
1065 // 3) Multiple codegen units, with `-o some_name`. We have
1066 // no good solution for this case, so warn the user.
1067 sess.warn(&format!("ignoring -o because multiple .{} files \
1068 were produced", ext));
1070 // 4) Multiple codegen units, but no explicit name. We
1071 // just leave the `foo.0.x` files in place.
1072 // (We don't have to do any work in this case.)
1077 // Flag to indicate whether the user explicitly requested bitcode.
1078 // Otherwise, we produced it only as a temporary output, and will need
1079 // to get rid of it.
1080 for output_type in crate_output.outputs.keys() {
1081 match *output_type {
1082 OutputType::Bitcode => {
1083 user_wants_bitcode = true;
1084 // Copy to .bc, but always keep the .0.bc. There is a later
1085 // check to figure out if we should delete .0.bc files, or keep
1086 // them for making an rlib.
1087 copy_if_one_unit(OutputType::Bitcode, true);
1089 OutputType::LlvmAssembly => {
1090 copy_if_one_unit(OutputType::LlvmAssembly, false);
1092 OutputType::Assembly => {
1093 copy_if_one_unit(OutputType::Assembly, false);
1095 OutputType::Object => {
1096 user_wants_objects = true;
1097 copy_if_one_unit(OutputType::Object, true);
1100 OutputType::Metadata |
1102 OutputType::DepInfo => {}
1106 // Clean up unwanted temporary files.
1108 // We create the following files by default:
1109 // - #crate#.#module-name#.bc
1110 // - #crate#.#module-name#.o
1111 // - #crate#.crate.metadata.bc
1112 // - #crate#.crate.metadata.o
1113 // - #crate#.o (linked from crate.##.o)
1114 // - #crate#.bc (copied from crate.##.bc)
1115 // We may create additional files if requested by the user (through
1116 // `-C save-temps` or `--emit=` flags).
1118 if !sess.opts.cg.save_temps {
1119 // Remove the temporary .#module-name#.o objects. If the user didn't
1120 // explicitly request bitcode (with --emit=bc), and the bitcode is not
1121 // needed for building an rlib, then we must remove .#module-name#.bc as
1124 // Specific rules for keeping .#module-name#.bc:
1125 // - If the user requested bitcode (`user_wants_bitcode`), and
1126 // codegen_units > 1, then keep it.
1127 // - If the user requested bitcode but codegen_units == 1, then we
1128 // can toss .#module-name#.bc because we copied it to .bc earlier.
1129 // - If we're not building an rlib and the user didn't request
1130 // bitcode, then delete .#module-name#.bc.
1131 // If you change how this works, also update back::link::link_rlib,
1132 // where .#module-name#.bc files are (maybe) deleted after making an
1134 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
1136 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
1138 let keep_numbered_objects = needs_crate_object ||
1139 (user_wants_objects && sess.codegen_units() > 1);
1141 for module in compiled_modules.modules.iter() {
1142 if let Some(ref path) = module.object {
1143 if !keep_numbered_objects {
1148 if let Some(ref path) = module.bytecode {
1149 if !keep_numbered_bitcode {
1155 if !user_wants_bitcode {
1156 if let Some(ref path) = compiled_modules.metadata_module.bytecode {
1157 remove(sess, &path);
1160 if let Some(ref allocator_module) = compiled_modules.allocator_module {
1161 if let Some(ref path) = allocator_module.bytecode {
1168 // We leave the following files around by default:
1170 // - #crate#.crate.metadata.o
1172 // These are used in linking steps and will be cleaned up afterward.
1175 pub(crate) fn dump_incremental_data(trans: &CrateTranslation) {
1176 println!("[incremental] Re-using {} out of {} modules",
1177 trans.modules.iter().filter(|m| m.pre_existing).count(),
1178 trans.modules.len());
1182 Optimize(ModuleTranslation),
1183 LTO(lto::LtoModuleTranslation),
1187 fn kind(&self) -> ModuleKind {
1189 WorkItem::Optimize(ref m) => m.kind,
1190 WorkItem::LTO(_) => ModuleKind::Regular,
1194 fn name(&self) -> String {
1196 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
1197 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
1202 enum WorkItemResult {
1203 Compiled(CompiledModule),
1204 NeedsLTO(ModuleTranslation),
1207 fn execute_work_item(cgcx: &CodegenContext,
1208 work_item: WorkItem,
1209 timeline: &mut Timeline)
1210 -> Result<WorkItemResult, FatalError>
1212 let diag_handler = cgcx.create_diag_handler();
1213 let config = cgcx.config(work_item.kind());
1214 let mtrans = match work_item {
1215 WorkItem::Optimize(mtrans) => mtrans,
1216 WorkItem::LTO(mut lto) => {
1218 let module = lto.optimize(cgcx, timeline)?;
1219 let module = codegen(cgcx, &diag_handler, module, config, timeline)?;
1220 return Ok(WorkItemResult::Compiled(module))
1224 let module_name = mtrans.name.clone();
1226 let pre_existing = match mtrans.source {
1227 ModuleSource::Translated(_) => None,
1228 ModuleSource::Preexisting(ref wp) => Some(wp.clone()),
1231 if let Some(wp) = pre_existing {
1232 let incr_comp_session_dir = cgcx.incr_comp_session_dir
1235 let name = &mtrans.name;
1236 let mut object = None;
1237 let mut bytecode = None;
1238 let mut bytecode_compressed = None;
1239 for (kind, saved_file) in wp.saved_files {
1240 let obj_out = match kind {
1241 WorkProductFileKind::Object => {
1242 let path = cgcx.output_filenames.temp_path(OutputType::Object, Some(name));
1243 object = Some(path.clone());
1246 WorkProductFileKind::Bytecode => {
1247 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(name));
1248 bytecode = Some(path.clone());
1251 WorkProductFileKind::BytecodeCompressed => {
1252 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(name))
1253 .with_extension(RLIB_BYTECODE_EXTENSION);
1254 bytecode_compressed = Some(path.clone());
1258 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
1260 debug!("copying pre-existing module `{}` from {:?} to {}",
1264 match link_or_copy(&source_file, &obj_out) {
1267 diag_handler.err(&format!("unable to copy {} to {}: {}",
1268 source_file.display(),
1274 assert_eq!(object.is_some(), config.emit_obj);
1275 assert_eq!(bytecode.is_some(), config.emit_bc);
1276 assert_eq!(bytecode_compressed.is_some(), config.emit_bc_compressed);
1278 Ok(WorkItemResult::Compiled(CompiledModule {
1279 llmod_id: mtrans.llmod_id.clone(),
1281 kind: ModuleKind::Regular,
1285 bytecode_compressed,
1288 debug!("llvm-optimizing {:?}", module_name);
1291 optimize(cgcx, &diag_handler, &mtrans, config, timeline)?;
1293 // After we've done the initial round of optimizations we need to
1294 // decide whether to synchronously codegen this module or ship it
1295 // back to the coordinator thread for further LTO processing (which
1296 // has to wait for all the initial modules to be optimized).
1298 // Here we dispatch based on the `cgcx.lto` and kind of module we're
1300 let needs_lto = match cgcx.lto {
1303 // Here we've got a full crate graph LTO requested. We ignore
1304 // this, however, if the crate type is only an rlib as there's
1305 // no full crate graph to process, that'll happen later.
1307 // This use case currently comes up primarily for targets that
1308 // require LTO so the request for LTO is always unconditionally
1309 // passed down to the backend, but we don't actually want to do
1310 // anything about it yet until we've got a final product.
1311 Lto::Yes | Lto::Fat | Lto::Thin => {
1312 cgcx.crate_types.len() != 1 ||
1313 cgcx.crate_types[0] != config::CrateTypeRlib
1316 // When we're automatically doing ThinLTO for multi-codegen-unit
1317 // builds we don't actually want to LTO the allocator modules if
1318 // it shows up. This is due to various linker shenanigans that
1319 // we'll encounter later.
1321 // Additionally here's where we also factor in the current LLVM
1322 // version. If it doesn't support ThinLTO we skip this.
1324 mtrans.kind != ModuleKind::Allocator &&
1325 llvm::LLVMRustThinLTOAvailable()
1329 // Metadata modules never participate in LTO regardless of the lto
1331 let needs_lto = needs_lto && mtrans.kind != ModuleKind::Metadata;
1334 Ok(WorkItemResult::NeedsLTO(mtrans))
1336 let module = codegen(cgcx, &diag_handler, mtrans, config, timeline)?;
1337 Ok(WorkItemResult::Compiled(module))
1344 Token(io::Result<Acquired>),
1346 result: ModuleTranslation,
1350 result: Result<CompiledModule, ()>,
1354 llvm_work_item: WorkItem,
1357 TranslationComplete,
1363 code: Option<DiagnosticId>,
1367 #[derive(PartialEq, Clone, Copy, Debug)]
1368 enum MainThreadWorkerState {
1374 fn start_executing_work(tcx: TyCtxt,
1375 crate_info: &CrateInfo,
1376 shared_emitter: SharedEmitter,
1377 trans_worker_send: Sender<Message>,
1378 coordinator_receive: Receiver<Box<Any + Send>>,
1381 time_graph: Option<TimeGraph>,
1382 modules_config: Arc<ModuleConfig>,
1383 metadata_config: Arc<ModuleConfig>,
1384 allocator_config: Arc<ModuleConfig>)
1385 -> thread::JoinHandle<Result<CompiledModules, ()>> {
1386 let coordinator_send = tcx.tx_to_llvm_workers.clone();
1387 let mut exported_symbols = FxHashMap();
1388 exported_symbols.insert(LOCAL_CRATE, tcx.exported_symbols(LOCAL_CRATE));
1389 for &cnum in tcx.crates().iter() {
1390 exported_symbols.insert(cnum, tcx.exported_symbols(cnum));
1392 let exported_symbols = Arc::new(exported_symbols);
1393 let sess = tcx.sess;
1395 // First up, convert our jobserver into a helper thread so we can use normal
1396 // mpsc channels to manage our messages and such.
1397 // After we've requested tokens then we'll, when we can,
1398 // get tokens on `coordinator_receive` which will
1399 // get managed in the main loop below.
1400 let coordinator_send2 = coordinator_send.clone();
1401 let helper = jobserver.into_helper_thread(move |token| {
1402 drop(coordinator_send2.send(Box::new(Message::Token(token))));
1403 }).expect("failed to spawn helper thread");
1405 let mut each_linked_rlib_for_lto = Vec::new();
1406 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1407 if link::ignored_for_lto(sess, crate_info, cnum) {
1410 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1413 let wasm_import_memory =
1414 attr::contains_name(&tcx.hir.krate().attrs, "wasm_import_memory");
1416 let assembler_cmd = if modules_config.no_integrated_as {
1417 // HACK: currently we use linker (gcc) as our assembler
1418 let (name, mut cmd, _) = get_linker(sess);
1419 cmd.args(&sess.target.target.options.asm_args);
1420 Some(Arc::new(AssemblerCommand {
1428 let cgcx = CodegenContext {
1429 crate_types: sess.crate_types.borrow().clone(),
1430 each_linked_rlib_for_lto,
1432 no_landing_pads: sess.no_landing_pads(),
1433 fewer_names: sess.fewer_names(),
1434 save_temps: sess.opts.cg.save_temps,
1435 opts: Arc::new(sess.opts.clone()),
1436 time_passes: sess.time_passes(),
1438 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1439 remark: sess.opts.cg.remark.clone(),
1441 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1443 diag_emitter: shared_emitter.clone(),
1445 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1446 regular_module_config: modules_config,
1447 metadata_module_config: metadata_config,
1448 allocator_module_config: allocator_config,
1449 tm_factory: target_machine_factory(tcx.sess),
1451 msvc_imps_needed: msvc_imps_needed(tcx),
1452 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1453 binaryen_linker: tcx.sess.linker_flavor() == LinkerFlavor::Binaryen,
1454 debuginfo: tcx.sess.opts.debuginfo,
1455 wasm_import_memory: wasm_import_memory,
1459 // This is the "main loop" of parallel work happening for parallel codegen.
1460 // It's here that we manage parallelism, schedule work, and work with
1461 // messages coming from clients.
1463 // There are a few environmental pre-conditions that shape how the system
1466 // - Error reporting only can happen on the main thread because that's the
1467 // only place where we have access to the compiler `Session`.
1468 // - LLVM work can be done on any thread.
1469 // - Translation can only happen on the main thread.
1470 // - Each thread doing substantial work most be in possession of a `Token`
1471 // from the `Jobserver`.
1472 // - The compiler process always holds one `Token`. Any additional `Tokens`
1473 // have to be requested from the `Jobserver`.
1477 // The error reporting restriction is handled separately from the rest: We
1478 // set up a `SharedEmitter` the holds an open channel to the main thread.
1479 // When an error occurs on any thread, the shared emitter will send the
1480 // error message to the receiver main thread (`SharedEmitterMain`). The
1481 // main thread will periodically query this error message queue and emit
1482 // any error messages it has received. It might even abort compilation if
1483 // has received a fatal error. In this case we rely on all other threads
1484 // being torn down automatically with the main thread.
1485 // Since the main thread will often be busy doing translation work, error
1486 // reporting will be somewhat delayed, since the message queue can only be
1487 // checked in between to work packages.
1489 // Work Processing Infrastructure
1490 // ==============================
1491 // The work processing infrastructure knows three major actors:
1493 // - the coordinator thread,
1494 // - the main thread, and
1495 // - LLVM worker threads
1497 // The coordinator thread is running a message loop. It instructs the main
1498 // thread about what work to do when, and it will spawn off LLVM worker
1499 // threads as open LLVM WorkItems become available.
1501 // The job of the main thread is to translate CGUs into LLVM work package
1502 // (since the main thread is the only thread that can do this). The main
1503 // thread will block until it receives a message from the coordinator, upon
1504 // which it will translate one CGU, send it to the coordinator and block
1505 // again. This way the coordinator can control what the main thread is
1508 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1509 // available, it will spawn off a new LLVM worker thread and let it process
1510 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1511 // it will just shut down, which also frees all resources associated with
1512 // the given LLVM module, and sends a message to the coordinator that the
1513 // has been completed.
1517 // The scheduler's goal is to minimize the time it takes to complete all
1518 // work there is, however, we also want to keep memory consumption low
1519 // if possible. These two goals are at odds with each other: If memory
1520 // consumption were not an issue, we could just let the main thread produce
1521 // LLVM WorkItems at full speed, assuring maximal utilization of
1522 // Tokens/LLVM worker threads. However, since translation usual is faster
1523 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1524 // WorkItem potentially holds on to a substantial amount of memory.
1526 // So the actual goal is to always produce just enough LLVM WorkItems as
1527 // not to starve our LLVM worker threads. That means, once we have enough
1528 // WorkItems in our queue, we can block the main thread, so it does not
1529 // produce more until we need them.
1531 // Doing LLVM Work on the Main Thread
1532 // ----------------------------------
1533 // Since the main thread owns the compiler processes implicit `Token`, it is
1534 // wasteful to keep it blocked without doing any work. Therefore, what we do
1535 // in this case is: We spawn off an additional LLVM worker thread that helps
1536 // reduce the queue. The work it is doing corresponds to the implicit
1537 // `Token`. The coordinator will mark the main thread as being busy with
1538 // LLVM work. (The actual work happens on another OS thread but we just care
1539 // about `Tokens`, not actual threads).
1541 // When any LLVM worker thread finishes while the main thread is marked as
1542 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1543 // of the just finished thread to the LLVM worker thread that is working on
1544 // behalf of the main thread's implicit Token, thus freeing up the main
1545 // thread again. The coordinator can then again decide what the main thread
1546 // should do. This allows the coordinator to make decisions at more points
1549 // Striking a Balance between Throughput and Memory Consumption
1550 // ------------------------------------------------------------
1551 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1552 // memory consumption as low as possible, are in conflict with each other,
1553 // we have to find a trade off between them. Right now, the goal is to keep
1554 // all workers busy, which means that no worker should find the queue empty
1555 // when it is ready to start.
1556 // How do we do achieve this? Good question :) We actually never know how
1557 // many `Tokens` are potentially available so it's hard to say how much to
1558 // fill up the queue before switching the main thread to LLVM work. Also we
1559 // currently don't have a means to estimate how long a running LLVM worker
1560 // will still be busy with it's current WorkItem. However, we know the
1561 // maximal count of available Tokens that makes sense (=the number of CPU
1562 // cores), so we can take a conservative guess. The heuristic we use here
1563 // is implemented in the `queue_full_enough()` function.
1565 // Some Background on Jobservers
1566 // -----------------------------
1567 // It's worth also touching on the management of parallelism here. We don't
1568 // want to just spawn a thread per work item because while that's optimal
1569 // parallelism it may overload a system with too many threads or violate our
1570 // configuration for the maximum amount of cpu to use for this process. To
1571 // manage this we use the `jobserver` crate.
1573 // Job servers are an artifact of GNU make and are used to manage
1574 // parallelism between processes. A jobserver is a glorified IPC semaphore
1575 // basically. Whenever we want to run some work we acquire the semaphore,
1576 // and whenever we're done with that work we release the semaphore. In this
1577 // manner we can ensure that the maximum number of parallel workers is
1578 // capped at any one point in time.
1580 // LTO and the coordinator thread
1581 // ------------------------------
1583 // The final job the coordinator thread is responsible for is managing LTO
1584 // and how that works. When LTO is requested what we'll to is collect all
1585 // optimized LLVM modules into a local vector on the coordinator. Once all
1586 // modules have been translated and optimized we hand this to the `lto`
1587 // module for further optimization. The `lto` module will return back a list
1588 // of more modules to work on, which the coordinator will continue to spawn
1591 // Each LLVM module is automatically sent back to the coordinator for LTO if
1592 // necessary. There's already optimizations in place to avoid sending work
1593 // back to the coordinator if LTO isn't requested.
1594 return thread::spawn(move || {
1595 // We pretend to be within the top-level LLVM time-passes task here:
1598 let max_workers = ::num_cpus::get();
1599 let mut worker_id_counter = 0;
1600 let mut free_worker_ids = Vec::new();
1601 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1602 if let Some(id) = free_worker_ids.pop() {
1605 let id = worker_id_counter;
1606 worker_id_counter += 1;
1611 // This is where we collect codegen units that have gone all the way
1612 // through translation and LLVM.
1613 let mut compiled_modules = vec![];
1614 let mut compiled_metadata_module = None;
1615 let mut compiled_allocator_module = None;
1616 let mut needs_lto = Vec::new();
1617 let mut started_lto = false;
1619 // This flag tracks whether all items have gone through translations
1620 let mut translation_done = false;
1622 // This is the queue of LLVM work items that still need processing.
1623 let mut work_items = Vec::<(WorkItem, u64)>::new();
1625 // This are the Jobserver Tokens we currently hold. Does not include
1626 // the implicit Token the compiler process owns no matter what.
1627 let mut tokens = Vec::new();
1629 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1630 let mut running = 0;
1632 let mut llvm_start_time = None;
1634 // Run the message loop while there's still anything that needs message
1636 while !translation_done ||
1637 work_items.len() > 0 ||
1639 needs_lto.len() > 0 ||
1640 main_thread_worker_state != MainThreadWorkerState::Idle {
1642 // While there are still CGUs to be translated, the coordinator has
1643 // to decide how to utilize the compiler processes implicit Token:
1644 // For translating more CGU or for running them through LLVM.
1645 if !translation_done {
1646 if main_thread_worker_state == MainThreadWorkerState::Idle {
1647 if !queue_full_enough(work_items.len(), running, max_workers) {
1648 // The queue is not full enough, translate more items:
1649 if let Err(_) = trans_worker_send.send(Message::TranslateItem) {
1650 panic!("Could not send Message::TranslateItem to main thread")
1652 main_thread_worker_state = MainThreadWorkerState::Translating;
1654 // The queue is full enough to not let the worker
1655 // threads starve. Use the implicit Token to do some
1657 let (item, _) = work_items.pop()
1658 .expect("queue empty - queue_full_enough() broken?");
1659 let cgcx = CodegenContext {
1660 worker: get_worker_id(&mut free_worker_ids),
1663 maybe_start_llvm_timer(cgcx.config(item.kind()),
1664 &mut llvm_start_time);
1665 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1666 spawn_work(cgcx, item);
1670 // If we've finished everything related to normal translation
1671 // then it must be the case that we've got some LTO work to do.
1672 // Perform the serial work here of figuring out what we're
1673 // going to LTO and then push a bunch of work items onto our
1675 if work_items.len() == 0 &&
1677 main_thread_worker_state == MainThreadWorkerState::Idle {
1678 assert!(!started_lto);
1679 assert!(needs_lto.len() > 0);
1681 let modules = mem::replace(&mut needs_lto, Vec::new());
1682 for (work, cost) in generate_lto_work(&cgcx, modules) {
1683 let insertion_index = work_items
1684 .binary_search_by_key(&cost, |&(_, cost)| cost)
1685 .unwrap_or_else(|e| e);
1686 work_items.insert(insertion_index, (work, cost));
1687 helper.request_token();
1691 // In this branch, we know that everything has been translated,
1692 // so it's just a matter of determining whether the implicit
1693 // Token is free to use for LLVM work.
1694 match main_thread_worker_state {
1695 MainThreadWorkerState::Idle => {
1696 if let Some((item, _)) = work_items.pop() {
1697 let cgcx = CodegenContext {
1698 worker: get_worker_id(&mut free_worker_ids),
1701 maybe_start_llvm_timer(cgcx.config(item.kind()),
1702 &mut llvm_start_time);
1703 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1704 spawn_work(cgcx, item);
1706 // There is no unstarted work, so let the main thread
1707 // take over for a running worker. Otherwise the
1708 // implicit token would just go to waste.
1709 // We reduce the `running` counter by one. The
1710 // `tokens.truncate()` below will take care of
1711 // giving the Token back.
1712 debug_assert!(running > 0);
1714 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1717 MainThreadWorkerState::Translating => {
1718 bug!("trans worker should not be translating after \
1719 translation was already completed")
1721 MainThreadWorkerState::LLVMing => {
1722 // Already making good use of that token
1727 // Spin up what work we can, only doing this while we've got available
1728 // parallelism slots and work left to spawn.
1729 while work_items.len() > 0 && running < tokens.len() {
1730 let (item, _) = work_items.pop().unwrap();
1732 maybe_start_llvm_timer(cgcx.config(item.kind()),
1733 &mut llvm_start_time);
1735 let cgcx = CodegenContext {
1736 worker: get_worker_id(&mut free_worker_ids),
1740 spawn_work(cgcx, item);
1744 // Relinquish accidentally acquired extra tokens
1745 tokens.truncate(running);
1747 let msg = coordinator_receive.recv().unwrap();
1748 match *msg.downcast::<Message>().ok().unwrap() {
1749 // Save the token locally and the next turn of the loop will use
1750 // this to spawn a new unit of work, or it may get dropped
1751 // immediately if we have no more work to spawn.
1752 Message::Token(token) => {
1757 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1758 // If the main thread token is used for LLVM work
1759 // at the moment, we turn that thread into a regular
1760 // LLVM worker thread, so the main thread is free
1761 // to react to translation demand.
1762 main_thread_worker_state = MainThreadWorkerState::Idle;
1767 let msg = &format!("failed to acquire jobserver token: {}", e);
1768 shared_emitter.fatal(msg);
1769 // Exit the coordinator thread
1775 Message::TranslationDone { llvm_work_item, cost } => {
1776 // We keep the queue sorted by estimated processing cost,
1777 // so that more expensive items are processed earlier. This
1778 // is good for throughput as it gives the main thread more
1779 // time to fill up the queue and it avoids scheduling
1780 // expensive items to the end.
1781 // Note, however, that this is not ideal for memory
1782 // consumption, as LLVM module sizes are not evenly
1784 let insertion_index =
1785 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1786 let insertion_index = match insertion_index {
1787 Ok(idx) | Err(idx) => idx
1789 work_items.insert(insertion_index, (llvm_work_item, cost));
1791 helper.request_token();
1792 assert_eq!(main_thread_worker_state,
1793 MainThreadWorkerState::Translating);
1794 main_thread_worker_state = MainThreadWorkerState::Idle;
1797 Message::TranslationComplete => {
1798 translation_done = true;
1799 assert_eq!(main_thread_worker_state,
1800 MainThreadWorkerState::Translating);
1801 main_thread_worker_state = MainThreadWorkerState::Idle;
1804 // If a thread exits successfully then we drop a token associated
1805 // with that worker and update our `running` count. We may later
1806 // re-acquire a token to continue running more work. We may also not
1807 // actually drop a token here if the worker was running with an
1808 // "ephemeral token"
1810 // Note that if the thread failed that means it panicked, so we
1811 // abort immediately.
1812 Message::Done { result: Ok(compiled_module), worker_id } => {
1813 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1814 main_thread_worker_state = MainThreadWorkerState::Idle;
1819 free_worker_ids.push(worker_id);
1821 match compiled_module.kind {
1822 ModuleKind::Regular => {
1823 compiled_modules.push(compiled_module);
1825 ModuleKind::Metadata => {
1826 assert!(compiled_metadata_module.is_none());
1827 compiled_metadata_module = Some(compiled_module);
1829 ModuleKind::Allocator => {
1830 assert!(compiled_allocator_module.is_none());
1831 compiled_allocator_module = Some(compiled_module);
1835 Message::NeedsLTO { result, worker_id } => {
1836 assert!(!started_lto);
1837 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1838 main_thread_worker_state = MainThreadWorkerState::Idle;
1843 free_worker_ids.push(worker_id);
1844 needs_lto.push(result);
1846 Message::Done { result: Err(()), worker_id: _ } => {
1847 shared_emitter.fatal("aborting due to worker thread failure");
1848 // Exit the coordinator thread
1851 Message::TranslateItem => {
1852 bug!("the coordinator should not receive translation requests")
1857 if let Some(llvm_start_time) = llvm_start_time {
1858 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
1859 // This is the top-level timing for all of LLVM, set the time-depth
1862 print_time_passes_entry(cgcx.time_passes,
1867 // Regardless of what order these modules completed in, report them to
1868 // the backend in the same order every time to ensure that we're handing
1869 // out deterministic results.
1870 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1872 let compiled_metadata_module = compiled_metadata_module
1873 .expect("Metadata module not compiled?");
1875 Ok(CompiledModules {
1876 modules: compiled_modules,
1877 metadata_module: compiled_metadata_module,
1878 allocator_module: compiled_allocator_module,
1882 // A heuristic that determines if we have enough LLVM WorkItems in the
1883 // queue so that the main thread can do LLVM work instead of translation
1884 fn queue_full_enough(items_in_queue: usize,
1885 workers_running: usize,
1886 max_workers: usize) -> bool {
1888 items_in_queue > 0 &&
1889 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1892 fn maybe_start_llvm_timer(config: &ModuleConfig,
1893 llvm_start_time: &mut Option<Instant>) {
1894 // We keep track of the -Ztime-passes output manually,
1895 // since the closure-based interface does not fit well here.
1896 if config.time_passes {
1897 if llvm_start_time.is_none() {
1898 *llvm_start_time = Some(Instant::now());
1904 pub const TRANS_WORKER_ID: usize = ::std::usize::MAX;
1905 pub const TRANS_WORKER_TIMELINE: time_graph::TimelineId =
1906 time_graph::TimelineId(TRANS_WORKER_ID);
1907 pub const TRANS_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1908 time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
1909 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1910 time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
1912 fn spawn_work(cgcx: CodegenContext, work: WorkItem) {
1913 let depth = time_depth();
1915 thread::spawn(move || {
1916 set_time_depth(depth);
1918 // Set up a destructor which will fire off a message that we're done as
1921 coordinator_send: Sender<Box<Any + Send>>,
1922 result: Option<WorkItemResult>,
1925 impl Drop for Bomb {
1926 fn drop(&mut self) {
1927 let worker_id = self.worker_id;
1928 let msg = match self.result.take() {
1929 Some(WorkItemResult::Compiled(m)) => {
1930 Message::Done { result: Ok(m), worker_id }
1932 Some(WorkItemResult::NeedsLTO(m)) => {
1933 Message::NeedsLTO { result: m, worker_id }
1935 None => Message::Done { result: Err(()), worker_id }
1937 drop(self.coordinator_send.send(Box::new(msg)));
1941 let mut bomb = Bomb {
1942 coordinator_send: cgcx.coordinator_send.clone(),
1944 worker_id: cgcx.worker,
1947 // Execute the work itself, and if it finishes successfully then flag
1948 // ourselves as a success as well.
1950 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1951 // as a diagnostic was already sent off to the main thread - just
1952 // surface that there was an error in this worker.
1954 let timeline = cgcx.time_graph.as_ref().map(|tg| {
1955 tg.start(time_graph::TimelineId(cgcx.worker),
1956 LLVM_WORK_PACKAGE_KIND,
1959 let mut timeline = timeline.unwrap_or(Timeline::noop());
1960 execute_work_item(&cgcx, work, &mut timeline).ok()
1965 pub fn run_assembler(cgcx: &CodegenContext, handler: &Handler, assembly: &Path, object: &Path) {
1966 let assembler = cgcx.assembler_cmd
1968 .expect("cgcx.assembler_cmd is missing?");
1970 let pname = &assembler.name;
1971 let mut cmd = assembler.cmd.clone();
1972 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
1973 debug!("{:?}", cmd);
1975 match cmd.output() {
1977 if !prog.status.success() {
1978 let mut note = prog.stderr.clone();
1979 note.extend_from_slice(&prog.stdout);
1981 handler.struct_err(&format!("linking with `{}` failed: {}",
1984 .note(&format!("{:?}", &cmd))
1985 .note(str::from_utf8(¬e[..]).unwrap())
1987 handler.abort_if_errors();
1991 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
1992 handler.abort_if_errors();
1997 pub unsafe fn with_llvm_pmb(llmod: ModuleRef,
1998 config: &ModuleConfig,
1999 opt_level: llvm::CodeGenOptLevel,
2000 f: &mut FnMut(llvm::PassManagerBuilderRef)) {
2001 // Create the PassManagerBuilder for LLVM. We configure it with
2002 // reasonable defaults and prepare it to actually populate the pass
2004 let builder = llvm::LLVMPassManagerBuilderCreate();
2005 let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
2006 let inline_threshold = config.inline_threshold;
2008 llvm::LLVMRustConfigurePassManagerBuilder(builder,
2010 config.merge_functions,
2011 config.vectorize_slp,
2012 config.vectorize_loop);
2013 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
2015 if opt_size != llvm::CodeGenOptSizeNone {
2016 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
2019 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
2021 // Here we match what clang does (kinda). For O0 we only inline
2022 // always-inline functions (but don't add lifetime intrinsics), at O1 we
2023 // inline with lifetime intrinsics, and O2+ we add an inliner with a
2024 // thresholds copied from clang.
2025 match (opt_level, opt_size, inline_threshold) {
2027 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
2029 (llvm::CodeGenOptLevel::Aggressive, ..) => {
2030 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
2032 (_, llvm::CodeGenOptSizeDefault, _) => {
2033 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
2035 (_, llvm::CodeGenOptSizeAggressive, _) => {
2036 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
2038 (llvm::CodeGenOptLevel::None, ..) => {
2039 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
2041 (llvm::CodeGenOptLevel::Less, ..) => {
2042 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
2044 (llvm::CodeGenOptLevel::Default, ..) => {
2045 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
2047 (llvm::CodeGenOptLevel::Other, ..) => {
2048 bug!("CodeGenOptLevel::Other selected")
2053 llvm::LLVMPassManagerBuilderDispose(builder);
2057 enum SharedEmitterMessage {
2058 Diagnostic(Diagnostic),
2059 InlineAsmError(u32, String),
2065 pub struct SharedEmitter {
2066 sender: Sender<SharedEmitterMessage>,
2069 pub struct SharedEmitterMain {
2070 receiver: Receiver<SharedEmitterMessage>,
2073 impl SharedEmitter {
2074 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
2075 let (sender, receiver) = channel();
2077 (SharedEmitter { sender }, SharedEmitterMain { receiver })
2080 fn inline_asm_error(&self, cookie: u32, msg: String) {
2081 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
2084 fn fatal(&self, msg: &str) {
2085 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2089 impl Emitter for SharedEmitter {
2090 fn emit(&mut self, db: &DiagnosticBuilder) {
2091 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2093 code: db.code.clone(),
2096 for child in &db.children {
2097 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2098 msg: child.message(),
2103 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
2107 impl SharedEmitterMain {
2108 pub fn check(&self, sess: &Session, blocking: bool) {
2110 let message = if blocking {
2111 match self.receiver.recv() {
2112 Ok(message) => Ok(message),
2116 match self.receiver.try_recv() {
2117 Ok(message) => Ok(message),
2123 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2124 let handler = sess.diagnostic();
2127 handler.emit_with_code(&MultiSpan::new(),
2133 handler.emit(&MultiSpan::new(),
2139 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
2140 match Mark::from_u32(cookie).expn_info() {
2141 Some(ei) => sess.span_err(ei.call_site, &msg),
2142 None => sess.err(&msg),
2145 Ok(SharedEmitterMessage::AbortIfErrors) => {
2146 sess.abort_if_errors();
2148 Ok(SharedEmitterMessage::Fatal(msg)) => {
2160 pub struct OngoingCrateTranslation {
2163 metadata: EncodedMetadata,
2164 windows_subsystem: Option<String>,
2165 linker_info: LinkerInfo,
2166 crate_info: CrateInfo,
2167 time_graph: Option<TimeGraph>,
2168 coordinator_send: Sender<Box<Any + Send>>,
2169 trans_worker_receive: Receiver<Message>,
2170 shared_emitter_main: SharedEmitterMain,
2171 future: thread::JoinHandle<Result<CompiledModules, ()>>,
2172 output_filenames: Arc<OutputFilenames>,
2175 impl OngoingCrateTranslation {
2176 pub(crate) fn join(self, sess: &Session, dep_graph: &DepGraph) -> CrateTranslation {
2177 self.shared_emitter_main.check(sess, true);
2178 let compiled_modules = match self.future.join() {
2179 Ok(Ok(compiled_modules)) => compiled_modules,
2181 sess.abort_if_errors();
2182 panic!("expected abort due to worker thread errors")
2185 sess.fatal("Error during translation/LLVM phase.");
2189 sess.abort_if_errors();
2191 if let Some(time_graph) = self.time_graph {
2192 time_graph.dump(&format!("{}-timings", self.crate_name));
2195 copy_module_artifacts_into_incr_comp_cache(sess,
2198 produce_final_output_artifacts(sess,
2200 &self.output_filenames);
2202 // FIXME: time_llvm_passes support - does this use a global context or
2204 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
2205 unsafe { llvm::LLVMRustPrintPassTimings(); }
2208 let trans = CrateTranslation {
2209 crate_name: self.crate_name,
2211 metadata: self.metadata,
2212 windows_subsystem: self.windows_subsystem,
2213 linker_info: self.linker_info,
2214 crate_info: self.crate_info,
2216 modules: compiled_modules.modules,
2217 allocator_module: compiled_modules.allocator_module,
2218 metadata_module: compiled_modules.metadata_module,
2224 pub(crate) fn submit_pre_translated_module_to_llvm(&self,
2226 mtrans: ModuleTranslation) {
2227 self.wait_for_signal_to_translate_item();
2228 self.check_for_errors(tcx.sess);
2230 // These are generally cheap and won't through off scheduling.
2232 submit_translated_module_to_llvm(tcx, mtrans, cost);
2235 pub fn translation_finished(&self, tcx: TyCtxt) {
2236 self.wait_for_signal_to_translate_item();
2237 self.check_for_errors(tcx.sess);
2238 drop(self.coordinator_send.send(Box::new(Message::TranslationComplete)));
2241 pub fn check_for_errors(&self, sess: &Session) {
2242 self.shared_emitter_main.check(sess, false);
2245 pub fn wait_for_signal_to_translate_item(&self) {
2246 match self.trans_worker_receive.recv() {
2247 Ok(Message::TranslateItem) => {
2250 Ok(_) => panic!("unexpected message"),
2252 // One of the LLVM threads must have panicked, fall through so
2253 // error handling can be reached.
2259 pub(crate) fn submit_translated_module_to_llvm(tcx: TyCtxt,
2260 mtrans: ModuleTranslation,
2262 let llvm_work_item = WorkItem::Optimize(mtrans);
2263 drop(tcx.tx_to_llvm_workers.send(Box::new(Message::TranslationDone {
2269 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
2270 tcx.sess.target.target.options.is_like_msvc &&
2271 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib)
2274 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2275 // This is required to satisfy `dllimport` references to static data in .rlibs
2276 // when using MSVC linker. We do this only for data, as linker can fix up
2277 // code references on its own.
2278 // See #26591, #27438
2279 fn create_msvc_imps(cgcx: &CodegenContext, llcx: ContextRef, llmod: ModuleRef) {
2280 if !cgcx.msvc_imps_needed {
2283 // The x86 ABI seems to require that leading underscores are added to symbol
2284 // names, so we need an extra underscore on 32-bit. There's also a leading
2285 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2286 // underscores added in front).
2287 let prefix = if cgcx.target_pointer_width == "32" {
2293 let i8p_ty = Type::i8p_llcx(llcx);
2294 let globals = base::iter_globals(llmod)
2296 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
2297 llvm::LLVMIsDeclaration(val) == 0
2300 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2301 let mut imp_name = prefix.as_bytes().to_vec();
2302 imp_name.extend(name.to_bytes());
2303 let imp_name = CString::new(imp_name).unwrap();
2306 .collect::<Vec<_>>();
2307 for (imp_name, val) in globals {
2308 let imp = llvm::LLVMAddGlobal(llmod,
2310 imp_name.as_ptr() as *const _);
2311 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
2312 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);