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 llvm_err(sess.diagnostic(), err).raise()
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| e.raise());
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);
828 options.stack(1024 * 1024);
829 options.import_memory(cgcx.wasm_import_memory);
830 let assembled = input.and_then(|input| {
831 Module::new(&input, &options)
832 .map_err(|e| io::Error::new(io::ErrorKind::Other, e))
834 let err = assembled.and_then(|binary| {
835 fs::write(&object, binary.data())
837 if let Err(e) = err {
838 handler.err(&format!("failed to run binaryen assembler: {}", e));
842 pub(crate) struct CompiledModules {
843 pub modules: Vec<CompiledModule>,
844 pub metadata_module: CompiledModule,
845 pub allocator_module: Option<CompiledModule>,
848 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
849 sess.crate_types.borrow().contains(&config::CrateTypeRlib) &&
850 sess.opts.output_types.contains_key(&OutputType::Exe)
853 pub fn start_async_translation(tcx: TyCtxt,
854 time_graph: Option<TimeGraph>,
856 metadata: EncodedMetadata,
857 coordinator_receive: Receiver<Box<Any + Send>>,
859 -> OngoingCrateTranslation {
861 let crate_name = tcx.crate_name(LOCAL_CRATE);
862 let no_builtins = attr::contains_name(&tcx.hir.krate().attrs, "no_builtins");
863 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir.krate().attrs,
864 "windows_subsystem");
865 let windows_subsystem = subsystem.map(|subsystem| {
866 if subsystem != "windows" && subsystem != "console" {
867 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
868 `windows` and `console` are allowed",
871 subsystem.to_string()
874 let linker_info = LinkerInfo::new(tcx);
875 let crate_info = CrateInfo::new(tcx);
877 // Figure out what we actually need to build.
878 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
879 let mut metadata_config = ModuleConfig::new(vec![]);
880 let mut allocator_config = ModuleConfig::new(vec![]);
882 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
884 Sanitizer::Address => {
885 modules_config.passes.push("asan".to_owned());
886 modules_config.passes.push("asan-module".to_owned());
888 Sanitizer::Memory => {
889 modules_config.passes.push("msan".to_owned())
891 Sanitizer::Thread => {
892 modules_config.passes.push("tsan".to_owned())
898 if sess.opts.debugging_opts.profile {
899 modules_config.passes.push("insert-gcov-profiling".to_owned())
902 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
903 modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
905 // Save all versions of the bytecode if we're saving our temporaries.
906 if sess.opts.cg.save_temps {
907 modules_config.emit_no_opt_bc = true;
908 modules_config.emit_bc = true;
909 modules_config.emit_lto_bc = true;
910 metadata_config.emit_bc = true;
911 allocator_config.emit_bc = true;
914 // Emit compressed bitcode files for the crate if we're emitting an rlib.
915 // Whenever an rlib is created, the bitcode is inserted into the archive in
916 // order to allow LTO against it.
917 if need_crate_bitcode_for_rlib(sess) {
918 modules_config.emit_bc_compressed = true;
919 allocator_config.emit_bc_compressed = true;
922 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
923 tcx.sess.target.target.options.no_integrated_as;
925 for output_type in sess.opts.output_types.keys() {
927 OutputType::Bitcode => { modules_config.emit_bc = true; }
928 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
929 OutputType::Assembly => {
930 modules_config.emit_asm = true;
931 // If we're not using the LLVM assembler, this function
932 // could be invoked specially with output_type_assembly, so
933 // in this case we still want the metadata object file.
934 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
935 metadata_config.emit_obj = true;
936 allocator_config.emit_obj = true;
939 OutputType::Object => { modules_config.emit_obj = true; }
940 OutputType::Metadata => { metadata_config.emit_obj = true; }
942 modules_config.emit_obj = true;
943 metadata_config.emit_obj = true;
944 allocator_config.emit_obj = true;
946 OutputType::Mir => {}
947 OutputType::DepInfo => {}
951 modules_config.set_flags(sess, no_builtins);
952 metadata_config.set_flags(sess, no_builtins);
953 allocator_config.set_flags(sess, no_builtins);
955 // Exclude metadata and allocator modules from time_passes output, since
956 // they throw off the "LLVM passes" measurement.
957 metadata_config.time_passes = false;
958 allocator_config.time_passes = false;
960 let client = sess.jobserver_from_env.clone().unwrap_or_else(|| {
961 // Pick a "reasonable maximum" if we don't otherwise have a jobserver in
962 // our environment, capping out at 32 so we don't take everything down
963 // by hogging the process run queue.
964 Client::new(32).expect("failed to create jobserver")
967 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
968 let (trans_worker_send, trans_worker_receive) = channel();
970 let coordinator_thread = start_executing_work(tcx,
978 Arc::new(modules_config),
979 Arc::new(metadata_config),
980 Arc::new(allocator_config));
982 OngoingCrateTranslation {
991 coordinator_send: tcx.tx_to_llvm_workers.clone(),
992 trans_worker_receive,
994 future: coordinator_thread,
995 output_filenames: tcx.output_filenames(LOCAL_CRATE),
999 fn copy_module_artifacts_into_incr_comp_cache(sess: &Session,
1000 dep_graph: &DepGraph,
1001 compiled_modules: &CompiledModules) {
1002 if sess.opts.incremental.is_none() {
1006 for module in compiled_modules.modules.iter() {
1007 let mut files = vec![];
1009 if let Some(ref path) = module.object {
1010 files.push((WorkProductFileKind::Object, path.clone()));
1012 if let Some(ref path) = module.bytecode {
1013 files.push((WorkProductFileKind::Bytecode, path.clone()));
1015 if let Some(ref path) = module.bytecode_compressed {
1016 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
1019 save_trans_partition(sess, dep_graph, &module.name, &files);
1023 fn produce_final_output_artifacts(sess: &Session,
1024 compiled_modules: &CompiledModules,
1025 crate_output: &OutputFilenames) {
1026 let mut user_wants_bitcode = false;
1027 let mut user_wants_objects = false;
1029 // Produce final compile outputs.
1030 let copy_gracefully = |from: &Path, to: &Path| {
1031 if let Err(e) = fs::copy(from, to) {
1032 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
1036 let copy_if_one_unit = |output_type: OutputType,
1037 keep_numbered: bool| {
1038 if compiled_modules.modules.len() == 1 {
1039 // 1) Only one codegen unit. In this case it's no difficulty
1040 // to copy `foo.0.x` to `foo.x`.
1041 let module_name = Some(&compiled_modules.modules[0].name[..]);
1042 let path = crate_output.temp_path(output_type, module_name);
1043 copy_gracefully(&path,
1044 &crate_output.path(output_type));
1045 if !sess.opts.cg.save_temps && !keep_numbered {
1046 // The user just wants `foo.x`, not `foo.#module-name#.x`.
1047 remove(sess, &path);
1050 let ext = crate_output.temp_path(output_type, None)
1057 if crate_output.outputs.contains_key(&output_type) {
1058 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
1059 // no good solution for this case, so warn the user.
1060 sess.warn(&format!("ignoring emit path because multiple .{} files \
1061 were produced", ext));
1062 } else if crate_output.single_output_file.is_some() {
1063 // 3) Multiple codegen units, with `-o some_name`. We have
1064 // no good solution for this case, so warn the user.
1065 sess.warn(&format!("ignoring -o because multiple .{} files \
1066 were produced", ext));
1068 // 4) Multiple codegen units, but no explicit name. We
1069 // just leave the `foo.0.x` files in place.
1070 // (We don't have to do any work in this case.)
1075 // Flag to indicate whether the user explicitly requested bitcode.
1076 // Otherwise, we produced it only as a temporary output, and will need
1077 // to get rid of it.
1078 for output_type in crate_output.outputs.keys() {
1079 match *output_type {
1080 OutputType::Bitcode => {
1081 user_wants_bitcode = true;
1082 // Copy to .bc, but always keep the .0.bc. There is a later
1083 // check to figure out if we should delete .0.bc files, or keep
1084 // them for making an rlib.
1085 copy_if_one_unit(OutputType::Bitcode, true);
1087 OutputType::LlvmAssembly => {
1088 copy_if_one_unit(OutputType::LlvmAssembly, false);
1090 OutputType::Assembly => {
1091 copy_if_one_unit(OutputType::Assembly, false);
1093 OutputType::Object => {
1094 user_wants_objects = true;
1095 copy_if_one_unit(OutputType::Object, true);
1098 OutputType::Metadata |
1100 OutputType::DepInfo => {}
1104 // Clean up unwanted temporary files.
1106 // We create the following files by default:
1107 // - #crate#.#module-name#.bc
1108 // - #crate#.#module-name#.o
1109 // - #crate#.crate.metadata.bc
1110 // - #crate#.crate.metadata.o
1111 // - #crate#.o (linked from crate.##.o)
1112 // - #crate#.bc (copied from crate.##.bc)
1113 // We may create additional files if requested by the user (through
1114 // `-C save-temps` or `--emit=` flags).
1116 if !sess.opts.cg.save_temps {
1117 // Remove the temporary .#module-name#.o objects. If the user didn't
1118 // explicitly request bitcode (with --emit=bc), and the bitcode is not
1119 // needed for building an rlib, then we must remove .#module-name#.bc as
1122 // Specific rules for keeping .#module-name#.bc:
1123 // - If the user requested bitcode (`user_wants_bitcode`), and
1124 // codegen_units > 1, then keep it.
1125 // - If the user requested bitcode but codegen_units == 1, then we
1126 // can toss .#module-name#.bc because we copied it to .bc earlier.
1127 // - If we're not building an rlib and the user didn't request
1128 // bitcode, then delete .#module-name#.bc.
1129 // If you change how this works, also update back::link::link_rlib,
1130 // where .#module-name#.bc files are (maybe) deleted after making an
1132 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
1134 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
1136 let keep_numbered_objects = needs_crate_object ||
1137 (user_wants_objects && sess.codegen_units() > 1);
1139 for module in compiled_modules.modules.iter() {
1140 if let Some(ref path) = module.object {
1141 if !keep_numbered_objects {
1146 if let Some(ref path) = module.bytecode {
1147 if !keep_numbered_bitcode {
1153 if !user_wants_bitcode {
1154 if let Some(ref path) = compiled_modules.metadata_module.bytecode {
1155 remove(sess, &path);
1158 if let Some(ref allocator_module) = compiled_modules.allocator_module {
1159 if let Some(ref path) = allocator_module.bytecode {
1166 // We leave the following files around by default:
1168 // - #crate#.crate.metadata.o
1170 // These are used in linking steps and will be cleaned up afterward.
1173 pub(crate) fn dump_incremental_data(trans: &CrateTranslation) {
1174 println!("[incremental] Re-using {} out of {} modules",
1175 trans.modules.iter().filter(|m| m.pre_existing).count(),
1176 trans.modules.len());
1180 Optimize(ModuleTranslation),
1181 LTO(lto::LtoModuleTranslation),
1185 fn kind(&self) -> ModuleKind {
1187 WorkItem::Optimize(ref m) => m.kind,
1188 WorkItem::LTO(_) => ModuleKind::Regular,
1192 fn name(&self) -> String {
1194 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
1195 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
1200 enum WorkItemResult {
1201 Compiled(CompiledModule),
1202 NeedsLTO(ModuleTranslation),
1205 fn execute_work_item(cgcx: &CodegenContext,
1206 work_item: WorkItem,
1207 timeline: &mut Timeline)
1208 -> Result<WorkItemResult, FatalError>
1210 let diag_handler = cgcx.create_diag_handler();
1211 let config = cgcx.config(work_item.kind());
1212 let mtrans = match work_item {
1213 WorkItem::Optimize(mtrans) => mtrans,
1214 WorkItem::LTO(mut lto) => {
1216 let module = lto.optimize(cgcx, timeline)?;
1217 let module = codegen(cgcx, &diag_handler, module, config, timeline)?;
1218 return Ok(WorkItemResult::Compiled(module))
1222 let module_name = mtrans.name.clone();
1224 let pre_existing = match mtrans.source {
1225 ModuleSource::Translated(_) => None,
1226 ModuleSource::Preexisting(ref wp) => Some(wp.clone()),
1229 if let Some(wp) = pre_existing {
1230 let incr_comp_session_dir = cgcx.incr_comp_session_dir
1233 let name = &mtrans.name;
1234 let mut object = None;
1235 let mut bytecode = None;
1236 let mut bytecode_compressed = None;
1237 for (kind, saved_file) in wp.saved_files {
1238 let obj_out = match kind {
1239 WorkProductFileKind::Object => {
1240 let path = cgcx.output_filenames.temp_path(OutputType::Object, Some(name));
1241 object = Some(path.clone());
1244 WorkProductFileKind::Bytecode => {
1245 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(name));
1246 bytecode = Some(path.clone());
1249 WorkProductFileKind::BytecodeCompressed => {
1250 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(name))
1251 .with_extension(RLIB_BYTECODE_EXTENSION);
1252 bytecode_compressed = Some(path.clone());
1256 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
1258 debug!("copying pre-existing module `{}` from {:?} to {}",
1262 match link_or_copy(&source_file, &obj_out) {
1265 diag_handler.err(&format!("unable to copy {} to {}: {}",
1266 source_file.display(),
1272 assert_eq!(object.is_some(), config.emit_obj);
1273 assert_eq!(bytecode.is_some(), config.emit_bc);
1274 assert_eq!(bytecode_compressed.is_some(), config.emit_bc_compressed);
1276 Ok(WorkItemResult::Compiled(CompiledModule {
1277 llmod_id: mtrans.llmod_id.clone(),
1279 kind: ModuleKind::Regular,
1283 bytecode_compressed,
1286 debug!("llvm-optimizing {:?}", module_name);
1289 optimize(cgcx, &diag_handler, &mtrans, config, timeline)?;
1291 // After we've done the initial round of optimizations we need to
1292 // decide whether to synchronously codegen this module or ship it
1293 // back to the coordinator thread for further LTO processing (which
1294 // has to wait for all the initial modules to be optimized).
1296 // Here we dispatch based on the `cgcx.lto` and kind of module we're
1298 let needs_lto = match cgcx.lto {
1301 // Here we've got a full crate graph LTO requested. We ignore
1302 // this, however, if the crate type is only an rlib as there's
1303 // no full crate graph to process, that'll happen later.
1305 // This use case currently comes up primarily for targets that
1306 // require LTO so the request for LTO is always unconditionally
1307 // passed down to the backend, but we don't actually want to do
1308 // anything about it yet until we've got a final product.
1309 Lto::Yes | Lto::Fat | Lto::Thin => {
1310 cgcx.crate_types.len() != 1 ||
1311 cgcx.crate_types[0] != config::CrateTypeRlib
1314 // When we're automatically doing ThinLTO for multi-codegen-unit
1315 // builds we don't actually want to LTO the allocator modules if
1316 // it shows up. This is due to various linker shenanigans that
1317 // we'll encounter later.
1319 // Additionally here's where we also factor in the current LLVM
1320 // version. If it doesn't support ThinLTO we skip this.
1322 mtrans.kind != ModuleKind::Allocator &&
1323 llvm::LLVMRustThinLTOAvailable()
1327 // Metadata modules never participate in LTO regardless of the lto
1329 let needs_lto = needs_lto && mtrans.kind != ModuleKind::Metadata;
1332 Ok(WorkItemResult::NeedsLTO(mtrans))
1334 let module = codegen(cgcx, &diag_handler, mtrans, config, timeline)?;
1335 Ok(WorkItemResult::Compiled(module))
1342 Token(io::Result<Acquired>),
1344 result: ModuleTranslation,
1348 result: Result<CompiledModule, ()>,
1352 llvm_work_item: WorkItem,
1355 TranslationComplete,
1361 code: Option<DiagnosticId>,
1365 #[derive(PartialEq, Clone, Copy, Debug)]
1366 enum MainThreadWorkerState {
1372 fn start_executing_work(tcx: TyCtxt,
1373 crate_info: &CrateInfo,
1374 shared_emitter: SharedEmitter,
1375 trans_worker_send: Sender<Message>,
1376 coordinator_receive: Receiver<Box<Any + Send>>,
1379 time_graph: Option<TimeGraph>,
1380 modules_config: Arc<ModuleConfig>,
1381 metadata_config: Arc<ModuleConfig>,
1382 allocator_config: Arc<ModuleConfig>)
1383 -> thread::JoinHandle<Result<CompiledModules, ()>> {
1384 let coordinator_send = tcx.tx_to_llvm_workers.clone();
1385 let mut exported_symbols = FxHashMap();
1386 exported_symbols.insert(LOCAL_CRATE, tcx.exported_symbols(LOCAL_CRATE));
1387 for &cnum in tcx.crates().iter() {
1388 exported_symbols.insert(cnum, tcx.exported_symbols(cnum));
1390 let exported_symbols = Arc::new(exported_symbols);
1391 let sess = tcx.sess;
1393 // First up, convert our jobserver into a helper thread so we can use normal
1394 // mpsc channels to manage our messages and such.
1395 // After we've requested tokens then we'll, when we can,
1396 // get tokens on `coordinator_receive` which will
1397 // get managed in the main loop below.
1398 let coordinator_send2 = coordinator_send.clone();
1399 let helper = jobserver.into_helper_thread(move |token| {
1400 drop(coordinator_send2.send(Box::new(Message::Token(token))));
1401 }).expect("failed to spawn helper thread");
1403 let mut each_linked_rlib_for_lto = Vec::new();
1404 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1405 if link::ignored_for_lto(sess, crate_info, cnum) {
1408 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1411 let wasm_import_memory =
1412 attr::contains_name(&tcx.hir.krate().attrs, "wasm_import_memory");
1414 let assembler_cmd = if modules_config.no_integrated_as {
1415 // HACK: currently we use linker (gcc) as our assembler
1416 let (name, mut cmd, _) = get_linker(sess);
1417 cmd.args(&sess.target.target.options.asm_args);
1418 Some(Arc::new(AssemblerCommand {
1426 let cgcx = CodegenContext {
1427 crate_types: sess.crate_types.borrow().clone(),
1428 each_linked_rlib_for_lto,
1430 no_landing_pads: sess.no_landing_pads(),
1431 fewer_names: sess.fewer_names(),
1432 save_temps: sess.opts.cg.save_temps,
1433 opts: Arc::new(sess.opts.clone()),
1434 time_passes: sess.time_passes(),
1436 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1437 remark: sess.opts.cg.remark.clone(),
1439 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1441 diag_emitter: shared_emitter.clone(),
1443 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1444 regular_module_config: modules_config,
1445 metadata_module_config: metadata_config,
1446 allocator_module_config: allocator_config,
1447 tm_factory: target_machine_factory(tcx.sess),
1449 msvc_imps_needed: msvc_imps_needed(tcx),
1450 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1451 binaryen_linker: tcx.sess.linker_flavor() == LinkerFlavor::Binaryen,
1452 debuginfo: tcx.sess.opts.debuginfo,
1457 // This is the "main loop" of parallel work happening for parallel codegen.
1458 // It's here that we manage parallelism, schedule work, and work with
1459 // messages coming from clients.
1461 // There are a few environmental pre-conditions that shape how the system
1464 // - Error reporting only can happen on the main thread because that's the
1465 // only place where we have access to the compiler `Session`.
1466 // - LLVM work can be done on any thread.
1467 // - Translation can only happen on the main thread.
1468 // - Each thread doing substantial work most be in possession of a `Token`
1469 // from the `Jobserver`.
1470 // - The compiler process always holds one `Token`. Any additional `Tokens`
1471 // have to be requested from the `Jobserver`.
1475 // The error reporting restriction is handled separately from the rest: We
1476 // set up a `SharedEmitter` the holds an open channel to the main thread.
1477 // When an error occurs on any thread, the shared emitter will send the
1478 // error message to the receiver main thread (`SharedEmitterMain`). The
1479 // main thread will periodically query this error message queue and emit
1480 // any error messages it has received. It might even abort compilation if
1481 // has received a fatal error. In this case we rely on all other threads
1482 // being torn down automatically with the main thread.
1483 // Since the main thread will often be busy doing translation work, error
1484 // reporting will be somewhat delayed, since the message queue can only be
1485 // checked in between to work packages.
1487 // Work Processing Infrastructure
1488 // ==============================
1489 // The work processing infrastructure knows three major actors:
1491 // - the coordinator thread,
1492 // - the main thread, and
1493 // - LLVM worker threads
1495 // The coordinator thread is running a message loop. It instructs the main
1496 // thread about what work to do when, and it will spawn off LLVM worker
1497 // threads as open LLVM WorkItems become available.
1499 // The job of the main thread is to translate CGUs into LLVM work package
1500 // (since the main thread is the only thread that can do this). The main
1501 // thread will block until it receives a message from the coordinator, upon
1502 // which it will translate one CGU, send it to the coordinator and block
1503 // again. This way the coordinator can control what the main thread is
1506 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1507 // available, it will spawn off a new LLVM worker thread and let it process
1508 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1509 // it will just shut down, which also frees all resources associated with
1510 // the given LLVM module, and sends a message to the coordinator that the
1511 // has been completed.
1515 // The scheduler's goal is to minimize the time it takes to complete all
1516 // work there is, however, we also want to keep memory consumption low
1517 // if possible. These two goals are at odds with each other: If memory
1518 // consumption were not an issue, we could just let the main thread produce
1519 // LLVM WorkItems at full speed, assuring maximal utilization of
1520 // Tokens/LLVM worker threads. However, since translation usual is faster
1521 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1522 // WorkItem potentially holds on to a substantial amount of memory.
1524 // So the actual goal is to always produce just enough LLVM WorkItems as
1525 // not to starve our LLVM worker threads. That means, once we have enough
1526 // WorkItems in our queue, we can block the main thread, so it does not
1527 // produce more until we need them.
1529 // Doing LLVM Work on the Main Thread
1530 // ----------------------------------
1531 // Since the main thread owns the compiler processes implicit `Token`, it is
1532 // wasteful to keep it blocked without doing any work. Therefore, what we do
1533 // in this case is: We spawn off an additional LLVM worker thread that helps
1534 // reduce the queue. The work it is doing corresponds to the implicit
1535 // `Token`. The coordinator will mark the main thread as being busy with
1536 // LLVM work. (The actual work happens on another OS thread but we just care
1537 // about `Tokens`, not actual threads).
1539 // When any LLVM worker thread finishes while the main thread is marked as
1540 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1541 // of the just finished thread to the LLVM worker thread that is working on
1542 // behalf of the main thread's implicit Token, thus freeing up the main
1543 // thread again. The coordinator can then again decide what the main thread
1544 // should do. This allows the coordinator to make decisions at more points
1547 // Striking a Balance between Throughput and Memory Consumption
1548 // ------------------------------------------------------------
1549 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1550 // memory consumption as low as possible, are in conflict with each other,
1551 // we have to find a trade off between them. Right now, the goal is to keep
1552 // all workers busy, which means that no worker should find the queue empty
1553 // when it is ready to start.
1554 // How do we do achieve this? Good question :) We actually never know how
1555 // many `Tokens` are potentially available so it's hard to say how much to
1556 // fill up the queue before switching the main thread to LLVM work. Also we
1557 // currently don't have a means to estimate how long a running LLVM worker
1558 // will still be busy with it's current WorkItem. However, we know the
1559 // maximal count of available Tokens that makes sense (=the number of CPU
1560 // cores), so we can take a conservative guess. The heuristic we use here
1561 // is implemented in the `queue_full_enough()` function.
1563 // Some Background on Jobservers
1564 // -----------------------------
1565 // It's worth also touching on the management of parallelism here. We don't
1566 // want to just spawn a thread per work item because while that's optimal
1567 // parallelism it may overload a system with too many threads or violate our
1568 // configuration for the maximum amount of cpu to use for this process. To
1569 // manage this we use the `jobserver` crate.
1571 // Job servers are an artifact of GNU make and are used to manage
1572 // parallelism between processes. A jobserver is a glorified IPC semaphore
1573 // basically. Whenever we want to run some work we acquire the semaphore,
1574 // and whenever we're done with that work we release the semaphore. In this
1575 // manner we can ensure that the maximum number of parallel workers is
1576 // capped at any one point in time.
1578 // LTO and the coordinator thread
1579 // ------------------------------
1581 // The final job the coordinator thread is responsible for is managing LTO
1582 // and how that works. When LTO is requested what we'll to is collect all
1583 // optimized LLVM modules into a local vector on the coordinator. Once all
1584 // modules have been translated and optimized we hand this to the `lto`
1585 // module for further optimization. The `lto` module will return back a list
1586 // of more modules to work on, which the coordinator will continue to spawn
1589 // Each LLVM module is automatically sent back to the coordinator for LTO if
1590 // necessary. There's already optimizations in place to avoid sending work
1591 // back to the coordinator if LTO isn't requested.
1592 return thread::spawn(move || {
1593 // We pretend to be within the top-level LLVM time-passes task here:
1596 let max_workers = ::num_cpus::get();
1597 let mut worker_id_counter = 0;
1598 let mut free_worker_ids = Vec::new();
1599 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1600 if let Some(id) = free_worker_ids.pop() {
1603 let id = worker_id_counter;
1604 worker_id_counter += 1;
1609 // This is where we collect codegen units that have gone all the way
1610 // through translation and LLVM.
1611 let mut compiled_modules = vec![];
1612 let mut compiled_metadata_module = None;
1613 let mut compiled_allocator_module = None;
1614 let mut needs_lto = Vec::new();
1615 let mut started_lto = false;
1617 // This flag tracks whether all items have gone through translations
1618 let mut translation_done = false;
1620 // This is the queue of LLVM work items that still need processing.
1621 let mut work_items = Vec::<(WorkItem, u64)>::new();
1623 // This are the Jobserver Tokens we currently hold. Does not include
1624 // the implicit Token the compiler process owns no matter what.
1625 let mut tokens = Vec::new();
1627 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1628 let mut running = 0;
1630 let mut llvm_start_time = None;
1632 // Run the message loop while there's still anything that needs message
1634 while !translation_done ||
1635 work_items.len() > 0 ||
1637 needs_lto.len() > 0 ||
1638 main_thread_worker_state != MainThreadWorkerState::Idle {
1640 // While there are still CGUs to be translated, the coordinator has
1641 // to decide how to utilize the compiler processes implicit Token:
1642 // For translating more CGU or for running them through LLVM.
1643 if !translation_done {
1644 if main_thread_worker_state == MainThreadWorkerState::Idle {
1645 if !queue_full_enough(work_items.len(), running, max_workers) {
1646 // The queue is not full enough, translate more items:
1647 if let Err(_) = trans_worker_send.send(Message::TranslateItem) {
1648 panic!("Could not send Message::TranslateItem to main thread")
1650 main_thread_worker_state = MainThreadWorkerState::Translating;
1652 // The queue is full enough to not let the worker
1653 // threads starve. Use the implicit Token to do some
1655 let (item, _) = work_items.pop()
1656 .expect("queue empty - queue_full_enough() broken?");
1657 let cgcx = CodegenContext {
1658 worker: get_worker_id(&mut free_worker_ids),
1661 maybe_start_llvm_timer(cgcx.config(item.kind()),
1662 &mut llvm_start_time);
1663 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1664 spawn_work(cgcx, item);
1668 // If we've finished everything related to normal translation
1669 // then it must be the case that we've got some LTO work to do.
1670 // Perform the serial work here of figuring out what we're
1671 // going to LTO and then push a bunch of work items onto our
1673 if work_items.len() == 0 &&
1675 main_thread_worker_state == MainThreadWorkerState::Idle {
1676 assert!(!started_lto);
1677 assert!(needs_lto.len() > 0);
1679 let modules = mem::replace(&mut needs_lto, Vec::new());
1680 for (work, cost) in generate_lto_work(&cgcx, modules) {
1681 let insertion_index = work_items
1682 .binary_search_by_key(&cost, |&(_, cost)| cost)
1683 .unwrap_or_else(|e| e);
1684 work_items.insert(insertion_index, (work, cost));
1685 helper.request_token();
1689 // In this branch, we know that everything has been translated,
1690 // so it's just a matter of determining whether the implicit
1691 // Token is free to use for LLVM work.
1692 match main_thread_worker_state {
1693 MainThreadWorkerState::Idle => {
1694 if let Some((item, _)) = work_items.pop() {
1695 let cgcx = CodegenContext {
1696 worker: get_worker_id(&mut free_worker_ids),
1699 maybe_start_llvm_timer(cgcx.config(item.kind()),
1700 &mut llvm_start_time);
1701 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1702 spawn_work(cgcx, item);
1704 // There is no unstarted work, so let the main thread
1705 // take over for a running worker. Otherwise the
1706 // implicit token would just go to waste.
1707 // We reduce the `running` counter by one. The
1708 // `tokens.truncate()` below will take care of
1709 // giving the Token back.
1710 debug_assert!(running > 0);
1712 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1715 MainThreadWorkerState::Translating => {
1716 bug!("trans worker should not be translating after \
1717 translation was already completed")
1719 MainThreadWorkerState::LLVMing => {
1720 // Already making good use of that token
1725 // Spin up what work we can, only doing this while we've got available
1726 // parallelism slots and work left to spawn.
1727 while work_items.len() > 0 && running < tokens.len() {
1728 let (item, _) = work_items.pop().unwrap();
1730 maybe_start_llvm_timer(cgcx.config(item.kind()),
1731 &mut llvm_start_time);
1733 let cgcx = CodegenContext {
1734 worker: get_worker_id(&mut free_worker_ids),
1738 spawn_work(cgcx, item);
1742 // Relinquish accidentally acquired extra tokens
1743 tokens.truncate(running);
1745 let msg = coordinator_receive.recv().unwrap();
1746 match *msg.downcast::<Message>().ok().unwrap() {
1747 // Save the token locally and the next turn of the loop will use
1748 // this to spawn a new unit of work, or it may get dropped
1749 // immediately if we have no more work to spawn.
1750 Message::Token(token) => {
1755 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1756 // If the main thread token is used for LLVM work
1757 // at the moment, we turn that thread into a regular
1758 // LLVM worker thread, so the main thread is free
1759 // to react to translation demand.
1760 main_thread_worker_state = MainThreadWorkerState::Idle;
1765 let msg = &format!("failed to acquire jobserver token: {}", e);
1766 shared_emitter.fatal(msg);
1767 // Exit the coordinator thread
1773 Message::TranslationDone { llvm_work_item, cost } => {
1774 // We keep the queue sorted by estimated processing cost,
1775 // so that more expensive items are processed earlier. This
1776 // is good for throughput as it gives the main thread more
1777 // time to fill up the queue and it avoids scheduling
1778 // expensive items to the end.
1779 // Note, however, that this is not ideal for memory
1780 // consumption, as LLVM module sizes are not evenly
1782 let insertion_index =
1783 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1784 let insertion_index = match insertion_index {
1785 Ok(idx) | Err(idx) => idx
1787 work_items.insert(insertion_index, (llvm_work_item, cost));
1789 helper.request_token();
1790 assert_eq!(main_thread_worker_state,
1791 MainThreadWorkerState::Translating);
1792 main_thread_worker_state = MainThreadWorkerState::Idle;
1795 Message::TranslationComplete => {
1796 translation_done = true;
1797 assert_eq!(main_thread_worker_state,
1798 MainThreadWorkerState::Translating);
1799 main_thread_worker_state = MainThreadWorkerState::Idle;
1802 // If a thread exits successfully then we drop a token associated
1803 // with that worker and update our `running` count. We may later
1804 // re-acquire a token to continue running more work. We may also not
1805 // actually drop a token here if the worker was running with an
1806 // "ephemeral token"
1808 // Note that if the thread failed that means it panicked, so we
1809 // abort immediately.
1810 Message::Done { result: Ok(compiled_module), worker_id } => {
1811 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1812 main_thread_worker_state = MainThreadWorkerState::Idle;
1817 free_worker_ids.push(worker_id);
1819 match compiled_module.kind {
1820 ModuleKind::Regular => {
1821 compiled_modules.push(compiled_module);
1823 ModuleKind::Metadata => {
1824 assert!(compiled_metadata_module.is_none());
1825 compiled_metadata_module = Some(compiled_module);
1827 ModuleKind::Allocator => {
1828 assert!(compiled_allocator_module.is_none());
1829 compiled_allocator_module = Some(compiled_module);
1833 Message::NeedsLTO { result, worker_id } => {
1834 assert!(!started_lto);
1835 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1836 main_thread_worker_state = MainThreadWorkerState::Idle;
1841 free_worker_ids.push(worker_id);
1842 needs_lto.push(result);
1844 Message::Done { result: Err(()), worker_id: _ } => {
1845 shared_emitter.fatal("aborting due to worker thread failure");
1846 // Exit the coordinator thread
1849 Message::TranslateItem => {
1850 bug!("the coordinator should not receive translation requests")
1855 if let Some(llvm_start_time) = llvm_start_time {
1856 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
1857 // This is the top-level timing for all of LLVM, set the time-depth
1860 print_time_passes_entry(cgcx.time_passes,
1865 // Regardless of what order these modules completed in, report them to
1866 // the backend in the same order every time to ensure that we're handing
1867 // out deterministic results.
1868 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1870 let compiled_metadata_module = compiled_metadata_module
1871 .expect("Metadata module not compiled?");
1873 Ok(CompiledModules {
1874 modules: compiled_modules,
1875 metadata_module: compiled_metadata_module,
1876 allocator_module: compiled_allocator_module,
1880 // A heuristic that determines if we have enough LLVM WorkItems in the
1881 // queue so that the main thread can do LLVM work instead of translation
1882 fn queue_full_enough(items_in_queue: usize,
1883 workers_running: usize,
1884 max_workers: usize) -> bool {
1886 items_in_queue > 0 &&
1887 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1890 fn maybe_start_llvm_timer(config: &ModuleConfig,
1891 llvm_start_time: &mut Option<Instant>) {
1892 // We keep track of the -Ztime-passes output manually,
1893 // since the closure-based interface does not fit well here.
1894 if config.time_passes {
1895 if llvm_start_time.is_none() {
1896 *llvm_start_time = Some(Instant::now());
1902 pub const TRANS_WORKER_ID: usize = ::std::usize::MAX;
1903 pub const TRANS_WORKER_TIMELINE: time_graph::TimelineId =
1904 time_graph::TimelineId(TRANS_WORKER_ID);
1905 pub const TRANS_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1906 time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
1907 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1908 time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
1910 fn spawn_work(cgcx: CodegenContext, work: WorkItem) {
1911 let depth = time_depth();
1913 thread::spawn(move || {
1914 set_time_depth(depth);
1916 // Set up a destructor which will fire off a message that we're done as
1919 coordinator_send: Sender<Box<Any + Send>>,
1920 result: Option<WorkItemResult>,
1923 impl Drop for Bomb {
1924 fn drop(&mut self) {
1925 let worker_id = self.worker_id;
1926 let msg = match self.result.take() {
1927 Some(WorkItemResult::Compiled(m)) => {
1928 Message::Done { result: Ok(m), worker_id }
1930 Some(WorkItemResult::NeedsLTO(m)) => {
1931 Message::NeedsLTO { result: m, worker_id }
1933 None => Message::Done { result: Err(()), worker_id }
1935 drop(self.coordinator_send.send(Box::new(msg)));
1939 let mut bomb = Bomb {
1940 coordinator_send: cgcx.coordinator_send.clone(),
1942 worker_id: cgcx.worker,
1945 // Execute the work itself, and if it finishes successfully then flag
1946 // ourselves as a success as well.
1948 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1949 // as a diagnostic was already sent off to the main thread - just
1950 // surface that there was an error in this worker.
1952 let timeline = cgcx.time_graph.as_ref().map(|tg| {
1953 tg.start(time_graph::TimelineId(cgcx.worker),
1954 LLVM_WORK_PACKAGE_KIND,
1957 let mut timeline = timeline.unwrap_or(Timeline::noop());
1958 execute_work_item(&cgcx, work, &mut timeline).ok()
1963 pub fn run_assembler(cgcx: &CodegenContext, handler: &Handler, assembly: &Path, object: &Path) {
1964 let assembler = cgcx.assembler_cmd
1966 .expect("cgcx.assembler_cmd is missing?");
1968 let pname = &assembler.name;
1969 let mut cmd = assembler.cmd.clone();
1970 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
1971 debug!("{:?}", cmd);
1973 match cmd.output() {
1975 if !prog.status.success() {
1976 let mut note = prog.stderr.clone();
1977 note.extend_from_slice(&prog.stdout);
1979 handler.struct_err(&format!("linking with `{}` failed: {}",
1982 .note(&format!("{:?}", &cmd))
1983 .note(str::from_utf8(¬e[..]).unwrap())
1985 handler.abort_if_errors();
1989 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
1990 handler.abort_if_errors();
1995 pub unsafe fn with_llvm_pmb(llmod: ModuleRef,
1996 config: &ModuleConfig,
1997 opt_level: llvm::CodeGenOptLevel,
1998 f: &mut FnMut(llvm::PassManagerBuilderRef)) {
1999 // Create the PassManagerBuilder for LLVM. We configure it with
2000 // reasonable defaults and prepare it to actually populate the pass
2002 let builder = llvm::LLVMPassManagerBuilderCreate();
2003 let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
2004 let inline_threshold = config.inline_threshold;
2006 llvm::LLVMRustConfigurePassManagerBuilder(builder,
2008 config.merge_functions,
2009 config.vectorize_slp,
2010 config.vectorize_loop);
2011 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
2013 if opt_size != llvm::CodeGenOptSizeNone {
2014 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
2017 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
2019 // Here we match what clang does (kinda). For O0 we only inline
2020 // always-inline functions (but don't add lifetime intrinsics), at O1 we
2021 // inline with lifetime intrinsics, and O2+ we add an inliner with a
2022 // thresholds copied from clang.
2023 match (opt_level, opt_size, inline_threshold) {
2025 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
2027 (llvm::CodeGenOptLevel::Aggressive, ..) => {
2028 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
2030 (_, llvm::CodeGenOptSizeDefault, _) => {
2031 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
2033 (_, llvm::CodeGenOptSizeAggressive, _) => {
2034 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
2036 (llvm::CodeGenOptLevel::None, ..) => {
2037 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
2039 (llvm::CodeGenOptLevel::Less, ..) => {
2040 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
2042 (llvm::CodeGenOptLevel::Default, ..) => {
2043 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
2045 (llvm::CodeGenOptLevel::Other, ..) => {
2046 bug!("CodeGenOptLevel::Other selected")
2051 llvm::LLVMPassManagerBuilderDispose(builder);
2055 enum SharedEmitterMessage {
2056 Diagnostic(Diagnostic),
2057 InlineAsmError(u32, String),
2063 pub struct SharedEmitter {
2064 sender: Sender<SharedEmitterMessage>,
2067 pub struct SharedEmitterMain {
2068 receiver: Receiver<SharedEmitterMessage>,
2071 impl SharedEmitter {
2072 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
2073 let (sender, receiver) = channel();
2075 (SharedEmitter { sender }, SharedEmitterMain { receiver })
2078 fn inline_asm_error(&self, cookie: u32, msg: String) {
2079 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
2082 fn fatal(&self, msg: &str) {
2083 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2087 impl Emitter for SharedEmitter {
2088 fn emit(&mut self, db: &DiagnosticBuilder) {
2089 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2091 code: db.code.clone(),
2094 for child in &db.children {
2095 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2096 msg: child.message(),
2101 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
2105 impl SharedEmitterMain {
2106 pub fn check(&self, sess: &Session, blocking: bool) {
2108 let message = if blocking {
2109 match self.receiver.recv() {
2110 Ok(message) => Ok(message),
2114 match self.receiver.try_recv() {
2115 Ok(message) => Ok(message),
2121 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2122 let handler = sess.diagnostic();
2125 handler.emit_with_code(&MultiSpan::new(),
2131 handler.emit(&MultiSpan::new(),
2137 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
2138 match Mark::from_u32(cookie).expn_info() {
2139 Some(ei) => sess.span_err(ei.call_site, &msg),
2140 None => sess.err(&msg),
2143 Ok(SharedEmitterMessage::AbortIfErrors) => {
2144 sess.abort_if_errors();
2146 Ok(SharedEmitterMessage::Fatal(msg)) => {
2158 pub struct OngoingCrateTranslation {
2161 metadata: EncodedMetadata,
2162 windows_subsystem: Option<String>,
2163 linker_info: LinkerInfo,
2164 crate_info: CrateInfo,
2165 time_graph: Option<TimeGraph>,
2166 coordinator_send: Sender<Box<Any + Send>>,
2167 trans_worker_receive: Receiver<Message>,
2168 shared_emitter_main: SharedEmitterMain,
2169 future: thread::JoinHandle<Result<CompiledModules, ()>>,
2170 output_filenames: Arc<OutputFilenames>,
2173 impl OngoingCrateTranslation {
2174 pub(crate) fn join(self, sess: &Session, dep_graph: &DepGraph) -> CrateTranslation {
2175 self.shared_emitter_main.check(sess, true);
2176 let compiled_modules = match self.future.join() {
2177 Ok(Ok(compiled_modules)) => compiled_modules,
2179 sess.abort_if_errors();
2180 panic!("expected abort due to worker thread errors")
2183 sess.fatal("Error during translation/LLVM phase.");
2187 sess.abort_if_errors();
2189 if let Some(time_graph) = self.time_graph {
2190 time_graph.dump(&format!("{}-timings", self.crate_name));
2193 copy_module_artifacts_into_incr_comp_cache(sess,
2196 produce_final_output_artifacts(sess,
2198 &self.output_filenames);
2200 // FIXME: time_llvm_passes support - does this use a global context or
2202 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
2203 unsafe { llvm::LLVMRustPrintPassTimings(); }
2206 let trans = CrateTranslation {
2207 crate_name: self.crate_name,
2209 metadata: self.metadata,
2210 windows_subsystem: self.windows_subsystem,
2211 linker_info: self.linker_info,
2212 crate_info: self.crate_info,
2214 modules: compiled_modules.modules,
2215 allocator_module: compiled_modules.allocator_module,
2216 metadata_module: compiled_modules.metadata_module,
2222 pub(crate) fn submit_pre_translated_module_to_llvm(&self,
2224 mtrans: ModuleTranslation) {
2225 self.wait_for_signal_to_translate_item();
2226 self.check_for_errors(tcx.sess);
2228 // These are generally cheap and won't through off scheduling.
2230 submit_translated_module_to_llvm(tcx, mtrans, cost);
2233 pub fn translation_finished(&self, tcx: TyCtxt) {
2234 self.wait_for_signal_to_translate_item();
2235 self.check_for_errors(tcx.sess);
2236 drop(self.coordinator_send.send(Box::new(Message::TranslationComplete)));
2239 pub fn check_for_errors(&self, sess: &Session) {
2240 self.shared_emitter_main.check(sess, false);
2243 pub fn wait_for_signal_to_translate_item(&self) {
2244 match self.trans_worker_receive.recv() {
2245 Ok(Message::TranslateItem) => {
2248 Ok(_) => panic!("unexpected message"),
2250 // One of the LLVM threads must have panicked, fall through so
2251 // error handling can be reached.
2257 pub(crate) fn submit_translated_module_to_llvm(tcx: TyCtxt,
2258 mtrans: ModuleTranslation,
2260 let llvm_work_item = WorkItem::Optimize(mtrans);
2261 drop(tcx.tx_to_llvm_workers.send(Box::new(Message::TranslationDone {
2267 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
2268 tcx.sess.target.target.options.is_like_msvc &&
2269 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib)
2272 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2273 // This is required to satisfy `dllimport` references to static data in .rlibs
2274 // when using MSVC linker. We do this only for data, as linker can fix up
2275 // code references on its own.
2276 // See #26591, #27438
2277 fn create_msvc_imps(cgcx: &CodegenContext, llcx: ContextRef, llmod: ModuleRef) {
2278 if !cgcx.msvc_imps_needed {
2281 // The x86 ABI seems to require that leading underscores are added to symbol
2282 // names, so we need an extra underscore on 32-bit. There's also a leading
2283 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2284 // underscores added in front).
2285 let prefix = if cgcx.target_pointer_width == "32" {
2291 let i8p_ty = Type::i8p_llcx(llcx);
2292 let globals = base::iter_globals(llmod)
2294 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
2295 llvm::LLVMIsDeclaration(val) == 0
2298 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2299 let mut imp_name = prefix.as_bytes().to_vec();
2300 imp_name.extend(name.to_bytes());
2301 let imp_name = CString::new(imp_name).unwrap();
2304 .collect::<Vec<_>>();
2305 for (imp_name, val) in globals {
2306 let imp = llvm::LLVMAddGlobal(llmod,
2308 imp_name.as_ptr() as *const _);
2309 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
2310 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);