1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use back::bytecode::{self, RLIB_BYTECODE_EXTENSION};
13 use back::lto::{self, ModuleBuffer, ThinBuffer};
14 use back::link::{self, get_linker, remove};
15 use back::command::Command;
16 use back::linker::LinkerInfo;
17 use back::symbol_export::ExportedSymbols;
20 use rustc_incremental::{save_trans_partition, in_incr_comp_dir};
21 use rustc::dep_graph::{DepGraph, WorkProductFileKind};
22 use rustc::middle::cstore::{LinkMeta, EncodedMetadata};
23 use rustc::session::config::{self, OutputFilenames, OutputType, Passes, SomePasses,
24 AllPasses, Sanitizer, Lto};
25 use rustc::session::Session;
26 use rustc::util::nodemap::FxHashMap;
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_ext, time_depth, set_time_depth, print_time_passes_entry};
36 use rustc::util::common::path2cstr;
37 use rustc::util::fs::{link_or_copy};
38 use errors::{self, Handler, Level, DiagnosticBuilder, FatalError, DiagnosticId};
39 use errors::emitter::{Emitter};
41 use syntax::ext::hygiene::Mark;
42 use syntax_pos::MultiSpan;
43 use syntax_pos::symbol::Symbol;
45 use context::{is_pie_binary, get_reloc_model};
46 use common::{C_bytes_in_context, val_ty};
47 use jobserver::{Client, Acquired};
51 use std::ffi::{CString, CStr};
53 use std::io::{self, Write};
55 use std::path::{Path, PathBuf};
58 use std::sync::mpsc::{channel, Sender, Receiver};
60 use std::time::Instant;
62 use libc::{c_uint, c_void, c_char, size_t};
64 pub const RELOC_MODEL_ARGS : [(&'static str, llvm::RelocMode); 7] = [
65 ("pic", llvm::RelocMode::PIC),
66 ("static", llvm::RelocMode::Static),
67 ("default", llvm::RelocMode::Default),
68 ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
69 ("ropi", llvm::RelocMode::ROPI),
70 ("rwpi", llvm::RelocMode::RWPI),
71 ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
74 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
75 ("small", llvm::CodeModel::Small),
76 ("kernel", llvm::CodeModel::Kernel),
77 ("medium", llvm::CodeModel::Medium),
78 ("large", llvm::CodeModel::Large),
81 pub const TLS_MODEL_ARGS : [(&'static str, llvm::ThreadLocalMode); 4] = [
82 ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
83 ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
84 ("initial-exec", llvm::ThreadLocalMode::InitialExec),
85 ("local-exec", llvm::ThreadLocalMode::LocalExec),
88 pub fn llvm_err(handler: &errors::Handler, msg: String) -> FatalError {
89 match llvm::last_error() {
90 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
91 None => handler.fatal(&msg),
95 pub fn write_output_file(
96 handler: &errors::Handler,
97 target: llvm::TargetMachineRef,
98 pm: llvm::PassManagerRef,
101 file_type: llvm::FileType) -> Result<(), FatalError> {
103 let output_c = path2cstr(output);
104 let result = llvm::LLVMRustWriteOutputFile(
105 target, pm, m, output_c.as_ptr(), file_type);
106 if result.into_result().is_err() {
107 let msg = format!("could not write output to {}", output.display());
108 Err(llvm_err(handler, msg))
115 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
117 config::OptLevel::No => llvm::CodeGenOptLevel::None,
118 config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
119 config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
120 config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
121 _ => llvm::CodeGenOptLevel::Default,
125 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
127 config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
128 config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
129 _ => llvm::CodeGenOptSizeNone,
133 pub fn create_target_machine(sess: &Session, find_features: bool) -> TargetMachineRef {
134 target_machine_factory(sess, find_features)().unwrap_or_else(|err| {
135 llvm_err(sess.diagnostic(), err).raise()
139 // If find_features is true this won't access `sess.crate_types` by assuming
140 // that `is_pie_binary` is false. When we discover LLVM target features
141 // `sess.crate_types` is uninitialized so we cannot access it.
142 pub fn target_machine_factory(sess: &Session, find_features: bool)
143 -> Arc<Fn() -> Result<TargetMachineRef, String> + Send + Sync>
145 let reloc_model = get_reloc_model(sess);
147 let opt_level = get_llvm_opt_level(sess.opts.optimize);
148 let use_softfp = sess.opts.cg.soft_float;
150 let ffunction_sections = sess.target.target.options.function_sections;
151 let fdata_sections = ffunction_sections;
153 let code_model_arg = sess.opts.cg.code_model.as_ref().or(
154 sess.target.target.options.code_model.as_ref(),
157 let code_model = match code_model_arg {
159 match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
162 sess.err(&format!("{:?} is not a valid code model",
164 sess.abort_if_errors();
169 None => llvm::CodeModel::None,
172 let singlethread = sess.target.target.options.singlethread;
174 let triple = &sess.target.target.llvm_target;
176 let triple = CString::new(triple.as_bytes()).unwrap();
177 let cpu = match sess.opts.cg.target_cpu {
179 None => &*sess.target.target.options.cpu
181 let cpu = CString::new(cpu.as_bytes()).unwrap();
182 let features = attributes::llvm_target_features(sess)
185 let features = CString::new(features).unwrap();
186 let is_pie_binary = !find_features && is_pie_binary(sess);
187 let trap_unreachable = sess.target.target.options.trap_unreachable;
191 llvm::LLVMRustCreateTargetMachine(
192 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
206 Err(format!("Could not create LLVM TargetMachine for triple: {}",
207 triple.to_str().unwrap()))
214 /// Module-specific configuration for `optimize_and_codegen`.
215 pub struct ModuleConfig {
216 /// Names of additional optimization passes to run.
218 /// Some(level) to optimize at a certain level, or None to run
219 /// absolutely no optimizations (used for the metadata module).
220 pub opt_level: Option<llvm::CodeGenOptLevel>,
222 /// Some(level) to optimize binary size, or None to not affect program size.
223 opt_size: Option<llvm::CodeGenOptSize>,
225 pgo_gen: Option<String>,
228 // Flags indicating which outputs to produce.
229 emit_no_opt_bc: bool,
231 emit_bc_compressed: bool,
236 // Miscellaneous flags. These are mostly copied from command-line
239 no_prepopulate_passes: bool,
242 vectorize_loop: bool,
244 merge_functions: bool,
245 inline_threshold: Option<usize>,
246 // Instead of creating an object file by doing LLVM codegen, just
247 // make the object file bitcode. Provides easy compatibility with
248 // emscripten's ecc compiler, when used as the linker.
249 obj_is_bitcode: bool,
250 no_integrated_as: bool,
252 embed_bitcode_marker: bool,
256 fn new(passes: Vec<String>) -> ModuleConfig {
263 pgo_use: String::new(),
265 emit_no_opt_bc: false,
267 emit_bc_compressed: false,
272 obj_is_bitcode: false,
273 embed_bitcode: false,
274 embed_bitcode_marker: false,
275 no_integrated_as: false,
278 no_prepopulate_passes: false,
281 vectorize_loop: false,
282 vectorize_slp: false,
283 merge_functions: false,
284 inline_threshold: None
288 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
289 self.no_verify = sess.no_verify();
290 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
291 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
292 self.time_passes = sess.time_passes();
293 self.inline_threshold = sess.opts.cg.inline_threshold;
294 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode;
295 let embed_bitcode = sess.target.target.options.embed_bitcode ||
296 sess.opts.debugging_opts.embed_bitcode;
298 match sess.opts.optimize {
299 config::OptLevel::No |
300 config::OptLevel::Less => {
301 self.embed_bitcode_marker = embed_bitcode;
303 _ => self.embed_bitcode = embed_bitcode,
307 // Copy what clang does by turning on loop vectorization at O2 and
308 // slp vectorization at O3. Otherwise configure other optimization aspects
309 // of this pass manager builder.
310 // Turn off vectorization for emscripten, as it's not very well supported.
311 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
312 (sess.opts.optimize == config::OptLevel::Default ||
313 sess.opts.optimize == config::OptLevel::Aggressive) &&
314 !sess.target.target.options.is_like_emscripten;
316 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
317 sess.opts.optimize == config::OptLevel::Aggressive &&
318 !sess.target.target.options.is_like_emscripten;
320 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
321 sess.opts.optimize == config::OptLevel::Aggressive;
325 /// Assembler name and command used by codegen when no_integrated_as is enabled
326 struct AssemblerCommand {
331 /// Additional resources used by optimize_and_codegen (not module specific)
333 pub struct CodegenContext {
334 // Resouces needed when running LTO
335 pub time_passes: bool,
337 pub no_landing_pads: bool,
338 pub save_temps: bool,
339 pub fewer_names: bool,
340 pub exported_symbols: Option<Arc<ExportedSymbols>>,
341 pub opts: Arc<config::Options>,
342 pub crate_types: Vec<config::CrateType>,
343 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
344 output_filenames: Arc<OutputFilenames>,
345 regular_module_config: Arc<ModuleConfig>,
346 metadata_module_config: Arc<ModuleConfig>,
347 allocator_module_config: Arc<ModuleConfig>,
348 pub tm_factory: Arc<Fn() -> Result<TargetMachineRef, String> + Send + Sync>,
349 pub msvc_imps_needed: bool,
350 pub target_pointer_width: String,
351 debuginfo: config::DebugInfoLevel,
353 // Number of cgus excluding the allocator/metadata modules
354 pub total_cgus: usize,
355 // Handler to use for diagnostics produced during codegen.
356 pub diag_emitter: SharedEmitter,
357 // LLVM passes added by plugins.
358 pub plugin_passes: Vec<String>,
359 // LLVM optimizations for which we want to print remarks.
361 // Worker thread number
363 // The incremental compilation session directory, or None if we are not
364 // compiling incrementally
365 pub incr_comp_session_dir: Option<PathBuf>,
366 // Channel back to the main control thread to send messages to
367 coordinator_send: Sender<Box<Any + Send>>,
368 // A reference to the TimeGraph so we can register timings. None means that
369 // measuring is disabled.
370 time_graph: Option<TimeGraph>,
371 // The assembler command if no_integrated_as option is enabled, None otherwise
372 assembler_cmd: Option<Arc<AssemblerCommand>>,
375 impl CodegenContext {
376 pub fn create_diag_handler(&self) -> Handler {
377 Handler::with_emitter(true, false, Box::new(self.diag_emitter.clone()))
380 pub(crate) fn config(&self, kind: ModuleKind) -> &ModuleConfig {
382 ModuleKind::Regular => &self.regular_module_config,
383 ModuleKind::Metadata => &self.metadata_module_config,
384 ModuleKind::Allocator => &self.allocator_module_config,
388 pub(crate) fn save_temp_bitcode(&self, trans: &ModuleTranslation, name: &str) {
389 if !self.save_temps {
393 let ext = format!("{}.bc", name);
394 let cgu = Some(&trans.name[..]);
395 let path = self.output_filenames.temp_path_ext(&ext, cgu);
396 let cstr = path2cstr(&path);
397 let llmod = trans.llvm().unwrap().llmod;
398 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
403 struct DiagnosticHandlers<'a> {
404 inner: Box<(&'a CodegenContext, &'a Handler)>,
408 impl<'a> DiagnosticHandlers<'a> {
409 fn new(cgcx: &'a CodegenContext,
410 handler: &'a Handler,
411 llcx: ContextRef) -> DiagnosticHandlers<'a> {
412 let data = Box::new((cgcx, handler));
414 let arg = &*data as &(_, _) as *const _ as *mut _;
415 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, arg);
416 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, arg);
425 impl<'a> Drop for DiagnosticHandlers<'a> {
428 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, 0 as *mut _);
429 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, 0 as *mut _);
434 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext,
437 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_string());
440 unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
446 let (cgcx, _) = *(user as *const (&CodegenContext, &Handler));
448 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
449 .expect("non-UTF8 SMDiagnostic");
451 report_inline_asm(cgcx, &msg, cookie);
454 unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
458 let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler));
460 match llvm::diagnostic::Diagnostic::unpack(info) {
461 llvm::diagnostic::InlineAsm(inline) => {
462 report_inline_asm(cgcx,
463 &llvm::twine_to_string(inline.message),
467 llvm::diagnostic::Optimization(opt) => {
468 let enabled = match cgcx.remark {
470 SomePasses(ref v) => v.iter().any(|s| *s == opt.pass_name),
474 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
483 llvm::diagnostic::PGO(diagnostic_ref) => {
484 let msg = llvm::build_string(|s| {
485 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
486 }).expect("non-UTF8 PGO diagnostic");
487 diag_handler.warn(&msg);
489 llvm::diagnostic::UnknownDiagnostic(..) => {},
493 // Unsafe due to LLVM calls.
494 unsafe fn optimize(cgcx: &CodegenContext,
495 diag_handler: &Handler,
496 mtrans: &ModuleTranslation,
497 config: &ModuleConfig,
498 timeline: &mut Timeline)
499 -> Result<(), FatalError>
501 let (llmod, llcx, tm) = match mtrans.source {
502 ModuleSource::Translated(ref llvm) => (llvm.llmod, llvm.llcx, llvm.tm),
503 ModuleSource::Preexisting(_) => {
504 bug!("optimize_and_codegen: called with ModuleSource::Preexisting")
508 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
510 let module_name = mtrans.name.clone();
511 let module_name = Some(&module_name[..]);
513 if config.emit_no_opt_bc {
514 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
515 let out = path2cstr(&out);
516 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
519 if config.opt_level.is_some() {
520 // Create the two optimizing pass managers. These mirror what clang
521 // does, and are by populated by LLVM's default PassManagerBuilder.
522 // Each manager has a different set of passes, but they also share
523 // some common passes.
524 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
525 let mpm = llvm::LLVMCreatePassManager();
527 // If we're verifying or linting, add them to the function pass
529 let addpass = |pass_name: &str| {
530 let pass_name = CString::new(pass_name).unwrap();
531 let pass = llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr());
535 let pass_manager = match llvm::LLVMRustPassKind(pass) {
536 llvm::PassKind::Function => fpm,
537 llvm::PassKind::Module => mpm,
538 llvm::PassKind::Other => {
539 diag_handler.err("Encountered LLVM pass kind we can't handle");
543 llvm::LLVMRustAddPass(pass_manager, pass);
547 if !config.no_verify { assert!(addpass("verify")); }
548 if !config.no_prepopulate_passes {
549 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
550 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
551 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
552 with_llvm_pmb(llmod, &config, opt_level, &mut |b| {
553 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
554 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
558 for pass in &config.passes {
560 diag_handler.warn(&format!("unknown pass `{}`, ignoring",
565 for pass in &cgcx.plugin_passes {
567 diag_handler.err(&format!("a plugin asked for LLVM pass \
568 `{}` but LLVM does not \
569 recognize it", pass));
573 diag_handler.abort_if_errors();
575 // Finally, run the actual optimization passes
576 time_ext(config.time_passes,
578 &format!("llvm function passes [{}]", module_name.unwrap()),
580 llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
582 timeline.record("fpm");
583 time_ext(config.time_passes,
585 &format!("llvm module passes [{}]", module_name.unwrap()),
587 llvm::LLVMRunPassManager(mpm, llmod)
590 // Deallocate managers that we're now done with
591 llvm::LLVMDisposePassManager(fpm);
592 llvm::LLVMDisposePassManager(mpm);
597 fn generate_lto_work(cgcx: &CodegenContext,
598 modules: Vec<ModuleTranslation>)
599 -> Vec<(WorkItem, u64)>
601 let mut timeline = cgcx.time_graph.as_ref().map(|tg| {
602 tg.start(TRANS_WORKER_TIMELINE,
603 TRANS_WORK_PACKAGE_KIND,
605 }).unwrap_or(Timeline::noop());
606 let lto_modules = lto::run(cgcx, modules, &mut timeline)
607 .unwrap_or_else(|e| e.raise());
609 lto_modules.into_iter().map(|module| {
610 let cost = module.cost();
611 (WorkItem::LTO(module), cost)
615 unsafe fn codegen(cgcx: &CodegenContext,
616 diag_handler: &Handler,
617 mtrans: ModuleTranslation,
618 config: &ModuleConfig,
619 timeline: &mut Timeline)
620 -> Result<CompiledModule, FatalError>
622 timeline.record("codegen");
623 let (llmod, llcx, tm) = match mtrans.source {
624 ModuleSource::Translated(ref llvm) => (llvm.llmod, llvm.llcx, llvm.tm),
625 ModuleSource::Preexisting(_) => {
626 bug!("codegen: called with ModuleSource::Preexisting")
629 let module_name = mtrans.name.clone();
630 let module_name = Some(&module_name[..]);
631 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
633 if cgcx.msvc_imps_needed {
634 create_msvc_imps(cgcx, llcx, llmod);
637 // A codegen-specific pass manager is used to generate object
638 // files for an LLVM module.
640 // Apparently each of these pass managers is a one-shot kind of
641 // thing, so we create a new one for each type of output. The
642 // pass manager passed to the closure should be ensured to not
643 // escape the closure itself, and the manager should only be
645 unsafe fn with_codegen<F, R>(tm: TargetMachineRef,
649 where F: FnOnce(PassManagerRef) -> R,
651 let cpm = llvm::LLVMCreatePassManager();
652 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
653 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
657 // If we don't have the integrated assembler, then we need to emit asm
658 // from LLVM and use `gcc` to create the object file.
659 let asm_to_obj = config.emit_obj && config.no_integrated_as;
661 // Change what we write and cleanup based on whether obj files are
662 // just llvm bitcode. In that case write bitcode, and possibly
663 // delete the bitcode if it wasn't requested. Don't generate the
664 // machine code, instead copy the .o file from the .bc
665 let write_bc = config.emit_bc || config.obj_is_bitcode;
666 let rm_bc = !config.emit_bc && config.obj_is_bitcode;
667 let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
668 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
670 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
671 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
674 if write_bc || config.emit_bc_compressed || config.embed_bitcode {
677 let data = if llvm::LLVMRustThinLTOAvailable() {
678 thin = ThinBuffer::new(llmod);
681 old = ModuleBuffer::new(llmod);
684 timeline.record("make-bc");
687 if let Err(e) = fs::write(&bc_out, data) {
688 diag_handler.err(&format!("failed to write bytecode: {}", e));
690 timeline.record("write-bc");
693 if config.embed_bitcode {
694 embed_bitcode(cgcx, llcx, llmod, Some(data));
695 timeline.record("embed-bc");
698 if config.emit_bc_compressed {
699 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
700 let data = bytecode::encode(&mtrans.llmod_id, data);
701 if let Err(e) = fs::write(&dst, data) {
702 diag_handler.err(&format!("failed to write bytecode: {}", e));
704 timeline.record("compress-bc");
706 } else if config.embed_bitcode_marker {
707 embed_bitcode(cgcx, llcx, llmod, None);
710 time_ext(config.time_passes, None, &format!("codegen passes [{}]", module_name.unwrap()),
711 || -> Result<(), FatalError> {
713 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
714 let out = path2cstr(&out);
716 extern "C" fn demangle_callback(input_ptr: *const c_char,
718 output_ptr: *mut c_char,
719 output_len: size_t) -> size_t {
721 slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
724 let input = match str::from_utf8(input) {
729 let output = unsafe {
730 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
732 let mut cursor = io::Cursor::new(output);
734 let demangled = match rustc_demangle::try_demangle(input) {
739 if let Err(_) = write!(cursor, "{:#}", demangled) {
740 // Possible only if provided buffer is not big enough
744 cursor.position() as size_t
747 with_codegen(tm, llmod, config.no_builtins, |cpm| {
748 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
749 llvm::LLVMDisposePassManager(cpm);
751 timeline.record("ir");
754 if config.emit_asm || asm_to_obj {
755 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
757 // We can't use the same module for asm and binary output, because that triggers
758 // various errors like invalid IR or broken binaries, so we might have to clone the
759 // module to produce the asm output
760 let llmod = if config.emit_obj {
761 llvm::LLVMCloneModule(llmod)
765 with_codegen(tm, llmod, config.no_builtins, |cpm| {
766 write_output_file(diag_handler, tm, cpm, llmod, &path,
767 llvm::FileType::AssemblyFile)
770 llvm::LLVMDisposeModule(llmod);
772 timeline.record("asm");
776 with_codegen(tm, llmod, config.no_builtins, |cpm| {
777 write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
778 llvm::FileType::ObjectFile)
780 timeline.record("obj");
781 } else if asm_to_obj {
782 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
783 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
784 timeline.record("asm_to_obj");
786 if !config.emit_asm && !cgcx.save_temps {
787 drop(fs::remove_file(&assembly));
795 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
796 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
797 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
802 debug!("removing_bitcode {:?}", bc_out);
803 if let Err(e) = fs::remove_file(&bc_out) {
804 diag_handler.err(&format!("failed to remove bitcode: {}", e));
809 Ok(mtrans.into_compiled_module(config.emit_obj,
811 config.emit_bc_compressed,
812 &cgcx.output_filenames))
815 /// Embed the bitcode of an LLVM module in the LLVM module itself.
817 /// This is done primarily for iOS where it appears to be standard to compile C
818 /// code at least with `-fembed-bitcode` which creates two sections in the
821 /// * __LLVM,__bitcode
822 /// * __LLVM,__cmdline
824 /// It appears *both* of these sections are necessary to get the linker to
825 /// recognize what's going on. For us though we just always throw in an empty
828 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
829 /// embed an empty section.
831 /// Basically all of this is us attempting to follow in the footsteps of clang
832 /// on iOS. See #35968 for lots more info.
833 unsafe fn embed_bitcode(cgcx: &CodegenContext,
836 bitcode: Option<&[u8]>) {
837 let llconst = C_bytes_in_context(llcx, bitcode.unwrap_or(&[]));
838 let llglobal = llvm::LLVMAddGlobal(
840 val_ty(llconst).to_ref(),
841 "rustc.embedded.module\0".as_ptr() as *const _,
843 llvm::LLVMSetInitializer(llglobal, llconst);
844 let section = if cgcx.opts.target_triple.triple().contains("-ios") {
849 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
850 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
852 let llconst = C_bytes_in_context(llcx, &[]);
853 let llglobal = llvm::LLVMAddGlobal(
855 val_ty(llconst).to_ref(),
856 "rustc.embedded.cmdline\0".as_ptr() as *const _,
858 llvm::LLVMSetInitializer(llglobal, llconst);
859 let section = if cgcx.opts.target_triple.triple().contains("-ios") {
864 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
865 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
868 pub(crate) struct CompiledModules {
869 pub modules: Vec<CompiledModule>,
870 pub metadata_module: CompiledModule,
871 pub allocator_module: Option<CompiledModule>,
874 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
875 sess.crate_types.borrow().contains(&config::CrateTypeRlib) &&
876 sess.opts.output_types.contains_key(&OutputType::Exe)
879 pub fn start_async_translation(tcx: TyCtxt,
880 time_graph: Option<TimeGraph>,
882 metadata: EncodedMetadata,
883 coordinator_receive: Receiver<Box<Any + Send>>,
885 -> OngoingCrateTranslation {
887 let crate_name = tcx.crate_name(LOCAL_CRATE);
888 let no_builtins = attr::contains_name(&tcx.hir.krate().attrs, "no_builtins");
889 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir.krate().attrs,
890 "windows_subsystem");
891 let windows_subsystem = subsystem.map(|subsystem| {
892 if subsystem != "windows" && subsystem != "console" {
893 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
894 `windows` and `console` are allowed",
897 subsystem.to_string()
900 let linker_info = LinkerInfo::new(tcx);
901 let crate_info = CrateInfo::new(tcx);
903 // Figure out what we actually need to build.
904 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
905 let mut metadata_config = ModuleConfig::new(vec![]);
906 let mut allocator_config = ModuleConfig::new(vec![]);
908 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
910 Sanitizer::Address => {
911 modules_config.passes.push("asan".to_owned());
912 modules_config.passes.push("asan-module".to_owned());
914 Sanitizer::Memory => {
915 modules_config.passes.push("msan".to_owned())
917 Sanitizer::Thread => {
918 modules_config.passes.push("tsan".to_owned())
924 if sess.opts.debugging_opts.profile {
925 modules_config.passes.push("insert-gcov-profiling".to_owned())
928 modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
929 modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
931 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
932 modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
934 // Save all versions of the bytecode if we're saving our temporaries.
935 if sess.opts.cg.save_temps {
936 modules_config.emit_no_opt_bc = true;
937 modules_config.emit_bc = true;
938 modules_config.emit_lto_bc = true;
939 metadata_config.emit_bc = true;
940 allocator_config.emit_bc = true;
943 // Emit compressed bitcode files for the crate if we're emitting an rlib.
944 // Whenever an rlib is created, the bitcode is inserted into the archive in
945 // order to allow LTO against it.
946 if need_crate_bitcode_for_rlib(sess) {
947 modules_config.emit_bc_compressed = true;
948 allocator_config.emit_bc_compressed = true;
951 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
952 tcx.sess.target.target.options.no_integrated_as;
954 for output_type in sess.opts.output_types.keys() {
956 OutputType::Bitcode => { modules_config.emit_bc = true; }
957 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
958 OutputType::Assembly => {
959 modules_config.emit_asm = true;
960 // If we're not using the LLVM assembler, this function
961 // could be invoked specially with output_type_assembly, so
962 // in this case we still want the metadata object file.
963 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
964 metadata_config.emit_obj = true;
965 allocator_config.emit_obj = true;
968 OutputType::Object => { modules_config.emit_obj = true; }
969 OutputType::Metadata => { metadata_config.emit_obj = true; }
971 modules_config.emit_obj = true;
972 metadata_config.emit_obj = true;
973 allocator_config.emit_obj = true;
975 OutputType::Mir => {}
976 OutputType::DepInfo => {}
980 modules_config.set_flags(sess, no_builtins);
981 metadata_config.set_flags(sess, no_builtins);
982 allocator_config.set_flags(sess, no_builtins);
984 // Exclude metadata and allocator modules from time_passes output, since
985 // they throw off the "LLVM passes" measurement.
986 metadata_config.time_passes = false;
987 allocator_config.time_passes = false;
989 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
990 let (trans_worker_send, trans_worker_receive) = channel();
992 let coordinator_thread = start_executing_work(tcx,
998 sess.jobserver.clone(),
1000 Arc::new(modules_config),
1001 Arc::new(metadata_config),
1002 Arc::new(allocator_config));
1004 OngoingCrateTranslation {
1013 coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
1014 trans_worker_receive,
1015 shared_emitter_main,
1016 future: coordinator_thread,
1017 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1021 fn copy_module_artifacts_into_incr_comp_cache(sess: &Session,
1022 dep_graph: &DepGraph,
1023 compiled_modules: &CompiledModules) {
1024 if sess.opts.incremental.is_none() {
1028 for module in compiled_modules.modules.iter() {
1029 let mut files = vec![];
1031 if let Some(ref path) = module.object {
1032 files.push((WorkProductFileKind::Object, path.clone()));
1034 if let Some(ref path) = module.bytecode {
1035 files.push((WorkProductFileKind::Bytecode, path.clone()));
1037 if let Some(ref path) = module.bytecode_compressed {
1038 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
1041 save_trans_partition(sess, dep_graph, &module.name, &files);
1045 fn produce_final_output_artifacts(sess: &Session,
1046 compiled_modules: &CompiledModules,
1047 crate_output: &OutputFilenames) {
1048 let mut user_wants_bitcode = false;
1049 let mut user_wants_objects = false;
1051 // Produce final compile outputs.
1052 let copy_gracefully = |from: &Path, to: &Path| {
1053 if let Err(e) = fs::copy(from, to) {
1054 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
1058 let copy_if_one_unit = |output_type: OutputType,
1059 keep_numbered: bool| {
1060 if compiled_modules.modules.len() == 1 {
1061 // 1) Only one codegen unit. In this case it's no difficulty
1062 // to copy `foo.0.x` to `foo.x`.
1063 let module_name = Some(&compiled_modules.modules[0].name[..]);
1064 let path = crate_output.temp_path(output_type, module_name);
1065 copy_gracefully(&path,
1066 &crate_output.path(output_type));
1067 if !sess.opts.cg.save_temps && !keep_numbered {
1068 // The user just wants `foo.x`, not `foo.#module-name#.x`.
1069 remove(sess, &path);
1072 let ext = crate_output.temp_path(output_type, None)
1079 if crate_output.outputs.contains_key(&output_type) {
1080 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
1081 // no good solution for this case, so warn the user.
1082 sess.warn(&format!("ignoring emit path because multiple .{} files \
1083 were produced", ext));
1084 } else if crate_output.single_output_file.is_some() {
1085 // 3) Multiple codegen units, with `-o some_name`. We have
1086 // no good solution for this case, so warn the user.
1087 sess.warn(&format!("ignoring -o because multiple .{} files \
1088 were produced", ext));
1090 // 4) Multiple codegen units, but no explicit name. We
1091 // just leave the `foo.0.x` files in place.
1092 // (We don't have to do any work in this case.)
1097 // Flag to indicate whether the user explicitly requested bitcode.
1098 // Otherwise, we produced it only as a temporary output, and will need
1099 // to get rid of it.
1100 for output_type in crate_output.outputs.keys() {
1101 match *output_type {
1102 OutputType::Bitcode => {
1103 user_wants_bitcode = true;
1104 // Copy to .bc, but always keep the .0.bc. There is a later
1105 // check to figure out if we should delete .0.bc files, or keep
1106 // them for making an rlib.
1107 copy_if_one_unit(OutputType::Bitcode, true);
1109 OutputType::LlvmAssembly => {
1110 copy_if_one_unit(OutputType::LlvmAssembly, false);
1112 OutputType::Assembly => {
1113 copy_if_one_unit(OutputType::Assembly, false);
1115 OutputType::Object => {
1116 user_wants_objects = true;
1117 copy_if_one_unit(OutputType::Object, true);
1120 OutputType::Metadata |
1122 OutputType::DepInfo => {}
1126 // Clean up unwanted temporary files.
1128 // We create the following files by default:
1129 // - #crate#.#module-name#.bc
1130 // - #crate#.#module-name#.o
1131 // - #crate#.crate.metadata.bc
1132 // - #crate#.crate.metadata.o
1133 // - #crate#.o (linked from crate.##.o)
1134 // - #crate#.bc (copied from crate.##.bc)
1135 // We may create additional files if requested by the user (through
1136 // `-C save-temps` or `--emit=` flags).
1138 if !sess.opts.cg.save_temps {
1139 // Remove the temporary .#module-name#.o objects. If the user didn't
1140 // explicitly request bitcode (with --emit=bc), and the bitcode is not
1141 // needed for building an rlib, then we must remove .#module-name#.bc as
1144 // Specific rules for keeping .#module-name#.bc:
1145 // - If the user requested bitcode (`user_wants_bitcode`), and
1146 // codegen_units > 1, then keep it.
1147 // - If the user requested bitcode but codegen_units == 1, then we
1148 // can toss .#module-name#.bc because we copied it to .bc earlier.
1149 // - If we're not building an rlib and the user didn't request
1150 // bitcode, then delete .#module-name#.bc.
1151 // If you change how this works, also update back::link::link_rlib,
1152 // where .#module-name#.bc files are (maybe) deleted after making an
1154 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
1156 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
1158 let keep_numbered_objects = needs_crate_object ||
1159 (user_wants_objects && sess.codegen_units() > 1);
1161 for module in compiled_modules.modules.iter() {
1162 if let Some(ref path) = module.object {
1163 if !keep_numbered_objects {
1168 if let Some(ref path) = module.bytecode {
1169 if !keep_numbered_bitcode {
1175 if !user_wants_bitcode {
1176 if let Some(ref path) = compiled_modules.metadata_module.bytecode {
1177 remove(sess, &path);
1180 if let Some(ref allocator_module) = compiled_modules.allocator_module {
1181 if let Some(ref path) = allocator_module.bytecode {
1188 // We leave the following files around by default:
1190 // - #crate#.crate.metadata.o
1192 // These are used in linking steps and will be cleaned up afterward.
1195 pub(crate) fn dump_incremental_data(trans: &CrateTranslation) {
1196 println!("[incremental] Re-using {} out of {} modules",
1197 trans.modules.iter().filter(|m| m.pre_existing).count(),
1198 trans.modules.len());
1202 Optimize(ModuleTranslation),
1203 LTO(lto::LtoModuleTranslation),
1207 fn kind(&self) -> ModuleKind {
1209 WorkItem::Optimize(ref m) => m.kind,
1210 WorkItem::LTO(_) => ModuleKind::Regular,
1214 fn name(&self) -> String {
1216 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
1217 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
1222 enum WorkItemResult {
1223 Compiled(CompiledModule),
1224 NeedsLTO(ModuleTranslation),
1227 fn execute_work_item(cgcx: &CodegenContext,
1228 work_item: WorkItem,
1229 timeline: &mut Timeline)
1230 -> Result<WorkItemResult, FatalError>
1232 let diag_handler = cgcx.create_diag_handler();
1233 let config = cgcx.config(work_item.kind());
1234 let mtrans = match work_item {
1235 WorkItem::Optimize(mtrans) => mtrans,
1236 WorkItem::LTO(mut lto) => {
1238 let module = lto.optimize(cgcx, timeline)?;
1239 let module = codegen(cgcx, &diag_handler, module, config, timeline)?;
1240 return Ok(WorkItemResult::Compiled(module))
1244 let module_name = mtrans.name.clone();
1246 let pre_existing = match mtrans.source {
1247 ModuleSource::Translated(_) => None,
1248 ModuleSource::Preexisting(ref wp) => Some(wp.clone()),
1251 if let Some(wp) = pre_existing {
1252 let incr_comp_session_dir = cgcx.incr_comp_session_dir
1255 let name = &mtrans.name;
1256 let mut object = None;
1257 let mut bytecode = None;
1258 let mut bytecode_compressed = None;
1259 for (kind, saved_file) in wp.saved_files {
1260 let obj_out = match kind {
1261 WorkProductFileKind::Object => {
1262 let path = cgcx.output_filenames.temp_path(OutputType::Object, Some(name));
1263 object = Some(path.clone());
1266 WorkProductFileKind::Bytecode => {
1267 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(name));
1268 bytecode = Some(path.clone());
1271 WorkProductFileKind::BytecodeCompressed => {
1272 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(name))
1273 .with_extension(RLIB_BYTECODE_EXTENSION);
1274 bytecode_compressed = Some(path.clone());
1278 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
1280 debug!("copying pre-existing module `{}` from {:?} to {}",
1284 match link_or_copy(&source_file, &obj_out) {
1287 diag_handler.err(&format!("unable to copy {} to {}: {}",
1288 source_file.display(),
1294 assert_eq!(object.is_some(), config.emit_obj);
1295 assert_eq!(bytecode.is_some(), config.emit_bc);
1296 assert_eq!(bytecode_compressed.is_some(), config.emit_bc_compressed);
1298 Ok(WorkItemResult::Compiled(CompiledModule {
1299 llmod_id: mtrans.llmod_id.clone(),
1301 kind: ModuleKind::Regular,
1305 bytecode_compressed,
1308 debug!("llvm-optimizing {:?}", module_name);
1311 optimize(cgcx, &diag_handler, &mtrans, config, timeline)?;
1313 // After we've done the initial round of optimizations we need to
1314 // decide whether to synchronously codegen this module or ship it
1315 // back to the coordinator thread for further LTO processing (which
1316 // has to wait for all the initial modules to be optimized).
1318 // Here we dispatch based on the `cgcx.lto` and kind of module we're
1320 let needs_lto = match cgcx.lto {
1323 // Here we've got a full crate graph LTO requested. We ignore
1324 // this, however, if the crate type is only an rlib as there's
1325 // no full crate graph to process, that'll happen later.
1327 // This use case currently comes up primarily for targets that
1328 // require LTO so the request for LTO is always unconditionally
1329 // passed down to the backend, but we don't actually want to do
1330 // anything about it yet until we've got a final product.
1331 Lto::Yes | Lto::Fat | Lto::Thin => {
1332 cgcx.crate_types.len() != 1 ||
1333 cgcx.crate_types[0] != config::CrateTypeRlib
1336 // When we're automatically doing ThinLTO for multi-codegen-unit
1337 // builds we don't actually want to LTO the allocator modules if
1338 // it shows up. This is due to various linker shenanigans that
1339 // we'll encounter later.
1341 // Additionally here's where we also factor in the current LLVM
1342 // version. If it doesn't support ThinLTO we skip this.
1344 mtrans.kind != ModuleKind::Allocator &&
1345 llvm::LLVMRustThinLTOAvailable()
1349 // Metadata modules never participate in LTO regardless of the lto
1351 let needs_lto = needs_lto && mtrans.kind != ModuleKind::Metadata;
1354 Ok(WorkItemResult::NeedsLTO(mtrans))
1356 let module = codegen(cgcx, &diag_handler, mtrans, config, timeline)?;
1357 Ok(WorkItemResult::Compiled(module))
1364 Token(io::Result<Acquired>),
1366 result: ModuleTranslation,
1370 result: Result<CompiledModule, ()>,
1374 llvm_work_item: WorkItem,
1377 TranslationComplete,
1383 code: Option<DiagnosticId>,
1387 #[derive(PartialEq, Clone, Copy, Debug)]
1388 enum MainThreadWorkerState {
1394 fn start_executing_work(tcx: TyCtxt,
1395 crate_info: &CrateInfo,
1396 shared_emitter: SharedEmitter,
1397 trans_worker_send: Sender<Message>,
1398 coordinator_receive: Receiver<Box<Any + Send>>,
1401 time_graph: Option<TimeGraph>,
1402 modules_config: Arc<ModuleConfig>,
1403 metadata_config: Arc<ModuleConfig>,
1404 allocator_config: Arc<ModuleConfig>)
1405 -> thread::JoinHandle<Result<CompiledModules, ()>> {
1406 let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1407 let sess = tcx.sess;
1409 // Compute the set of symbols we need to retain when doing LTO (if we need to)
1410 let exported_symbols = {
1411 let mut exported_symbols = FxHashMap();
1413 let copy_symbols = |cnum| {
1414 let symbols = tcx.exported_symbols(cnum)
1416 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1424 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1425 Some(Arc::new(exported_symbols))
1427 Lto::Yes | Lto::Fat | Lto::Thin => {
1428 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1429 for &cnum in tcx.crates().iter() {
1430 exported_symbols.insert(cnum, copy_symbols(cnum));
1432 Some(Arc::new(exported_symbols))
1437 // First up, convert our jobserver into a helper thread so we can use normal
1438 // mpsc channels to manage our messages and such.
1439 // After we've requested tokens then we'll, when we can,
1440 // get tokens on `coordinator_receive` which will
1441 // get managed in the main loop below.
1442 let coordinator_send2 = coordinator_send.clone();
1443 let helper = jobserver.into_helper_thread(move |token| {
1444 drop(coordinator_send2.send(Box::new(Message::Token(token))));
1445 }).expect("failed to spawn helper thread");
1447 let mut each_linked_rlib_for_lto = Vec::new();
1448 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1449 if link::ignored_for_lto(sess, crate_info, cnum) {
1452 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1455 let assembler_cmd = if modules_config.no_integrated_as {
1456 // HACK: currently we use linker (gcc) as our assembler
1457 let (name, mut cmd) = get_linker(sess);
1458 cmd.args(&sess.target.target.options.asm_args);
1459 Some(Arc::new(AssemblerCommand {
1467 let cgcx = CodegenContext {
1468 crate_types: sess.crate_types.borrow().clone(),
1469 each_linked_rlib_for_lto,
1471 no_landing_pads: sess.no_landing_pads(),
1472 fewer_names: sess.fewer_names(),
1473 save_temps: sess.opts.cg.save_temps,
1474 opts: Arc::new(sess.opts.clone()),
1475 time_passes: sess.time_passes(),
1477 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1478 remark: sess.opts.cg.remark.clone(),
1480 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1482 diag_emitter: shared_emitter.clone(),
1484 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1485 regular_module_config: modules_config,
1486 metadata_module_config: metadata_config,
1487 allocator_module_config: allocator_config,
1488 tm_factory: target_machine_factory(tcx.sess, false),
1490 msvc_imps_needed: msvc_imps_needed(tcx),
1491 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1492 debuginfo: tcx.sess.opts.debuginfo,
1496 // This is the "main loop" of parallel work happening for parallel codegen.
1497 // It's here that we manage parallelism, schedule work, and work with
1498 // messages coming from clients.
1500 // There are a few environmental pre-conditions that shape how the system
1503 // - Error reporting only can happen on the main thread because that's the
1504 // only place where we have access to the compiler `Session`.
1505 // - LLVM work can be done on any thread.
1506 // - Translation can only happen on the main thread.
1507 // - Each thread doing substantial work most be in possession of a `Token`
1508 // from the `Jobserver`.
1509 // - The compiler process always holds one `Token`. Any additional `Tokens`
1510 // have to be requested from the `Jobserver`.
1514 // The error reporting restriction is handled separately from the rest: We
1515 // set up a `SharedEmitter` the holds an open channel to the main thread.
1516 // When an error occurs on any thread, the shared emitter will send the
1517 // error message to the receiver main thread (`SharedEmitterMain`). The
1518 // main thread will periodically query this error message queue and emit
1519 // any error messages it has received. It might even abort compilation if
1520 // has received a fatal error. In this case we rely on all other threads
1521 // being torn down automatically with the main thread.
1522 // Since the main thread will often be busy doing translation work, error
1523 // reporting will be somewhat delayed, since the message queue can only be
1524 // checked in between to work packages.
1526 // Work Processing Infrastructure
1527 // ==============================
1528 // The work processing infrastructure knows three major actors:
1530 // - the coordinator thread,
1531 // - the main thread, and
1532 // - LLVM worker threads
1534 // The coordinator thread is running a message loop. It instructs the main
1535 // thread about what work to do when, and it will spawn off LLVM worker
1536 // threads as open LLVM WorkItems become available.
1538 // The job of the main thread is to translate CGUs into LLVM work package
1539 // (since the main thread is the only thread that can do this). The main
1540 // thread will block until it receives a message from the coordinator, upon
1541 // which it will translate one CGU, send it to the coordinator and block
1542 // again. This way the coordinator can control what the main thread is
1545 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1546 // available, it will spawn off a new LLVM worker thread and let it process
1547 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1548 // it will just shut down, which also frees all resources associated with
1549 // the given LLVM module, and sends a message to the coordinator that the
1550 // has been completed.
1554 // The scheduler's goal is to minimize the time it takes to complete all
1555 // work there is, however, we also want to keep memory consumption low
1556 // if possible. These two goals are at odds with each other: If memory
1557 // consumption were not an issue, we could just let the main thread produce
1558 // LLVM WorkItems at full speed, assuring maximal utilization of
1559 // Tokens/LLVM worker threads. However, since translation usual is faster
1560 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1561 // WorkItem potentially holds on to a substantial amount of memory.
1563 // So the actual goal is to always produce just enough LLVM WorkItems as
1564 // not to starve our LLVM worker threads. That means, once we have enough
1565 // WorkItems in our queue, we can block the main thread, so it does not
1566 // produce more until we need them.
1568 // Doing LLVM Work on the Main Thread
1569 // ----------------------------------
1570 // Since the main thread owns the compiler processes implicit `Token`, it is
1571 // wasteful to keep it blocked without doing any work. Therefore, what we do
1572 // in this case is: We spawn off an additional LLVM worker thread that helps
1573 // reduce the queue. The work it is doing corresponds to the implicit
1574 // `Token`. The coordinator will mark the main thread as being busy with
1575 // LLVM work. (The actual work happens on another OS thread but we just care
1576 // about `Tokens`, not actual threads).
1578 // When any LLVM worker thread finishes while the main thread is marked as
1579 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1580 // of the just finished thread to the LLVM worker thread that is working on
1581 // behalf of the main thread's implicit Token, thus freeing up the main
1582 // thread again. The coordinator can then again decide what the main thread
1583 // should do. This allows the coordinator to make decisions at more points
1586 // Striking a Balance between Throughput and Memory Consumption
1587 // ------------------------------------------------------------
1588 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1589 // memory consumption as low as possible, are in conflict with each other,
1590 // we have to find a trade off between them. Right now, the goal is to keep
1591 // all workers busy, which means that no worker should find the queue empty
1592 // when it is ready to start.
1593 // How do we do achieve this? Good question :) We actually never know how
1594 // many `Tokens` are potentially available so it's hard to say how much to
1595 // fill up the queue before switching the main thread to LLVM work. Also we
1596 // currently don't have a means to estimate how long a running LLVM worker
1597 // will still be busy with it's current WorkItem. However, we know the
1598 // maximal count of available Tokens that makes sense (=the number of CPU
1599 // cores), so we can take a conservative guess. The heuristic we use here
1600 // is implemented in the `queue_full_enough()` function.
1602 // Some Background on Jobservers
1603 // -----------------------------
1604 // It's worth also touching on the management of parallelism here. We don't
1605 // want to just spawn a thread per work item because while that's optimal
1606 // parallelism it may overload a system with too many threads or violate our
1607 // configuration for the maximum amount of cpu to use for this process. To
1608 // manage this we use the `jobserver` crate.
1610 // Job servers are an artifact of GNU make and are used to manage
1611 // parallelism between processes. A jobserver is a glorified IPC semaphore
1612 // basically. Whenever we want to run some work we acquire the semaphore,
1613 // and whenever we're done with that work we release the semaphore. In this
1614 // manner we can ensure that the maximum number of parallel workers is
1615 // capped at any one point in time.
1617 // LTO and the coordinator thread
1618 // ------------------------------
1620 // The final job the coordinator thread is responsible for is managing LTO
1621 // and how that works. When LTO is requested what we'll to is collect all
1622 // optimized LLVM modules into a local vector on the coordinator. Once all
1623 // modules have been translated and optimized we hand this to the `lto`
1624 // module for further optimization. The `lto` module will return back a list
1625 // of more modules to work on, which the coordinator will continue to spawn
1628 // Each LLVM module is automatically sent back to the coordinator for LTO if
1629 // necessary. There's already optimizations in place to avoid sending work
1630 // back to the coordinator if LTO isn't requested.
1631 return thread::spawn(move || {
1632 // We pretend to be within the top-level LLVM time-passes task here:
1635 let max_workers = ::num_cpus::get();
1636 let mut worker_id_counter = 0;
1637 let mut free_worker_ids = Vec::new();
1638 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1639 if let Some(id) = free_worker_ids.pop() {
1642 let id = worker_id_counter;
1643 worker_id_counter += 1;
1648 // This is where we collect codegen units that have gone all the way
1649 // through translation and LLVM.
1650 let mut compiled_modules = vec![];
1651 let mut compiled_metadata_module = None;
1652 let mut compiled_allocator_module = None;
1653 let mut needs_lto = Vec::new();
1654 let mut started_lto = false;
1656 // This flag tracks whether all items have gone through translations
1657 let mut translation_done = false;
1659 // This is the queue of LLVM work items that still need processing.
1660 let mut work_items = Vec::<(WorkItem, u64)>::new();
1662 // This are the Jobserver Tokens we currently hold. Does not include
1663 // the implicit Token the compiler process owns no matter what.
1664 let mut tokens = Vec::new();
1666 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1667 let mut running = 0;
1669 let mut llvm_start_time = None;
1671 // Run the message loop while there's still anything that needs message
1673 while !translation_done ||
1674 work_items.len() > 0 ||
1676 needs_lto.len() > 0 ||
1677 main_thread_worker_state != MainThreadWorkerState::Idle {
1679 // While there are still CGUs to be translated, the coordinator has
1680 // to decide how to utilize the compiler processes implicit Token:
1681 // For translating more CGU or for running them through LLVM.
1682 if !translation_done {
1683 if main_thread_worker_state == MainThreadWorkerState::Idle {
1684 if !queue_full_enough(work_items.len(), running, max_workers) {
1685 // The queue is not full enough, translate more items:
1686 if let Err(_) = trans_worker_send.send(Message::TranslateItem) {
1687 panic!("Could not send Message::TranslateItem to main thread")
1689 main_thread_worker_state = MainThreadWorkerState::Translating;
1691 // The queue is full enough to not let the worker
1692 // threads starve. Use the implicit Token to do some
1694 let (item, _) = work_items.pop()
1695 .expect("queue empty - queue_full_enough() broken?");
1696 let cgcx = CodegenContext {
1697 worker: get_worker_id(&mut free_worker_ids),
1700 maybe_start_llvm_timer(cgcx.config(item.kind()),
1701 &mut llvm_start_time);
1702 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1703 spawn_work(cgcx, item);
1707 // If we've finished everything related to normal translation
1708 // then it must be the case that we've got some LTO work to do.
1709 // Perform the serial work here of figuring out what we're
1710 // going to LTO and then push a bunch of work items onto our
1712 if work_items.len() == 0 &&
1714 main_thread_worker_state == MainThreadWorkerState::Idle {
1715 assert!(!started_lto);
1716 assert!(needs_lto.len() > 0);
1718 let modules = mem::replace(&mut needs_lto, Vec::new());
1719 for (work, cost) in generate_lto_work(&cgcx, modules) {
1720 let insertion_index = work_items
1721 .binary_search_by_key(&cost, |&(_, cost)| cost)
1722 .unwrap_or_else(|e| e);
1723 work_items.insert(insertion_index, (work, cost));
1724 helper.request_token();
1728 // In this branch, we know that everything has been translated,
1729 // so it's just a matter of determining whether the implicit
1730 // Token is free to use for LLVM work.
1731 match main_thread_worker_state {
1732 MainThreadWorkerState::Idle => {
1733 if let Some((item, _)) = work_items.pop() {
1734 let cgcx = CodegenContext {
1735 worker: get_worker_id(&mut free_worker_ids),
1738 maybe_start_llvm_timer(cgcx.config(item.kind()),
1739 &mut llvm_start_time);
1740 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1741 spawn_work(cgcx, item);
1743 // There is no unstarted work, so let the main thread
1744 // take over for a running worker. Otherwise the
1745 // implicit token would just go to waste.
1746 // We reduce the `running` counter by one. The
1747 // `tokens.truncate()` below will take care of
1748 // giving the Token back.
1749 debug_assert!(running > 0);
1751 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1754 MainThreadWorkerState::Translating => {
1755 bug!("trans worker should not be translating after \
1756 translation was already completed")
1758 MainThreadWorkerState::LLVMing => {
1759 // Already making good use of that token
1764 // Spin up what work we can, only doing this while we've got available
1765 // parallelism slots and work left to spawn.
1766 while work_items.len() > 0 && running < tokens.len() {
1767 let (item, _) = work_items.pop().unwrap();
1769 maybe_start_llvm_timer(cgcx.config(item.kind()),
1770 &mut llvm_start_time);
1772 let cgcx = CodegenContext {
1773 worker: get_worker_id(&mut free_worker_ids),
1777 spawn_work(cgcx, item);
1781 // Relinquish accidentally acquired extra tokens
1782 tokens.truncate(running);
1784 let msg = coordinator_receive.recv().unwrap();
1785 match *msg.downcast::<Message>().ok().unwrap() {
1786 // Save the token locally and the next turn of the loop will use
1787 // this to spawn a new unit of work, or it may get dropped
1788 // immediately if we have no more work to spawn.
1789 Message::Token(token) => {
1794 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1795 // If the main thread token is used for LLVM work
1796 // at the moment, we turn that thread into a regular
1797 // LLVM worker thread, so the main thread is free
1798 // to react to translation demand.
1799 main_thread_worker_state = MainThreadWorkerState::Idle;
1804 let msg = &format!("failed to acquire jobserver token: {}", e);
1805 shared_emitter.fatal(msg);
1806 // Exit the coordinator thread
1812 Message::TranslationDone { llvm_work_item, cost } => {
1813 // We keep the queue sorted by estimated processing cost,
1814 // so that more expensive items are processed earlier. This
1815 // is good for throughput as it gives the main thread more
1816 // time to fill up the queue and it avoids scheduling
1817 // expensive items to the end.
1818 // Note, however, that this is not ideal for memory
1819 // consumption, as LLVM module sizes are not evenly
1821 let insertion_index =
1822 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1823 let insertion_index = match insertion_index {
1824 Ok(idx) | Err(idx) => idx
1826 work_items.insert(insertion_index, (llvm_work_item, cost));
1828 helper.request_token();
1829 assert_eq!(main_thread_worker_state,
1830 MainThreadWorkerState::Translating);
1831 main_thread_worker_state = MainThreadWorkerState::Idle;
1834 Message::TranslationComplete => {
1835 translation_done = true;
1836 assert_eq!(main_thread_worker_state,
1837 MainThreadWorkerState::Translating);
1838 main_thread_worker_state = MainThreadWorkerState::Idle;
1841 // If a thread exits successfully then we drop a token associated
1842 // with that worker and update our `running` count. We may later
1843 // re-acquire a token to continue running more work. We may also not
1844 // actually drop a token here if the worker was running with an
1845 // "ephemeral token"
1847 // Note that if the thread failed that means it panicked, so we
1848 // abort immediately.
1849 Message::Done { result: Ok(compiled_module), worker_id } => {
1850 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1851 main_thread_worker_state = MainThreadWorkerState::Idle;
1856 free_worker_ids.push(worker_id);
1858 match compiled_module.kind {
1859 ModuleKind::Regular => {
1860 compiled_modules.push(compiled_module);
1862 ModuleKind::Metadata => {
1863 assert!(compiled_metadata_module.is_none());
1864 compiled_metadata_module = Some(compiled_module);
1866 ModuleKind::Allocator => {
1867 assert!(compiled_allocator_module.is_none());
1868 compiled_allocator_module = Some(compiled_module);
1872 Message::NeedsLTO { result, worker_id } => {
1873 assert!(!started_lto);
1874 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1875 main_thread_worker_state = MainThreadWorkerState::Idle;
1880 free_worker_ids.push(worker_id);
1881 needs_lto.push(result);
1883 Message::Done { result: Err(()), worker_id: _ } => {
1884 shared_emitter.fatal("aborting due to worker thread failure");
1885 // Exit the coordinator thread
1888 Message::TranslateItem => {
1889 bug!("the coordinator should not receive translation requests")
1894 if let Some(llvm_start_time) = llvm_start_time {
1895 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
1896 // This is the top-level timing for all of LLVM, set the time-depth
1899 print_time_passes_entry(cgcx.time_passes,
1904 // Regardless of what order these modules completed in, report them to
1905 // the backend in the same order every time to ensure that we're handing
1906 // out deterministic results.
1907 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1909 let compiled_metadata_module = compiled_metadata_module
1910 .expect("Metadata module not compiled?");
1912 Ok(CompiledModules {
1913 modules: compiled_modules,
1914 metadata_module: compiled_metadata_module,
1915 allocator_module: compiled_allocator_module,
1919 // A heuristic that determines if we have enough LLVM WorkItems in the
1920 // queue so that the main thread can do LLVM work instead of translation
1921 fn queue_full_enough(items_in_queue: usize,
1922 workers_running: usize,
1923 max_workers: usize) -> bool {
1925 items_in_queue > 0 &&
1926 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1929 fn maybe_start_llvm_timer(config: &ModuleConfig,
1930 llvm_start_time: &mut Option<Instant>) {
1931 // We keep track of the -Ztime-passes output manually,
1932 // since the closure-based interface does not fit well here.
1933 if config.time_passes {
1934 if llvm_start_time.is_none() {
1935 *llvm_start_time = Some(Instant::now());
1941 pub const TRANS_WORKER_ID: usize = ::std::usize::MAX;
1942 pub const TRANS_WORKER_TIMELINE: time_graph::TimelineId =
1943 time_graph::TimelineId(TRANS_WORKER_ID);
1944 pub const TRANS_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1945 time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
1946 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1947 time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
1949 fn spawn_work(cgcx: CodegenContext, work: WorkItem) {
1950 let depth = time_depth();
1952 thread::spawn(move || {
1953 set_time_depth(depth);
1955 // Set up a destructor which will fire off a message that we're done as
1958 coordinator_send: Sender<Box<Any + Send>>,
1959 result: Option<WorkItemResult>,
1962 impl Drop for Bomb {
1963 fn drop(&mut self) {
1964 let worker_id = self.worker_id;
1965 let msg = match self.result.take() {
1966 Some(WorkItemResult::Compiled(m)) => {
1967 Message::Done { result: Ok(m), worker_id }
1969 Some(WorkItemResult::NeedsLTO(m)) => {
1970 Message::NeedsLTO { result: m, worker_id }
1972 None => Message::Done { result: Err(()), worker_id }
1974 drop(self.coordinator_send.send(Box::new(msg)));
1978 let mut bomb = Bomb {
1979 coordinator_send: cgcx.coordinator_send.clone(),
1981 worker_id: cgcx.worker,
1984 // Execute the work itself, and if it finishes successfully then flag
1985 // ourselves as a success as well.
1987 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1988 // as a diagnostic was already sent off to the main thread - just
1989 // surface that there was an error in this worker.
1991 let timeline = cgcx.time_graph.as_ref().map(|tg| {
1992 tg.start(time_graph::TimelineId(cgcx.worker),
1993 LLVM_WORK_PACKAGE_KIND,
1996 let mut timeline = timeline.unwrap_or(Timeline::noop());
1997 execute_work_item(&cgcx, work, &mut timeline).ok()
2002 pub fn run_assembler(cgcx: &CodegenContext, handler: &Handler, assembly: &Path, object: &Path) {
2003 let assembler = cgcx.assembler_cmd
2005 .expect("cgcx.assembler_cmd is missing?");
2007 let pname = &assembler.name;
2008 let mut cmd = assembler.cmd.clone();
2009 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
2010 debug!("{:?}", cmd);
2012 match cmd.output() {
2014 if !prog.status.success() {
2015 let mut note = prog.stderr.clone();
2016 note.extend_from_slice(&prog.stdout);
2018 handler.struct_err(&format!("linking with `{}` failed: {}",
2021 .note(&format!("{:?}", &cmd))
2022 .note(str::from_utf8(¬e[..]).unwrap())
2024 handler.abort_if_errors();
2028 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
2029 handler.abort_if_errors();
2034 pub unsafe fn with_llvm_pmb(llmod: ModuleRef,
2035 config: &ModuleConfig,
2036 opt_level: llvm::CodeGenOptLevel,
2037 f: &mut FnMut(llvm::PassManagerBuilderRef)) {
2040 // Create the PassManagerBuilder for LLVM. We configure it with
2041 // reasonable defaults and prepare it to actually populate the pass
2043 let builder = llvm::LLVMPassManagerBuilderCreate();
2044 let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
2045 let inline_threshold = config.inline_threshold;
2047 let pgo_gen_path = config.pgo_gen.as_ref().map(|s| {
2048 let s = if s.is_empty() { "default_%m.profraw" } else { s };
2049 CString::new(s.as_bytes()).unwrap()
2052 let pgo_use_path = if config.pgo_use.is_empty() {
2055 Some(CString::new(config.pgo_use.as_bytes()).unwrap())
2058 llvm::LLVMRustConfigurePassManagerBuilder(
2061 config.merge_functions,
2062 config.vectorize_slp,
2063 config.vectorize_loop,
2064 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2065 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2068 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
2070 if opt_size != llvm::CodeGenOptSizeNone {
2071 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
2074 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
2076 // Here we match what clang does (kinda). For O0 we only inline
2077 // always-inline functions (but don't add lifetime intrinsics), at O1 we
2078 // inline with lifetime intrinsics, and O2+ we add an inliner with a
2079 // thresholds copied from clang.
2080 match (opt_level, opt_size, inline_threshold) {
2082 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
2084 (llvm::CodeGenOptLevel::Aggressive, ..) => {
2085 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
2087 (_, llvm::CodeGenOptSizeDefault, _) => {
2088 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
2090 (_, llvm::CodeGenOptSizeAggressive, _) => {
2091 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
2093 (llvm::CodeGenOptLevel::None, ..) => {
2094 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
2096 (llvm::CodeGenOptLevel::Less, ..) => {
2097 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
2099 (llvm::CodeGenOptLevel::Default, ..) => {
2100 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
2102 (llvm::CodeGenOptLevel::Other, ..) => {
2103 bug!("CodeGenOptLevel::Other selected")
2108 llvm::LLVMPassManagerBuilderDispose(builder);
2112 enum SharedEmitterMessage {
2113 Diagnostic(Diagnostic),
2114 InlineAsmError(u32, String),
2120 pub struct SharedEmitter {
2121 sender: Sender<SharedEmitterMessage>,
2124 pub struct SharedEmitterMain {
2125 receiver: Receiver<SharedEmitterMessage>,
2128 impl SharedEmitter {
2129 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
2130 let (sender, receiver) = channel();
2132 (SharedEmitter { sender }, SharedEmitterMain { receiver })
2135 fn inline_asm_error(&self, cookie: u32, msg: String) {
2136 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
2139 fn fatal(&self, msg: &str) {
2140 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2144 impl Emitter for SharedEmitter {
2145 fn emit(&mut self, db: &DiagnosticBuilder) {
2146 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2148 code: db.code.clone(),
2151 for child in &db.children {
2152 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2153 msg: child.message(),
2158 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
2162 impl SharedEmitterMain {
2163 pub fn check(&self, sess: &Session, blocking: bool) {
2165 let message = if blocking {
2166 match self.receiver.recv() {
2167 Ok(message) => Ok(message),
2171 match self.receiver.try_recv() {
2172 Ok(message) => Ok(message),
2178 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2179 let handler = sess.diagnostic();
2182 handler.emit_with_code(&MultiSpan::new(),
2188 handler.emit(&MultiSpan::new(),
2194 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
2195 match Mark::from_u32(cookie).expn_info() {
2196 Some(ei) => sess.span_err(ei.call_site, &msg),
2197 None => sess.err(&msg),
2200 Ok(SharedEmitterMessage::AbortIfErrors) => {
2201 sess.abort_if_errors();
2203 Ok(SharedEmitterMessage::Fatal(msg)) => {
2215 pub struct OngoingCrateTranslation {
2218 metadata: EncodedMetadata,
2219 windows_subsystem: Option<String>,
2220 linker_info: LinkerInfo,
2221 crate_info: CrateInfo,
2222 time_graph: Option<TimeGraph>,
2223 coordinator_send: Sender<Box<Any + Send>>,
2224 trans_worker_receive: Receiver<Message>,
2225 shared_emitter_main: SharedEmitterMain,
2226 future: thread::JoinHandle<Result<CompiledModules, ()>>,
2227 output_filenames: Arc<OutputFilenames>,
2230 impl OngoingCrateTranslation {
2231 pub(crate) fn join(self, sess: &Session, dep_graph: &DepGraph) -> CrateTranslation {
2232 self.shared_emitter_main.check(sess, true);
2233 let compiled_modules = match self.future.join() {
2234 Ok(Ok(compiled_modules)) => compiled_modules,
2236 sess.abort_if_errors();
2237 panic!("expected abort due to worker thread errors")
2240 sess.fatal("Error during translation/LLVM phase.");
2244 sess.abort_if_errors();
2246 if let Some(time_graph) = self.time_graph {
2247 time_graph.dump(&format!("{}-timings", self.crate_name));
2250 copy_module_artifacts_into_incr_comp_cache(sess,
2253 produce_final_output_artifacts(sess,
2255 &self.output_filenames);
2257 // FIXME: time_llvm_passes support - does this use a global context or
2259 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
2260 unsafe { llvm::LLVMRustPrintPassTimings(); }
2263 let trans = CrateTranslation {
2264 crate_name: self.crate_name,
2266 metadata: self.metadata,
2267 windows_subsystem: self.windows_subsystem,
2268 linker_info: self.linker_info,
2269 crate_info: self.crate_info,
2271 modules: compiled_modules.modules,
2272 allocator_module: compiled_modules.allocator_module,
2273 metadata_module: compiled_modules.metadata_module,
2279 pub(crate) fn submit_pre_translated_module_to_llvm(&self,
2281 mtrans: ModuleTranslation) {
2282 self.wait_for_signal_to_translate_item();
2283 self.check_for_errors(tcx.sess);
2285 // These are generally cheap and won't through off scheduling.
2287 submit_translated_module_to_llvm(tcx, mtrans, cost);
2290 pub fn translation_finished(&self, tcx: TyCtxt) {
2291 self.wait_for_signal_to_translate_item();
2292 self.check_for_errors(tcx.sess);
2293 drop(self.coordinator_send.send(Box::new(Message::TranslationComplete)));
2296 pub fn check_for_errors(&self, sess: &Session) {
2297 self.shared_emitter_main.check(sess, false);
2300 pub fn wait_for_signal_to_translate_item(&self) {
2301 match self.trans_worker_receive.recv() {
2302 Ok(Message::TranslateItem) => {
2305 Ok(_) => panic!("unexpected message"),
2307 // One of the LLVM threads must have panicked, fall through so
2308 // error handling can be reached.
2314 pub(crate) fn submit_translated_module_to_llvm(tcx: TyCtxt,
2315 mtrans: ModuleTranslation,
2317 let llvm_work_item = WorkItem::Optimize(mtrans);
2318 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::TranslationDone {
2324 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
2325 tcx.sess.target.target.options.is_like_msvc &&
2326 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib)
2329 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2330 // This is required to satisfy `dllimport` references to static data in .rlibs
2331 // when using MSVC linker. We do this only for data, as linker can fix up
2332 // code references on its own.
2333 // See #26591, #27438
2334 fn create_msvc_imps(cgcx: &CodegenContext, llcx: ContextRef, llmod: ModuleRef) {
2335 if !cgcx.msvc_imps_needed {
2338 // The x86 ABI seems to require that leading underscores are added to symbol
2339 // names, so we need an extra underscore on 32-bit. There's also a leading
2340 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2341 // underscores added in front).
2342 let prefix = if cgcx.target_pointer_width == "32" {
2348 let i8p_ty = Type::i8p_llcx(llcx);
2349 let globals = base::iter_globals(llmod)
2351 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
2352 llvm::LLVMIsDeclaration(val) == 0
2355 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2356 let mut imp_name = prefix.as_bytes().to_vec();
2357 imp_name.extend(name.to_bytes());
2358 let imp_name = CString::new(imp_name).unwrap();
2361 .collect::<Vec<_>>();
2362 for (imp_name, val) in globals {
2363 let imp = llvm::LLVMAddGlobal(llmod,
2365 imp_name.as_ptr() as *const _);
2366 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
2367 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);