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::{copy_cgu_workproducts_to_incr_comp_cache_dir, in_incr_comp_dir};
21 use rustc::dep_graph::{WorkProduct, WorkProductId, 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};
28 use llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
29 use {CodegenResults, ModuleSource, ModuleCodegen, CompiledModule, ModuleKind};
31 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
32 use rustc::ty::TyCtxt;
33 use rustc::util::common::{time_ext, time_depth, set_time_depth, print_time_passes_entry};
34 use rustc::util::common::path2cstr;
35 use rustc::util::fs::{link_or_copy};
36 use errors::{self, Handler, Level, DiagnosticBuilder, FatalError, DiagnosticId};
37 use errors::emitter::{Emitter};
39 use syntax::ext::hygiene::Mark;
40 use syntax_pos::MultiSpan;
41 use syntax_pos::symbol::Symbol;
43 use context::{is_pie_binary, get_reloc_model};
44 use common::{C_bytes_in_context, val_ty};
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: &'ll llvm::TargetMachine,
96 pm: &llvm::PassManager<'ll>,
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 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
115 config::OptLevel::No => llvm::CodeGenOptLevel::None,
116 config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
117 config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
118 config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
119 _ => llvm::CodeGenOptLevel::Default,
123 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
125 config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
126 config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
127 _ => llvm::CodeGenOptSizeNone,
131 pub fn create_target_machine(
134 ) -> &'static mut llvm::TargetMachine {
135 target_machine_factory(sess, find_features)().unwrap_or_else(|err| {
136 llvm_err(sess.diagnostic(), err).raise()
140 // If find_features is true this won't access `sess.crate_types` by assuming
141 // that `is_pie_binary` is false. When we discover LLVM target features
142 // `sess.crate_types` is uninitialized so we cannot access it.
143 pub fn target_machine_factory(sess: &Session, find_features: bool)
144 -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>
146 let reloc_model = get_reloc_model(sess);
148 let opt_level = get_llvm_opt_level(sess.opts.optimize);
149 let use_softfp = sess.opts.cg.soft_float;
151 let ffunction_sections = sess.target.target.options.function_sections;
152 let fdata_sections = ffunction_sections;
154 let code_model_arg = sess.opts.cg.code_model.as_ref().or(
155 sess.target.target.options.code_model.as_ref(),
158 let code_model = match code_model_arg {
160 match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
163 sess.err(&format!("{:?} is not a valid code model",
165 sess.abort_if_errors();
170 None => llvm::CodeModel::None,
173 let singlethread = sess.target.target.options.singlethread;
175 let triple = &sess.target.target.llvm_target;
177 let triple = CString::new(triple.as_bytes()).unwrap();
178 let cpu = sess.target_cpu();
179 let cpu = CString::new(cpu.as_bytes()).unwrap();
180 let features = attributes::llvm_target_features(sess)
183 let features = CString::new(features).unwrap();
184 let is_pie_binary = !find_features && is_pie_binary(sess);
185 let trap_unreachable = sess.target.target.options.trap_unreachable;
189 llvm::LLVMRustCreateTargetMachine(
190 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
204 format!("Could not create LLVM TargetMachine for triple: {}",
205 triple.to_str().unwrap())
210 /// Module-specific configuration for `optimize_and_codegen`.
211 pub struct ModuleConfig {
212 /// Names of additional optimization passes to run.
214 /// Some(level) to optimize at a certain level, or None to run
215 /// absolutely no optimizations (used for the metadata module).
216 pub opt_level: Option<llvm::CodeGenOptLevel>,
218 /// Some(level) to optimize binary size, or None to not affect program size.
219 opt_size: Option<llvm::CodeGenOptSize>,
221 pgo_gen: Option<String>,
224 // Flags indicating which outputs to produce.
225 emit_no_opt_bc: bool,
227 emit_bc_compressed: bool,
232 // Miscellaneous flags. These are mostly copied from command-line
234 pub verify_llvm_ir: bool,
235 no_prepopulate_passes: bool,
238 vectorize_loop: bool,
240 merge_functions: bool,
241 inline_threshold: Option<usize>,
242 // Instead of creating an object file by doing LLVM codegen, just
243 // make the object file bitcode. Provides easy compatibility with
244 // emscripten's ecc compiler, when used as the linker.
245 obj_is_bitcode: bool,
246 no_integrated_as: bool,
248 embed_bitcode_marker: bool,
252 fn new(passes: Vec<String>) -> ModuleConfig {
259 pgo_use: String::new(),
261 emit_no_opt_bc: false,
263 emit_bc_compressed: false,
268 obj_is_bitcode: false,
269 embed_bitcode: false,
270 embed_bitcode_marker: false,
271 no_integrated_as: false,
273 verify_llvm_ir: false,
274 no_prepopulate_passes: false,
277 vectorize_loop: false,
278 vectorize_slp: false,
279 merge_functions: false,
280 inline_threshold: None
284 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
285 self.verify_llvm_ir = sess.verify_llvm_ir();
286 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
287 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
288 self.time_passes = sess.time_passes();
289 self.inline_threshold = sess.opts.cg.inline_threshold;
290 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
291 sess.opts.debugging_opts.cross_lang_lto.enabled();
292 let embed_bitcode = sess.target.target.options.embed_bitcode ||
293 sess.opts.debugging_opts.embed_bitcode;
295 match sess.opts.optimize {
296 config::OptLevel::No |
297 config::OptLevel::Less => {
298 self.embed_bitcode_marker = embed_bitcode;
300 _ => self.embed_bitcode = embed_bitcode,
304 // Copy what clang does by turning on loop vectorization at O2 and
305 // slp vectorization at O3. Otherwise configure other optimization aspects
306 // of this pass manager builder.
307 // Turn off vectorization for emscripten, as it's not very well supported.
308 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
309 (sess.opts.optimize == config::OptLevel::Default ||
310 sess.opts.optimize == config::OptLevel::Aggressive) &&
311 !sess.target.target.options.is_like_emscripten;
313 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
314 sess.opts.optimize == config::OptLevel::Aggressive &&
315 !sess.target.target.options.is_like_emscripten;
317 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
318 sess.opts.optimize == config::OptLevel::Aggressive;
322 /// Assembler name and command used by codegen when no_integrated_as is enabled
323 struct AssemblerCommand {
328 /// Additional resources used by optimize_and_codegen (not module specific)
330 pub struct CodegenContext {
331 // Resouces needed when running LTO
332 pub time_passes: bool,
334 pub no_landing_pads: bool,
335 pub save_temps: bool,
336 pub fewer_names: bool,
337 pub exported_symbols: Option<Arc<ExportedSymbols>>,
338 pub opts: Arc<config::Options>,
339 pub crate_types: Vec<config::CrateType>,
340 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
341 output_filenames: Arc<OutputFilenames>,
342 regular_module_config: Arc<ModuleConfig>,
343 metadata_module_config: Arc<ModuleConfig>,
344 allocator_module_config: Arc<ModuleConfig>,
345 pub tm_factory: Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>,
346 pub msvc_imps_needed: bool,
347 pub target_pointer_width: String,
348 debuginfo: config::DebugInfoLevel,
350 // Number of cgus excluding the allocator/metadata modules
351 pub total_cgus: usize,
352 // Handler to use for diagnostics produced during codegen.
353 pub diag_emitter: SharedEmitter,
354 // LLVM passes added by plugins.
355 pub plugin_passes: Vec<String>,
356 // LLVM optimizations for which we want to print remarks.
358 // Worker thread number
360 // The incremental compilation session directory, or None if we are not
361 // compiling incrementally
362 pub incr_comp_session_dir: Option<PathBuf>,
363 // Channel back to the main control thread to send messages to
364 coordinator_send: Sender<Box<dyn Any + Send>>,
365 // A reference to the TimeGraph so we can register timings. None means that
366 // measuring is disabled.
367 time_graph: Option<TimeGraph>,
368 // The assembler command if no_integrated_as option is enabled, None otherwise
369 assembler_cmd: Option<Arc<AssemblerCommand>>,
372 impl CodegenContext {
373 pub fn create_diag_handler(&self) -> Handler {
374 Handler::with_emitter(true, false, Box::new(self.diag_emitter.clone()))
377 pub(crate) fn config(&self, kind: ModuleKind) -> &ModuleConfig {
379 ModuleKind::Regular => &self.regular_module_config,
380 ModuleKind::Metadata => &self.metadata_module_config,
381 ModuleKind::Allocator => &self.allocator_module_config,
385 pub(crate) fn save_temp_bitcode(&self, module: &ModuleCodegen, name: &str) {
386 if !self.save_temps {
390 let ext = format!("{}.bc", name);
391 let cgu = Some(&module.name[..]);
392 let path = self.output_filenames.temp_path_ext(&ext, cgu);
393 let cstr = path2cstr(&path);
394 let llmod = module.llvm().unwrap().llmod();
395 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
400 pub struct DiagnosticHandlers<'a> {
401 data: *mut (&'a CodegenContext, &'a Handler),
402 llcx: &'a llvm::Context,
405 impl<'a> DiagnosticHandlers<'a> {
406 pub fn new(cgcx: &'a CodegenContext,
407 handler: &'a Handler,
408 llcx: &'a llvm::Context) -> Self {
409 let data = Box::into_raw(Box::new((cgcx, handler)));
411 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data as *mut _);
412 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data as *mut _);
414 DiagnosticHandlers { data, llcx }
418 impl<'a> Drop for DiagnosticHandlers<'a> {
420 use std::ptr::null_mut;
422 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
423 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
424 drop(Box::from_raw(self.data));
429 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext,
432 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_string());
435 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
441 let (cgcx, _) = *(user as *const (&CodegenContext, &Handler));
443 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
444 .expect("non-UTF8 SMDiagnostic");
446 report_inline_asm(cgcx, &msg, cookie);
449 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
453 let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler));
455 match llvm::diagnostic::Diagnostic::unpack(info) {
456 llvm::diagnostic::InlineAsm(inline) => {
457 report_inline_asm(cgcx,
458 &llvm::twine_to_string(inline.message),
462 llvm::diagnostic::Optimization(opt) => {
463 let enabled = match cgcx.remark {
465 SomePasses(ref v) => v.iter().any(|s| *s == opt.pass_name),
469 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
478 llvm::diagnostic::PGO(diagnostic_ref) |
479 llvm::diagnostic::Linker(diagnostic_ref) => {
480 let msg = llvm::build_string(|s| {
481 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
482 }).expect("non-UTF8 diagnostic");
483 diag_handler.warn(&msg);
485 llvm::diagnostic::UnknownDiagnostic(..) => {},
489 // Unsafe due to LLVM calls.
490 unsafe fn optimize(cgcx: &CodegenContext,
491 diag_handler: &Handler,
492 module: &ModuleCodegen,
493 config: &ModuleConfig,
494 timeline: &mut Timeline)
495 -> Result<(), FatalError>
497 let (llmod, llcx, tm) = match module.source {
498 ModuleSource::Codegened(ref llvm) => (llvm.llmod(), &*llvm.llcx, &*llvm.tm),
499 ModuleSource::Preexisting(_) => {
500 bug!("optimize_and_codegen: called with ModuleSource::Preexisting")
504 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
506 let module_name = module.name.clone();
507 let module_name = Some(&module_name[..]);
509 if config.emit_no_opt_bc {
510 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
511 let out = path2cstr(&out);
512 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
515 if config.opt_level.is_some() {
516 // Create the two optimizing pass managers. These mirror what clang
517 // does, and are by populated by LLVM's default PassManagerBuilder.
518 // Each manager has a different set of passes, but they also share
519 // some common passes.
520 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
521 let mpm = llvm::LLVMCreatePassManager();
524 // If we're verifying or linting, add them to the function pass
526 let addpass = |pass_name: &str| {
527 let pass_name = CString::new(pass_name).unwrap();
528 let pass = match llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr()) {
530 None => return false,
532 let pass_manager = match llvm::LLVMRustPassKind(pass) {
533 llvm::PassKind::Function => &*fpm,
534 llvm::PassKind::Module => &*mpm,
535 llvm::PassKind::Other => {
536 diag_handler.err("Encountered LLVM pass kind we can't handle");
540 llvm::LLVMRustAddPass(pass_manager, pass);
544 if config.verify_llvm_ir { assert!(addpass("verify")); }
545 if !config.no_prepopulate_passes {
546 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
547 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
548 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
549 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal;
550 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
551 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
552 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
556 for pass in &config.passes {
558 diag_handler.warn(&format!("unknown pass `{}`, ignoring",
563 for pass in &cgcx.plugin_passes {
565 diag_handler.err(&format!("a plugin asked for LLVM pass \
566 `{}` but LLVM does not \
567 recognize it", pass));
572 diag_handler.abort_if_errors();
574 // Finally, run the actual optimization passes
575 time_ext(config.time_passes,
577 &format!("llvm function passes [{}]", module_name.unwrap()),
579 llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
581 timeline.record("fpm");
582 time_ext(config.time_passes,
584 &format!("llvm module passes [{}]", module_name.unwrap()),
586 llvm::LLVMRunPassManager(mpm, llmod)
589 // Deallocate managers that we're now done with
590 llvm::LLVMDisposePassManager(fpm);
591 llvm::LLVMDisposePassManager(mpm);
596 fn generate_lto_work(cgcx: &CodegenContext,
597 modules: Vec<ModuleCodegen>)
598 -> Vec<(WorkItem, u64)>
600 let mut timeline = cgcx.time_graph.as_ref().map(|tg| {
601 tg.start(CODEGEN_WORKER_TIMELINE,
602 CODEGEN_WORK_PACKAGE_KIND,
604 }).unwrap_or(Timeline::noop());
605 let lto_modules = lto::run(cgcx, modules, &mut timeline)
606 .unwrap_or_else(|e| e.raise());
608 lto_modules.into_iter().map(|module| {
609 let cost = module.cost();
610 (WorkItem::LTO(module), cost)
614 unsafe fn codegen(cgcx: &CodegenContext,
615 diag_handler: &Handler,
616 module: ModuleCodegen,
617 config: &ModuleConfig,
618 timeline: &mut Timeline)
619 -> Result<CompiledModule, FatalError>
621 timeline.record("codegen");
623 let (llmod, llcx, tm) = match module.source {
624 ModuleSource::Codegened(ref llvm) => (llvm.llmod(), &*llvm.llcx, &*llvm.tm),
625 ModuleSource::Preexisting(_) => {
626 bug!("codegen: called with ModuleSource::Preexisting")
629 let module_name = module.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<'ll, F, R>(tm: &'ll llvm::TargetMachine,
646 llmod: &'ll llvm::Module,
649 where F: FnOnce(&'ll mut PassManager<'ll>) -> 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(&module.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)
769 timeline.record("asm");
773 with_codegen(tm, llmod, config.no_builtins, |cpm| {
774 write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
775 llvm::FileType::ObjectFile)
777 timeline.record("obj");
778 } else if asm_to_obj {
779 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
780 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
781 timeline.record("asm_to_obj");
783 if !config.emit_asm && !cgcx.save_temps {
784 drop(fs::remove_file(&assembly));
792 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
793 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
794 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
799 debug!("removing_bitcode {:?}", bc_out);
800 if let Err(e) = fs::remove_file(&bc_out) {
801 diag_handler.err(&format!("failed to remove bitcode: {}", e));
807 Ok(module.into_compiled_module(config.emit_obj,
809 config.emit_bc_compressed,
810 &cgcx.output_filenames))
813 /// Embed the bitcode of an LLVM module in the LLVM module itself.
815 /// This is done primarily for iOS where it appears to be standard to compile C
816 /// code at least with `-fembed-bitcode` which creates two sections in the
819 /// * __LLVM,__bitcode
820 /// * __LLVM,__cmdline
822 /// It appears *both* of these sections are necessary to get the linker to
823 /// recognize what's going on. For us though we just always throw in an empty
826 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
827 /// embed an empty section.
829 /// Basically all of this is us attempting to follow in the footsteps of clang
830 /// on iOS. See #35968 for lots more info.
831 unsafe fn embed_bitcode(cgcx: &CodegenContext,
832 llcx: &llvm::Context,
833 llmod: &llvm::Module,
834 bitcode: Option<&[u8]>) {
835 let llconst = C_bytes_in_context(llcx, bitcode.unwrap_or(&[]));
836 let llglobal = llvm::LLVMAddGlobal(
839 "rustc.embedded.module\0".as_ptr() as *const _,
841 llvm::LLVMSetInitializer(llglobal, llconst);
843 let is_apple = cgcx.opts.target_triple.triple().contains("-ios") ||
844 cgcx.opts.target_triple.triple().contains("-darwin");
846 let section = if is_apple {
851 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
852 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
853 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
855 let llconst = C_bytes_in_context(llcx, &[]);
856 let llglobal = llvm::LLVMAddGlobal(
859 "rustc.embedded.cmdline\0".as_ptr() as *const _,
861 llvm::LLVMSetInitializer(llglobal, llconst);
862 let section = if is_apple {
867 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
868 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
871 pub(crate) struct CompiledModules {
872 pub modules: Vec<CompiledModule>,
873 pub metadata_module: CompiledModule,
874 pub allocator_module: Option<CompiledModule>,
877 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
878 sess.crate_types.borrow().contains(&config::CrateTypeRlib) &&
879 sess.opts.output_types.contains_key(&OutputType::Exe)
882 pub fn start_async_codegen(tcx: TyCtxt,
883 time_graph: Option<TimeGraph>,
885 metadata: EncodedMetadata,
886 coordinator_receive: Receiver<Box<dyn Any + Send>>,
890 let crate_name = tcx.crate_name(LOCAL_CRATE);
891 let no_builtins = attr::contains_name(&tcx.hir.krate().attrs, "no_builtins");
892 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir.krate().attrs,
893 "windows_subsystem");
894 let windows_subsystem = subsystem.map(|subsystem| {
895 if subsystem != "windows" && subsystem != "console" {
896 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
897 `windows` and `console` are allowed",
900 subsystem.to_string()
903 let linker_info = LinkerInfo::new(tcx);
904 let crate_info = CrateInfo::new(tcx);
906 // Figure out what we actually need to build.
907 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
908 let mut metadata_config = ModuleConfig::new(vec![]);
909 let mut allocator_config = ModuleConfig::new(vec![]);
911 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
913 Sanitizer::Address => {
914 modules_config.passes.push("asan".to_owned());
915 modules_config.passes.push("asan-module".to_owned());
917 Sanitizer::Memory => {
918 modules_config.passes.push("msan".to_owned())
920 Sanitizer::Thread => {
921 modules_config.passes.push("tsan".to_owned())
927 if sess.opts.debugging_opts.profile {
928 modules_config.passes.push("insert-gcov-profiling".to_owned())
931 modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
932 modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
934 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
935 modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
937 // Save all versions of the bytecode if we're saving our temporaries.
938 if sess.opts.cg.save_temps {
939 modules_config.emit_no_opt_bc = true;
940 modules_config.emit_bc = true;
941 modules_config.emit_lto_bc = true;
942 metadata_config.emit_bc = true;
943 allocator_config.emit_bc = true;
946 // Emit compressed bitcode files for the crate if we're emitting an rlib.
947 // Whenever an rlib is created, the bitcode is inserted into the archive in
948 // order to allow LTO against it.
949 if need_crate_bitcode_for_rlib(sess) {
950 modules_config.emit_bc_compressed = true;
951 allocator_config.emit_bc_compressed = true;
954 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
955 tcx.sess.target.target.options.no_integrated_as;
957 for output_type in sess.opts.output_types.keys() {
959 OutputType::Bitcode => { modules_config.emit_bc = true; }
960 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
961 OutputType::Assembly => {
962 modules_config.emit_asm = true;
963 // If we're not using the LLVM assembler, this function
964 // could be invoked specially with output_type_assembly, so
965 // in this case we still want the metadata object file.
966 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
967 metadata_config.emit_obj = true;
968 allocator_config.emit_obj = true;
971 OutputType::Object => { modules_config.emit_obj = true; }
972 OutputType::Metadata => { metadata_config.emit_obj = true; }
974 modules_config.emit_obj = true;
975 metadata_config.emit_obj = true;
976 allocator_config.emit_obj = true;
978 OutputType::Mir => {}
979 OutputType::DepInfo => {}
983 modules_config.set_flags(sess, no_builtins);
984 metadata_config.set_flags(sess, no_builtins);
985 allocator_config.set_flags(sess, no_builtins);
987 // Exclude metadata and allocator modules from time_passes output, since
988 // they throw off the "LLVM passes" measurement.
989 metadata_config.time_passes = false;
990 allocator_config.time_passes = false;
992 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
993 let (codegen_worker_send, codegen_worker_receive) = channel();
995 let coordinator_thread = start_executing_work(tcx,
1001 sess.jobserver.clone(),
1003 Arc::new(modules_config),
1004 Arc::new(metadata_config),
1005 Arc::new(allocator_config));
1016 coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
1017 codegen_worker_receive,
1018 shared_emitter_main,
1019 future: coordinator_thread,
1020 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1024 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
1026 compiled_modules: &CompiledModules
1027 ) -> FxHashMap<WorkProductId, WorkProduct> {
1028 let mut work_products = FxHashMap::default();
1030 if sess.opts.incremental.is_none() {
1031 return work_products;
1034 for module in compiled_modules.modules.iter() {
1035 let mut files = vec![];
1037 if let Some(ref path) = module.object {
1038 files.push((WorkProductFileKind::Object, path.clone()));
1040 if let Some(ref path) = module.bytecode {
1041 files.push((WorkProductFileKind::Bytecode, path.clone()));
1043 if let Some(ref path) = module.bytecode_compressed {
1044 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
1047 if let Some((id, product)) =
1048 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
1049 work_products.insert(id, product);
1056 fn produce_final_output_artifacts(sess: &Session,
1057 compiled_modules: &CompiledModules,
1058 crate_output: &OutputFilenames) {
1059 let mut user_wants_bitcode = false;
1060 let mut user_wants_objects = false;
1062 // Produce final compile outputs.
1063 let copy_gracefully = |from: &Path, to: &Path| {
1064 if let Err(e) = fs::copy(from, to) {
1065 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
1069 let copy_if_one_unit = |output_type: OutputType,
1070 keep_numbered: bool| {
1071 if compiled_modules.modules.len() == 1 {
1072 // 1) Only one codegen unit. In this case it's no difficulty
1073 // to copy `foo.0.x` to `foo.x`.
1074 let module_name = Some(&compiled_modules.modules[0].name[..]);
1075 let path = crate_output.temp_path(output_type, module_name);
1076 copy_gracefully(&path,
1077 &crate_output.path(output_type));
1078 if !sess.opts.cg.save_temps && !keep_numbered {
1079 // The user just wants `foo.x`, not `foo.#module-name#.x`.
1080 remove(sess, &path);
1083 let ext = crate_output.temp_path(output_type, None)
1090 if crate_output.outputs.contains_key(&output_type) {
1091 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
1092 // no good solution for this case, so warn the user.
1093 sess.warn(&format!("ignoring emit path because multiple .{} files \
1094 were produced", ext));
1095 } else if crate_output.single_output_file.is_some() {
1096 // 3) Multiple codegen units, with `-o some_name`. We have
1097 // no good solution for this case, so warn the user.
1098 sess.warn(&format!("ignoring -o because multiple .{} files \
1099 were produced", ext));
1101 // 4) Multiple codegen units, but no explicit name. We
1102 // just leave the `foo.0.x` files in place.
1103 // (We don't have to do any work in this case.)
1108 // Flag to indicate whether the user explicitly requested bitcode.
1109 // Otherwise, we produced it only as a temporary output, and will need
1110 // to get rid of it.
1111 for output_type in crate_output.outputs.keys() {
1112 match *output_type {
1113 OutputType::Bitcode => {
1114 user_wants_bitcode = true;
1115 // Copy to .bc, but always keep the .0.bc. There is a later
1116 // check to figure out if we should delete .0.bc files, or keep
1117 // them for making an rlib.
1118 copy_if_one_unit(OutputType::Bitcode, true);
1120 OutputType::LlvmAssembly => {
1121 copy_if_one_unit(OutputType::LlvmAssembly, false);
1123 OutputType::Assembly => {
1124 copy_if_one_unit(OutputType::Assembly, false);
1126 OutputType::Object => {
1127 user_wants_objects = true;
1128 copy_if_one_unit(OutputType::Object, true);
1131 OutputType::Metadata |
1133 OutputType::DepInfo => {}
1137 // Clean up unwanted temporary files.
1139 // We create the following files by default:
1140 // - #crate#.#module-name#.bc
1141 // - #crate#.#module-name#.o
1142 // - #crate#.crate.metadata.bc
1143 // - #crate#.crate.metadata.o
1144 // - #crate#.o (linked from crate.##.o)
1145 // - #crate#.bc (copied from crate.##.bc)
1146 // We may create additional files if requested by the user (through
1147 // `-C save-temps` or `--emit=` flags).
1149 if !sess.opts.cg.save_temps {
1150 // Remove the temporary .#module-name#.o objects. If the user didn't
1151 // explicitly request bitcode (with --emit=bc), and the bitcode is not
1152 // needed for building an rlib, then we must remove .#module-name#.bc as
1155 // Specific rules for keeping .#module-name#.bc:
1156 // - If the user requested bitcode (`user_wants_bitcode`), and
1157 // codegen_units > 1, then keep it.
1158 // - If the user requested bitcode but codegen_units == 1, then we
1159 // can toss .#module-name#.bc because we copied it to .bc earlier.
1160 // - If we're not building an rlib and the user didn't request
1161 // bitcode, then delete .#module-name#.bc.
1162 // If you change how this works, also update back::link::link_rlib,
1163 // where .#module-name#.bc files are (maybe) deleted after making an
1165 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
1167 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
1169 let keep_numbered_objects = needs_crate_object ||
1170 (user_wants_objects && sess.codegen_units() > 1);
1172 for module in compiled_modules.modules.iter() {
1173 if let Some(ref path) = module.object {
1174 if !keep_numbered_objects {
1179 if let Some(ref path) = module.bytecode {
1180 if !keep_numbered_bitcode {
1186 if !user_wants_bitcode {
1187 if let Some(ref path) = compiled_modules.metadata_module.bytecode {
1188 remove(sess, &path);
1191 if let Some(ref allocator_module) = compiled_modules.allocator_module {
1192 if let Some(ref path) = allocator_module.bytecode {
1199 // We leave the following files around by default:
1201 // - #crate#.crate.metadata.o
1203 // These are used in linking steps and will be cleaned up afterward.
1206 pub(crate) fn dump_incremental_data(codegen_results: &CodegenResults) {
1207 println!("[incremental] Re-using {} out of {} modules",
1208 codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
1209 codegen_results.modules.len());
1213 Optimize(ModuleCodegen),
1214 LTO(lto::LtoModuleCodegen),
1218 fn kind(&self) -> ModuleKind {
1220 WorkItem::Optimize(ref m) => m.kind,
1221 WorkItem::LTO(_) => ModuleKind::Regular,
1225 fn name(&self) -> String {
1227 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
1228 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
1233 enum WorkItemResult {
1234 Compiled(CompiledModule),
1235 NeedsLTO(ModuleCodegen),
1238 fn execute_work_item(cgcx: &CodegenContext,
1239 work_item: WorkItem,
1240 timeline: &mut Timeline)
1241 -> Result<WorkItemResult, FatalError>
1243 let diag_handler = cgcx.create_diag_handler();
1244 let config = cgcx.config(work_item.kind());
1245 let module = match work_item {
1246 WorkItem::Optimize(module) => module,
1247 WorkItem::LTO(mut lto) => {
1249 let module = lto.optimize(cgcx, timeline)?;
1250 let module = codegen(cgcx, &diag_handler, module, config, timeline)?;
1251 return Ok(WorkItemResult::Compiled(module))
1255 let module_name = module.name.clone();
1257 let pre_existing = match module.source {
1258 ModuleSource::Codegened(_) => None,
1259 ModuleSource::Preexisting(ref wp) => Some(wp.clone()),
1262 if let Some(wp) = pre_existing {
1263 let incr_comp_session_dir = cgcx.incr_comp_session_dir
1266 let name = &module.name;
1267 let mut object = None;
1268 let mut bytecode = None;
1269 let mut bytecode_compressed = None;
1270 for (kind, saved_file) in wp.saved_files {
1271 let obj_out = match kind {
1272 WorkProductFileKind::Object => {
1273 let path = cgcx.output_filenames.temp_path(OutputType::Object, Some(name));
1274 object = Some(path.clone());
1277 WorkProductFileKind::Bytecode => {
1278 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(name));
1279 bytecode = Some(path.clone());
1282 WorkProductFileKind::BytecodeCompressed => {
1283 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(name))
1284 .with_extension(RLIB_BYTECODE_EXTENSION);
1285 bytecode_compressed = Some(path.clone());
1289 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
1291 debug!("copying pre-existing module `{}` from {:?} to {}",
1295 match link_or_copy(&source_file, &obj_out) {
1298 diag_handler.err(&format!("unable to copy {} to {}: {}",
1299 source_file.display(),
1305 assert_eq!(object.is_some(), config.emit_obj);
1306 assert_eq!(bytecode.is_some(), config.emit_bc);
1307 assert_eq!(bytecode_compressed.is_some(), config.emit_bc_compressed);
1309 Ok(WorkItemResult::Compiled(CompiledModule {
1310 llmod_id: module.llmod_id.clone(),
1312 kind: ModuleKind::Regular,
1316 bytecode_compressed,
1319 debug!("llvm-optimizing {:?}", module_name);
1322 optimize(cgcx, &diag_handler, &module, config, timeline)?;
1324 // After we've done the initial round of optimizations we need to
1325 // decide whether to synchronously codegen this module or ship it
1326 // back to the coordinator thread for further LTO processing (which
1327 // has to wait for all the initial modules to be optimized).
1329 // Here we dispatch based on the `cgcx.lto` and kind of module we're
1331 let needs_lto = match cgcx.lto {
1334 // Here we've got a full crate graph LTO requested. We ignore
1335 // this, however, if the crate type is only an rlib as there's
1336 // no full crate graph to process, that'll happen later.
1338 // This use case currently comes up primarily for targets that
1339 // require LTO so the request for LTO is always unconditionally
1340 // passed down to the backend, but we don't actually want to do
1341 // anything about it yet until we've got a final product.
1342 Lto::Yes | Lto::Fat | Lto::Thin => {
1343 cgcx.crate_types.len() != 1 ||
1344 cgcx.crate_types[0] != config::CrateTypeRlib
1347 // When we're automatically doing ThinLTO for multi-codegen-unit
1348 // builds we don't actually want to LTO the allocator modules if
1349 // it shows up. This is due to various linker shenanigans that
1350 // we'll encounter later.
1352 // Additionally here's where we also factor in the current LLVM
1353 // version. If it doesn't support ThinLTO we skip this.
1355 module.kind != ModuleKind::Allocator &&
1356 llvm::LLVMRustThinLTOAvailable()
1360 // Metadata modules never participate in LTO regardless of the lto
1362 let needs_lto = needs_lto && module.kind != ModuleKind::Metadata;
1364 // Don't run LTO passes when cross-lang LTO is enabled. The linker
1365 // will do that for us in this case.
1366 let needs_lto = needs_lto &&
1367 !cgcx.opts.debugging_opts.cross_lang_lto.enabled();
1370 Ok(WorkItemResult::NeedsLTO(module))
1372 let module = codegen(cgcx, &diag_handler, module, config, timeline)?;
1373 Ok(WorkItemResult::Compiled(module))
1380 Token(io::Result<Acquired>),
1382 result: ModuleCodegen,
1386 result: Result<CompiledModule, ()>,
1390 llvm_work_item: WorkItem,
1399 code: Option<DiagnosticId>,
1403 #[derive(PartialEq, Clone, Copy, Debug)]
1404 enum MainThreadWorkerState {
1410 fn start_executing_work(tcx: TyCtxt,
1411 crate_info: &CrateInfo,
1412 shared_emitter: SharedEmitter,
1413 codegen_worker_send: Sender<Message>,
1414 coordinator_receive: Receiver<Box<dyn Any + Send>>,
1417 time_graph: Option<TimeGraph>,
1418 modules_config: Arc<ModuleConfig>,
1419 metadata_config: Arc<ModuleConfig>,
1420 allocator_config: Arc<ModuleConfig>)
1421 -> thread::JoinHandle<Result<CompiledModules, ()>> {
1422 let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1423 let sess = tcx.sess;
1425 // Compute the set of symbols we need to retain when doing LTO (if we need to)
1426 let exported_symbols = {
1427 let mut exported_symbols = FxHashMap();
1429 let copy_symbols = |cnum| {
1430 let symbols = tcx.exported_symbols(cnum)
1432 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1440 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1441 Some(Arc::new(exported_symbols))
1443 Lto::Yes | Lto::Fat | Lto::Thin => {
1444 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1445 for &cnum in tcx.crates().iter() {
1446 exported_symbols.insert(cnum, copy_symbols(cnum));
1448 Some(Arc::new(exported_symbols))
1453 // First up, convert our jobserver into a helper thread so we can use normal
1454 // mpsc channels to manage our messages and such.
1455 // After we've requested tokens then we'll, when we can,
1456 // get tokens on `coordinator_receive` which will
1457 // get managed in the main loop below.
1458 let coordinator_send2 = coordinator_send.clone();
1459 let helper = jobserver.into_helper_thread(move |token| {
1460 drop(coordinator_send2.send(Box::new(Message::Token(token))));
1461 }).expect("failed to spawn helper thread");
1463 let mut each_linked_rlib_for_lto = Vec::new();
1464 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1465 if link::ignored_for_lto(sess, crate_info, cnum) {
1468 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1471 let assembler_cmd = if modules_config.no_integrated_as {
1472 // HACK: currently we use linker (gcc) as our assembler
1473 let (name, mut cmd) = get_linker(sess);
1474 cmd.args(&sess.target.target.options.asm_args);
1475 Some(Arc::new(AssemblerCommand {
1483 let cgcx = CodegenContext {
1484 crate_types: sess.crate_types.borrow().clone(),
1485 each_linked_rlib_for_lto,
1487 no_landing_pads: sess.no_landing_pads(),
1488 fewer_names: sess.fewer_names(),
1489 save_temps: sess.opts.cg.save_temps,
1490 opts: Arc::new(sess.opts.clone()),
1491 time_passes: sess.time_passes(),
1493 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1494 remark: sess.opts.cg.remark.clone(),
1496 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1498 diag_emitter: shared_emitter.clone(),
1500 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1501 regular_module_config: modules_config,
1502 metadata_module_config: metadata_config,
1503 allocator_module_config: allocator_config,
1504 tm_factory: target_machine_factory(tcx.sess, false),
1506 msvc_imps_needed: msvc_imps_needed(tcx),
1507 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1508 debuginfo: tcx.sess.opts.debuginfo,
1512 // This is the "main loop" of parallel work happening for parallel codegen.
1513 // It's here that we manage parallelism, schedule work, and work with
1514 // messages coming from clients.
1516 // There are a few environmental pre-conditions that shape how the system
1519 // - Error reporting only can happen on the main thread because that's the
1520 // only place where we have access to the compiler `Session`.
1521 // - LLVM work can be done on any thread.
1522 // - Codegen can only happen on the main thread.
1523 // - Each thread doing substantial work most be in possession of a `Token`
1524 // from the `Jobserver`.
1525 // - The compiler process always holds one `Token`. Any additional `Tokens`
1526 // have to be requested from the `Jobserver`.
1530 // The error reporting restriction is handled separately from the rest: We
1531 // set up a `SharedEmitter` the holds an open channel to the main thread.
1532 // When an error occurs on any thread, the shared emitter will send the
1533 // error message to the receiver main thread (`SharedEmitterMain`). The
1534 // main thread will periodically query this error message queue and emit
1535 // any error messages it has received. It might even abort compilation if
1536 // has received a fatal error. In this case we rely on all other threads
1537 // being torn down automatically with the main thread.
1538 // Since the main thread will often be busy doing codegen work, error
1539 // reporting will be somewhat delayed, since the message queue can only be
1540 // checked in between to work packages.
1542 // Work Processing Infrastructure
1543 // ==============================
1544 // The work processing infrastructure knows three major actors:
1546 // - the coordinator thread,
1547 // - the main thread, and
1548 // - LLVM worker threads
1550 // The coordinator thread is running a message loop. It instructs the main
1551 // thread about what work to do when, and it will spawn off LLVM worker
1552 // threads as open LLVM WorkItems become available.
1554 // The job of the main thread is to codegen CGUs into LLVM work package
1555 // (since the main thread is the only thread that can do this). The main
1556 // thread will block until it receives a message from the coordinator, upon
1557 // which it will codegen one CGU, send it to the coordinator and block
1558 // again. This way the coordinator can control what the main thread is
1561 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1562 // available, it will spawn off a new LLVM worker thread and let it process
1563 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1564 // it will just shut down, which also frees all resources associated with
1565 // the given LLVM module, and sends a message to the coordinator that the
1566 // has been completed.
1570 // The scheduler's goal is to minimize the time it takes to complete all
1571 // work there is, however, we also want to keep memory consumption low
1572 // if possible. These two goals are at odds with each other: If memory
1573 // consumption were not an issue, we could just let the main thread produce
1574 // LLVM WorkItems at full speed, assuring maximal utilization of
1575 // Tokens/LLVM worker threads. However, since codegen usual is faster
1576 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1577 // WorkItem potentially holds on to a substantial amount of memory.
1579 // So the actual goal is to always produce just enough LLVM WorkItems as
1580 // not to starve our LLVM worker threads. That means, once we have enough
1581 // WorkItems in our queue, we can block the main thread, so it does not
1582 // produce more until we need them.
1584 // Doing LLVM Work on the Main Thread
1585 // ----------------------------------
1586 // Since the main thread owns the compiler processes implicit `Token`, it is
1587 // wasteful to keep it blocked without doing any work. Therefore, what we do
1588 // in this case is: We spawn off an additional LLVM worker thread that helps
1589 // reduce the queue. The work it is doing corresponds to the implicit
1590 // `Token`. The coordinator will mark the main thread as being busy with
1591 // LLVM work. (The actual work happens on another OS thread but we just care
1592 // about `Tokens`, not actual threads).
1594 // When any LLVM worker thread finishes while the main thread is marked as
1595 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1596 // of the just finished thread to the LLVM worker thread that is working on
1597 // behalf of the main thread's implicit Token, thus freeing up the main
1598 // thread again. The coordinator can then again decide what the main thread
1599 // should do. This allows the coordinator to make decisions at more points
1602 // Striking a Balance between Throughput and Memory Consumption
1603 // ------------------------------------------------------------
1604 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1605 // memory consumption as low as possible, are in conflict with each other,
1606 // we have to find a trade off between them. Right now, the goal is to keep
1607 // all workers busy, which means that no worker should find the queue empty
1608 // when it is ready to start.
1609 // How do we do achieve this? Good question :) We actually never know how
1610 // many `Tokens` are potentially available so it's hard to say how much to
1611 // fill up the queue before switching the main thread to LLVM work. Also we
1612 // currently don't have a means to estimate how long a running LLVM worker
1613 // will still be busy with it's current WorkItem. However, we know the
1614 // maximal count of available Tokens that makes sense (=the number of CPU
1615 // cores), so we can take a conservative guess. The heuristic we use here
1616 // is implemented in the `queue_full_enough()` function.
1618 // Some Background on Jobservers
1619 // -----------------------------
1620 // It's worth also touching on the management of parallelism here. We don't
1621 // want to just spawn a thread per work item because while that's optimal
1622 // parallelism it may overload a system with too many threads or violate our
1623 // configuration for the maximum amount of cpu to use for this process. To
1624 // manage this we use the `jobserver` crate.
1626 // Job servers are an artifact of GNU make and are used to manage
1627 // parallelism between processes. A jobserver is a glorified IPC semaphore
1628 // basically. Whenever we want to run some work we acquire the semaphore,
1629 // and whenever we're done with that work we release the semaphore. In this
1630 // manner we can ensure that the maximum number of parallel workers is
1631 // capped at any one point in time.
1633 // LTO and the coordinator thread
1634 // ------------------------------
1636 // The final job the coordinator thread is responsible for is managing LTO
1637 // and how that works. When LTO is requested what we'll to is collect all
1638 // optimized LLVM modules into a local vector on the coordinator. Once all
1639 // modules have been codegened and optimized we hand this to the `lto`
1640 // module for further optimization. The `lto` module will return back a list
1641 // of more modules to work on, which the coordinator will continue to spawn
1644 // Each LLVM module is automatically sent back to the coordinator for LTO if
1645 // necessary. There's already optimizations in place to avoid sending work
1646 // back to the coordinator if LTO isn't requested.
1647 return thread::spawn(move || {
1648 // We pretend to be within the top-level LLVM time-passes task here:
1651 let max_workers = ::num_cpus::get();
1652 let mut worker_id_counter = 0;
1653 let mut free_worker_ids = Vec::new();
1654 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1655 if let Some(id) = free_worker_ids.pop() {
1658 let id = worker_id_counter;
1659 worker_id_counter += 1;
1664 // This is where we collect codegen units that have gone all the way
1665 // through codegen and LLVM.
1666 let mut compiled_modules = vec![];
1667 let mut compiled_metadata_module = None;
1668 let mut compiled_allocator_module = None;
1669 let mut needs_lto = Vec::new();
1670 let mut started_lto = false;
1672 // This flag tracks whether all items have gone through codegens
1673 let mut codegen_done = false;
1675 // This is the queue of LLVM work items that still need processing.
1676 let mut work_items = Vec::<(WorkItem, u64)>::new();
1678 // This are the Jobserver Tokens we currently hold. Does not include
1679 // the implicit Token the compiler process owns no matter what.
1680 let mut tokens = Vec::new();
1682 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1683 let mut running = 0;
1685 let mut llvm_start_time = None;
1687 // Run the message loop while there's still anything that needs message
1689 while !codegen_done ||
1690 work_items.len() > 0 ||
1692 needs_lto.len() > 0 ||
1693 main_thread_worker_state != MainThreadWorkerState::Idle {
1695 // While there are still CGUs to be codegened, the coordinator has
1696 // to decide how to utilize the compiler processes implicit Token:
1697 // For codegenning more CGU or for running them through LLVM.
1699 if main_thread_worker_state == MainThreadWorkerState::Idle {
1700 if !queue_full_enough(work_items.len(), running, max_workers) {
1701 // The queue is not full enough, codegen more items:
1702 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1703 panic!("Could not send Message::CodegenItem to main thread")
1705 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1707 // The queue is full enough to not let the worker
1708 // threads starve. Use the implicit Token to do some
1710 let (item, _) = work_items.pop()
1711 .expect("queue empty - queue_full_enough() broken?");
1712 let cgcx = CodegenContext {
1713 worker: get_worker_id(&mut free_worker_ids),
1716 maybe_start_llvm_timer(cgcx.config(item.kind()),
1717 &mut llvm_start_time);
1718 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1719 spawn_work(cgcx, item);
1723 // If we've finished everything related to normal codegen
1724 // then it must be the case that we've got some LTO work to do.
1725 // Perform the serial work here of figuring out what we're
1726 // going to LTO and then push a bunch of work items onto our
1728 if work_items.len() == 0 &&
1730 main_thread_worker_state == MainThreadWorkerState::Idle {
1731 assert!(!started_lto);
1732 assert!(needs_lto.len() > 0);
1734 let modules = mem::replace(&mut needs_lto, Vec::new());
1735 for (work, cost) in generate_lto_work(&cgcx, modules) {
1736 let insertion_index = work_items
1737 .binary_search_by_key(&cost, |&(_, cost)| cost)
1738 .unwrap_or_else(|e| e);
1739 work_items.insert(insertion_index, (work, cost));
1740 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1741 helper.request_token();
1746 // In this branch, we know that everything has been codegened,
1747 // so it's just a matter of determining whether the implicit
1748 // Token is free to use for LLVM work.
1749 match main_thread_worker_state {
1750 MainThreadWorkerState::Idle => {
1751 if let Some((item, _)) = work_items.pop() {
1752 let cgcx = CodegenContext {
1753 worker: get_worker_id(&mut free_worker_ids),
1756 maybe_start_llvm_timer(cgcx.config(item.kind()),
1757 &mut llvm_start_time);
1758 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1759 spawn_work(cgcx, item);
1761 // There is no unstarted work, so let the main thread
1762 // take over for a running worker. Otherwise the
1763 // implicit token would just go to waste.
1764 // We reduce the `running` counter by one. The
1765 // `tokens.truncate()` below will take care of
1766 // giving the Token back.
1767 debug_assert!(running > 0);
1769 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1772 MainThreadWorkerState::Codegenning => {
1773 bug!("codegen worker should not be codegenning after \
1774 codegen was already completed")
1776 MainThreadWorkerState::LLVMing => {
1777 // Already making good use of that token
1782 // Spin up what work we can, only doing this while we've got available
1783 // parallelism slots and work left to spawn.
1784 while work_items.len() > 0 && running < tokens.len() {
1785 let (item, _) = work_items.pop().unwrap();
1787 maybe_start_llvm_timer(cgcx.config(item.kind()),
1788 &mut llvm_start_time);
1790 let cgcx = CodegenContext {
1791 worker: get_worker_id(&mut free_worker_ids),
1795 spawn_work(cgcx, item);
1799 // Relinquish accidentally acquired extra tokens
1800 tokens.truncate(running);
1802 let msg = coordinator_receive.recv().unwrap();
1803 match *msg.downcast::<Message>().ok().unwrap() {
1804 // Save the token locally and the next turn of the loop will use
1805 // this to spawn a new unit of work, or it may get dropped
1806 // immediately if we have no more work to spawn.
1807 Message::Token(token) => {
1812 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1813 // If the main thread token is used for LLVM work
1814 // at the moment, we turn that thread into a regular
1815 // LLVM worker thread, so the main thread is free
1816 // to react to codegen demand.
1817 main_thread_worker_state = MainThreadWorkerState::Idle;
1822 let msg = &format!("failed to acquire jobserver token: {}", e);
1823 shared_emitter.fatal(msg);
1824 // Exit the coordinator thread
1830 Message::CodegenDone { llvm_work_item, cost } => {
1831 // We keep the queue sorted by estimated processing cost,
1832 // so that more expensive items are processed earlier. This
1833 // is good for throughput as it gives the main thread more
1834 // time to fill up the queue and it avoids scheduling
1835 // expensive items to the end.
1836 // Note, however, that this is not ideal for memory
1837 // consumption, as LLVM module sizes are not evenly
1839 let insertion_index =
1840 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1841 let insertion_index = match insertion_index {
1842 Ok(idx) | Err(idx) => idx
1844 work_items.insert(insertion_index, (llvm_work_item, cost));
1846 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1847 helper.request_token();
1849 assert_eq!(main_thread_worker_state,
1850 MainThreadWorkerState::Codegenning);
1851 main_thread_worker_state = MainThreadWorkerState::Idle;
1854 Message::CodegenComplete => {
1855 codegen_done = true;
1856 assert_eq!(main_thread_worker_state,
1857 MainThreadWorkerState::Codegenning);
1858 main_thread_worker_state = MainThreadWorkerState::Idle;
1861 // If a thread exits successfully then we drop a token associated
1862 // with that worker and update our `running` count. We may later
1863 // re-acquire a token to continue running more work. We may also not
1864 // actually drop a token here if the worker was running with an
1865 // "ephemeral token"
1867 // Note that if the thread failed that means it panicked, so we
1868 // abort immediately.
1869 Message::Done { result: Ok(compiled_module), worker_id } => {
1870 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1871 main_thread_worker_state = MainThreadWorkerState::Idle;
1876 free_worker_ids.push(worker_id);
1878 match compiled_module.kind {
1879 ModuleKind::Regular => {
1880 compiled_modules.push(compiled_module);
1882 ModuleKind::Metadata => {
1883 assert!(compiled_metadata_module.is_none());
1884 compiled_metadata_module = Some(compiled_module);
1886 ModuleKind::Allocator => {
1887 assert!(compiled_allocator_module.is_none());
1888 compiled_allocator_module = Some(compiled_module);
1892 Message::NeedsLTO { result, worker_id } => {
1893 assert!(!started_lto);
1894 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1895 main_thread_worker_state = MainThreadWorkerState::Idle;
1900 free_worker_ids.push(worker_id);
1901 needs_lto.push(result);
1903 Message::Done { result: Err(()), worker_id: _ } => {
1904 shared_emitter.fatal("aborting due to worker thread failure");
1905 // Exit the coordinator thread
1908 Message::CodegenItem => {
1909 bug!("the coordinator should not receive codegen requests")
1914 if let Some(llvm_start_time) = llvm_start_time {
1915 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
1916 // This is the top-level timing for all of LLVM, set the time-depth
1919 print_time_passes_entry(cgcx.time_passes,
1924 // Regardless of what order these modules completed in, report them to
1925 // the backend in the same order every time to ensure that we're handing
1926 // out deterministic results.
1927 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1929 let compiled_metadata_module = compiled_metadata_module
1930 .expect("Metadata module not compiled?");
1932 Ok(CompiledModules {
1933 modules: compiled_modules,
1934 metadata_module: compiled_metadata_module,
1935 allocator_module: compiled_allocator_module,
1939 // A heuristic that determines if we have enough LLVM WorkItems in the
1940 // queue so that the main thread can do LLVM work instead of codegen
1941 fn queue_full_enough(items_in_queue: usize,
1942 workers_running: usize,
1943 max_workers: usize) -> bool {
1945 items_in_queue > 0 &&
1946 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1949 fn maybe_start_llvm_timer(config: &ModuleConfig,
1950 llvm_start_time: &mut Option<Instant>) {
1951 // We keep track of the -Ztime-passes output manually,
1952 // since the closure-based interface does not fit well here.
1953 if config.time_passes {
1954 if llvm_start_time.is_none() {
1955 *llvm_start_time = Some(Instant::now());
1961 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1962 pub const CODEGEN_WORKER_TIMELINE: time_graph::TimelineId =
1963 time_graph::TimelineId(CODEGEN_WORKER_ID);
1964 pub const CODEGEN_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1965 time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
1966 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1967 time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
1969 fn spawn_work(cgcx: CodegenContext, work: WorkItem) {
1970 let depth = time_depth();
1972 thread::spawn(move || {
1973 set_time_depth(depth);
1975 // Set up a destructor which will fire off a message that we're done as
1978 coordinator_send: Sender<Box<dyn Any + Send>>,
1979 result: Option<WorkItemResult>,
1982 impl Drop for Bomb {
1983 fn drop(&mut self) {
1984 let worker_id = self.worker_id;
1985 let msg = match self.result.take() {
1986 Some(WorkItemResult::Compiled(m)) => {
1987 Message::Done { result: Ok(m), worker_id }
1989 Some(WorkItemResult::NeedsLTO(m)) => {
1990 Message::NeedsLTO { result: m, worker_id }
1992 None => Message::Done { result: Err(()), worker_id }
1994 drop(self.coordinator_send.send(Box::new(msg)));
1998 let mut bomb = Bomb {
1999 coordinator_send: cgcx.coordinator_send.clone(),
2001 worker_id: cgcx.worker,
2004 // Execute the work itself, and if it finishes successfully then flag
2005 // ourselves as a success as well.
2007 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
2008 // as a diagnostic was already sent off to the main thread - just
2009 // surface that there was an error in this worker.
2011 let timeline = cgcx.time_graph.as_ref().map(|tg| {
2012 tg.start(time_graph::TimelineId(cgcx.worker),
2013 LLVM_WORK_PACKAGE_KIND,
2016 let mut timeline = timeline.unwrap_or(Timeline::noop());
2017 execute_work_item(&cgcx, work, &mut timeline).ok()
2022 pub fn run_assembler(cgcx: &CodegenContext, handler: &Handler, assembly: &Path, object: &Path) {
2023 let assembler = cgcx.assembler_cmd
2025 .expect("cgcx.assembler_cmd is missing?");
2027 let pname = &assembler.name;
2028 let mut cmd = assembler.cmd.clone();
2029 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
2030 debug!("{:?}", cmd);
2032 match cmd.output() {
2034 if !prog.status.success() {
2035 let mut note = prog.stderr.clone();
2036 note.extend_from_slice(&prog.stdout);
2038 handler.struct_err(&format!("linking with `{}` failed: {}",
2041 .note(&format!("{:?}", &cmd))
2042 .note(str::from_utf8(¬e[..]).unwrap())
2044 handler.abort_if_errors();
2048 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
2049 handler.abort_if_errors();
2054 pub unsafe fn with_llvm_pmb(llmod: &llvm::Module,
2055 config: &ModuleConfig,
2056 opt_level: llvm::CodeGenOptLevel,
2057 prepare_for_thin_lto: bool,
2058 f: &mut dyn FnMut(&llvm::PassManagerBuilder)) {
2061 // Create the PassManagerBuilder for LLVM. We configure it with
2062 // reasonable defaults and prepare it to actually populate the pass
2064 let builder = llvm::LLVMPassManagerBuilderCreate();
2065 let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
2066 let inline_threshold = config.inline_threshold;
2068 let pgo_gen_path = config.pgo_gen.as_ref().map(|s| {
2069 let s = if s.is_empty() { "default_%m.profraw" } else { s };
2070 CString::new(s.as_bytes()).unwrap()
2073 let pgo_use_path = if config.pgo_use.is_empty() {
2076 Some(CString::new(config.pgo_use.as_bytes()).unwrap())
2079 llvm::LLVMRustConfigurePassManagerBuilder(
2082 config.merge_functions,
2083 config.vectorize_slp,
2084 config.vectorize_loop,
2085 prepare_for_thin_lto,
2086 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2087 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2090 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
2092 if opt_size != llvm::CodeGenOptSizeNone {
2093 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
2096 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
2098 // Here we match what clang does (kinda). For O0 we only inline
2099 // always-inline functions (but don't add lifetime intrinsics), at O1 we
2100 // inline with lifetime intrinsics, and O2+ we add an inliner with a
2101 // thresholds copied from clang.
2102 match (opt_level, opt_size, inline_threshold) {
2104 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
2106 (llvm::CodeGenOptLevel::Aggressive, ..) => {
2107 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
2109 (_, llvm::CodeGenOptSizeDefault, _) => {
2110 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
2112 (_, llvm::CodeGenOptSizeAggressive, _) => {
2113 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
2115 (llvm::CodeGenOptLevel::None, ..) => {
2116 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
2118 (llvm::CodeGenOptLevel::Less, ..) => {
2119 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
2121 (llvm::CodeGenOptLevel::Default, ..) => {
2122 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
2124 (llvm::CodeGenOptLevel::Other, ..) => {
2125 bug!("CodeGenOptLevel::Other selected")
2130 llvm::LLVMPassManagerBuilderDispose(builder);
2134 enum SharedEmitterMessage {
2135 Diagnostic(Diagnostic),
2136 InlineAsmError(u32, String),
2142 pub struct SharedEmitter {
2143 sender: Sender<SharedEmitterMessage>,
2146 pub struct SharedEmitterMain {
2147 receiver: Receiver<SharedEmitterMessage>,
2150 impl SharedEmitter {
2151 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
2152 let (sender, receiver) = channel();
2154 (SharedEmitter { sender }, SharedEmitterMain { receiver })
2157 fn inline_asm_error(&self, cookie: u32, msg: String) {
2158 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
2161 fn fatal(&self, msg: &str) {
2162 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2166 impl Emitter for SharedEmitter {
2167 fn emit(&mut self, db: &DiagnosticBuilder) {
2168 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2170 code: db.code.clone(),
2173 for child in &db.children {
2174 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2175 msg: child.message(),
2180 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
2184 impl SharedEmitterMain {
2185 pub fn check(&self, sess: &Session, blocking: bool) {
2187 let message = if blocking {
2188 match self.receiver.recv() {
2189 Ok(message) => Ok(message),
2193 match self.receiver.try_recv() {
2194 Ok(message) => Ok(message),
2200 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2201 let handler = sess.diagnostic();
2204 handler.emit_with_code(&MultiSpan::new(),
2210 handler.emit(&MultiSpan::new(),
2216 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
2217 match Mark::from_u32(cookie).expn_info() {
2218 Some(ei) => sess.span_err(ei.call_site, &msg),
2219 None => sess.err(&msg),
2222 Ok(SharedEmitterMessage::AbortIfErrors) => {
2223 sess.abort_if_errors();
2225 Ok(SharedEmitterMessage::Fatal(msg)) => {
2237 pub struct OngoingCodegen {
2240 metadata: EncodedMetadata,
2241 windows_subsystem: Option<String>,
2242 linker_info: LinkerInfo,
2243 crate_info: CrateInfo,
2244 time_graph: Option<TimeGraph>,
2245 coordinator_send: Sender<Box<dyn Any + Send>>,
2246 codegen_worker_receive: Receiver<Message>,
2247 shared_emitter_main: SharedEmitterMain,
2248 future: thread::JoinHandle<Result<CompiledModules, ()>>,
2249 output_filenames: Arc<OutputFilenames>,
2252 impl OngoingCodegen {
2256 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
2257 self.shared_emitter_main.check(sess, true);
2258 let compiled_modules = match self.future.join() {
2259 Ok(Ok(compiled_modules)) => compiled_modules,
2261 sess.abort_if_errors();
2262 panic!("expected abort due to worker thread errors")
2265 sess.fatal("Error during codegen/LLVM phase.");
2269 sess.abort_if_errors();
2271 if let Some(time_graph) = self.time_graph {
2272 time_graph.dump(&format!("{}-timings", self.crate_name));
2275 let work_products = copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
2278 produce_final_output_artifacts(sess,
2280 &self.output_filenames);
2282 // FIXME: time_llvm_passes support - does this use a global context or
2284 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
2285 unsafe { llvm::LLVMRustPrintPassTimings(); }
2289 crate_name: self.crate_name,
2291 metadata: self.metadata,
2292 windows_subsystem: self.windows_subsystem,
2293 linker_info: self.linker_info,
2294 crate_info: self.crate_info,
2296 modules: compiled_modules.modules,
2297 allocator_module: compiled_modules.allocator_module,
2298 metadata_module: compiled_modules.metadata_module,
2302 pub(crate) fn submit_pre_codegened_module_to_llvm(&self,
2304 module: ModuleCodegen) {
2305 self.wait_for_signal_to_codegen_item();
2306 self.check_for_errors(tcx.sess);
2308 // These are generally cheap and won't through off scheduling.
2310 submit_codegened_module_to_llvm(tcx, module, cost);
2313 pub fn codegen_finished(&self, tcx: TyCtxt) {
2314 self.wait_for_signal_to_codegen_item();
2315 self.check_for_errors(tcx.sess);
2316 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete)));
2319 pub fn check_for_errors(&self, sess: &Session) {
2320 self.shared_emitter_main.check(sess, false);
2323 pub fn wait_for_signal_to_codegen_item(&self) {
2324 match self.codegen_worker_receive.recv() {
2325 Ok(Message::CodegenItem) => {
2328 Ok(_) => panic!("unexpected message"),
2330 // One of the LLVM threads must have panicked, fall through so
2331 // error handling can be reached.
2337 pub(crate) fn submit_codegened_module_to_llvm(tcx: TyCtxt,
2338 module: ModuleCodegen,
2340 let llvm_work_item = WorkItem::Optimize(module);
2341 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2347 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
2348 tcx.sess.target.target.options.is_like_msvc &&
2349 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib)
2352 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2353 // This is required to satisfy `dllimport` references to static data in .rlibs
2354 // when using MSVC linker. We do this only for data, as linker can fix up
2355 // code references on its own.
2356 // See #26591, #27438
2357 fn create_msvc_imps(cgcx: &CodegenContext, llcx: &llvm::Context, llmod: &llvm::Module) {
2358 if !cgcx.msvc_imps_needed {
2361 // The x86 ABI seems to require that leading underscores are added to symbol
2362 // names, so we need an extra underscore on 32-bit. There's also a leading
2363 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2364 // underscores added in front).
2365 let prefix = if cgcx.target_pointer_width == "32" {
2371 let i8p_ty = Type::i8p_llcx(llcx);
2372 let globals = base::iter_globals(llmod)
2374 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
2375 llvm::LLVMIsDeclaration(val) == 0
2378 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2379 let mut imp_name = prefix.as_bytes().to_vec();
2380 imp_name.extend(name.to_bytes());
2381 let imp_name = CString::new(imp_name).unwrap();
2384 .collect::<Vec<_>>();
2385 for (imp_name, val) in globals {
2386 let imp = llvm::LLVMAddGlobal(llmod,
2388 imp_name.as_ptr() as *const _);
2389 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
2390 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);