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};
29 use llvm::{ModuleRef, TargetMachineRef, PassManagerRef, DiagnosticInfoRef};
30 use llvm::{SMDiagnosticRef, ContextRef};
31 use {CodegenResults, ModuleSource, ModuleCodegen, 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<dyn 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 = sess.target_cpu();
178 let cpu = CString::new(cpu.as_bytes()).unwrap();
179 let features = attributes::llvm_target_features(sess)
182 let features = CString::new(features).unwrap();
183 let is_pie_binary = !find_features && is_pie_binary(sess);
184 let trap_unreachable = sess.target.target.options.trap_unreachable;
188 llvm::LLVMRustCreateTargetMachine(
189 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
203 Err(format!("Could not create LLVM TargetMachine for triple: {}",
204 triple.to_str().unwrap()))
211 /// Module-specific configuration for `optimize_and_codegen`.
212 pub struct ModuleConfig {
213 /// Names of additional optimization passes to run.
215 /// Some(level) to optimize at a certain level, or None to run
216 /// absolutely no optimizations (used for the metadata module).
217 pub opt_level: Option<llvm::CodeGenOptLevel>,
219 /// Some(level) to optimize binary size, or None to not affect program size.
220 opt_size: Option<llvm::CodeGenOptSize>,
222 pgo_gen: Option<String>,
225 // Flags indicating which outputs to produce.
226 emit_no_opt_bc: bool,
228 emit_bc_compressed: bool,
233 // Miscellaneous flags. These are mostly copied from command-line
235 pub verify_llvm_ir: bool,
236 no_prepopulate_passes: bool,
239 vectorize_loop: bool,
241 merge_functions: bool,
242 inline_threshold: Option<usize>,
243 // Instead of creating an object file by doing LLVM codegen, just
244 // make the object file bitcode. Provides easy compatibility with
245 // emscripten's ecc compiler, when used as the linker.
246 obj_is_bitcode: bool,
247 no_integrated_as: bool,
249 embed_bitcode_marker: bool,
253 fn new(passes: Vec<String>) -> ModuleConfig {
260 pgo_use: String::new(),
262 emit_no_opt_bc: false,
264 emit_bc_compressed: false,
269 obj_is_bitcode: false,
270 embed_bitcode: false,
271 embed_bitcode_marker: false,
272 no_integrated_as: false,
274 verify_llvm_ir: false,
275 no_prepopulate_passes: false,
278 vectorize_loop: false,
279 vectorize_slp: false,
280 merge_functions: false,
281 inline_threshold: None
285 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
286 self.verify_llvm_ir = sess.verify_llvm_ir();
287 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
288 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
289 self.time_passes = sess.time_passes();
290 self.inline_threshold = sess.opts.cg.inline_threshold;
291 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
292 sess.opts.debugging_opts.cross_lang_lto.enabled();
293 let embed_bitcode = sess.target.target.options.embed_bitcode ||
294 sess.opts.debugging_opts.embed_bitcode;
296 match sess.opts.optimize {
297 config::OptLevel::No |
298 config::OptLevel::Less => {
299 self.embed_bitcode_marker = embed_bitcode;
301 _ => self.embed_bitcode = embed_bitcode,
305 // Copy what clang does by turning on loop vectorization at O2 and
306 // slp vectorization at O3. Otherwise configure other optimization aspects
307 // of this pass manager builder.
308 // Turn off vectorization for emscripten, as it's not very well supported.
309 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
310 (sess.opts.optimize == config::OptLevel::Default ||
311 sess.opts.optimize == config::OptLevel::Aggressive) &&
312 !sess.target.target.options.is_like_emscripten;
314 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
315 sess.opts.optimize == config::OptLevel::Aggressive &&
316 !sess.target.target.options.is_like_emscripten;
318 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
319 sess.opts.optimize == config::OptLevel::Aggressive;
323 /// Assembler name and command used by codegen when no_integrated_as is enabled
324 struct AssemblerCommand {
329 /// Additional resources used by optimize_and_codegen (not module specific)
331 pub struct CodegenContext {
332 // Resouces needed when running LTO
333 pub time_passes: bool,
335 pub no_landing_pads: bool,
336 pub save_temps: bool,
337 pub fewer_names: bool,
338 pub exported_symbols: Option<Arc<ExportedSymbols>>,
339 pub opts: Arc<config::Options>,
340 pub crate_types: Vec<config::CrateType>,
341 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
342 output_filenames: Arc<OutputFilenames>,
343 regular_module_config: Arc<ModuleConfig>,
344 metadata_module_config: Arc<ModuleConfig>,
345 allocator_module_config: Arc<ModuleConfig>,
346 pub tm_factory: Arc<dyn Fn() -> Result<TargetMachineRef, String> + Send + Sync>,
347 pub msvc_imps_needed: bool,
348 pub target_pointer_width: String,
349 debuginfo: config::DebugInfoLevel,
351 // Number of cgus excluding the allocator/metadata modules
352 pub total_cgus: usize,
353 // Handler to use for diagnostics produced during codegen.
354 pub diag_emitter: SharedEmitter,
355 // LLVM passes added by plugins.
356 pub plugin_passes: Vec<String>,
357 // LLVM optimizations for which we want to print remarks.
359 // Worker thread number
361 // The incremental compilation session directory, or None if we are not
362 // compiling incrementally
363 pub incr_comp_session_dir: Option<PathBuf>,
364 // Channel back to the main control thread to send messages to
365 coordinator_send: Sender<Box<dyn Any + Send>>,
366 // A reference to the TimeGraph so we can register timings. None means that
367 // measuring is disabled.
368 time_graph: Option<TimeGraph>,
369 // The assembler command if no_integrated_as option is enabled, None otherwise
370 assembler_cmd: Option<Arc<AssemblerCommand>>,
373 impl CodegenContext {
374 pub fn create_diag_handler(&self) -> Handler {
375 Handler::with_emitter(true, false, Box::new(self.diag_emitter.clone()))
378 pub(crate) fn config(&self, kind: ModuleKind) -> &ModuleConfig {
380 ModuleKind::Regular => &self.regular_module_config,
381 ModuleKind::Metadata => &self.metadata_module_config,
382 ModuleKind::Allocator => &self.allocator_module_config,
386 pub(crate) fn save_temp_bitcode(&self, module: &ModuleCodegen, name: &str) {
387 if !self.save_temps {
391 let ext = format!("{}.bc", name);
392 let cgu = Some(&module.name[..]);
393 let path = self.output_filenames.temp_path_ext(&ext, cgu);
394 let cstr = path2cstr(&path);
395 let llmod = module.llvm().unwrap().llmod;
396 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
401 struct DiagnosticHandlers<'a> {
403 // This value is not actually dead, llcx has pointers to it and needs these pointers to be alive
404 // until Drop is executed on this object
405 inner: Box<(&'a CodegenContext, &'a Handler)>,
409 impl<'a> DiagnosticHandlers<'a> {
410 fn new(cgcx: &'a CodegenContext,
411 handler: &'a Handler,
412 llcx: ContextRef) -> DiagnosticHandlers<'a> {
413 let data = Box::new((cgcx, handler));
415 let arg = &*data as &(_, _) as *const _ as *mut _;
416 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, arg);
417 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, arg);
426 impl<'a> Drop for DiagnosticHandlers<'a> {
429 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, 0 as *mut _);
430 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, 0 as *mut _);
435 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext,
438 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_string());
441 unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
447 let (cgcx, _) = *(user as *const (&CodegenContext, &Handler));
449 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
450 .expect("non-UTF8 SMDiagnostic");
452 report_inline_asm(cgcx, &msg, cookie);
455 unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
459 let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler));
461 match llvm::diagnostic::Diagnostic::unpack(info) {
462 llvm::diagnostic::InlineAsm(inline) => {
463 report_inline_asm(cgcx,
464 &llvm::twine_to_string(inline.message),
468 llvm::diagnostic::Optimization(opt) => {
469 let enabled = match cgcx.remark {
471 SomePasses(ref v) => v.iter().any(|s| *s == opt.pass_name),
475 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
484 llvm::diagnostic::PGO(diagnostic_ref) => {
485 let msg = llvm::build_string(|s| {
486 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
487 }).expect("non-UTF8 PGO diagnostic");
488 diag_handler.warn(&msg);
490 llvm::diagnostic::UnknownDiagnostic(..) => {},
494 // Unsafe due to LLVM calls.
495 unsafe fn optimize(cgcx: &CodegenContext,
496 diag_handler: &Handler,
497 module: &ModuleCodegen,
498 config: &ModuleConfig,
499 timeline: &mut Timeline)
500 -> Result<(), FatalError>
502 let (llmod, llcx, tm) = match module.source {
503 ModuleSource::Codegened(ref llvm) => (llvm.llmod, llvm.llcx, llvm.tm),
504 ModuleSource::Preexisting(_) => {
505 bug!("optimize_and_codegen: called with ModuleSource::Preexisting")
509 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
511 let module_name = module.name.clone();
512 let module_name = Some(&module_name[..]);
514 if config.emit_no_opt_bc {
515 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
516 let out = path2cstr(&out);
517 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
520 if config.opt_level.is_some() {
521 // Create the two optimizing pass managers. These mirror what clang
522 // does, and are by populated by LLVM's default PassManagerBuilder.
523 // Each manager has a different set of passes, but they also share
524 // some common passes.
525 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
526 let mpm = llvm::LLVMCreatePassManager();
528 // If we're verifying or linting, add them to the function pass
530 let addpass = |pass_name: &str| {
531 let pass_name = CString::new(pass_name).unwrap();
532 let pass = llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr());
536 let pass_manager = match llvm::LLVMRustPassKind(pass) {
537 llvm::PassKind::Function => fpm,
538 llvm::PassKind::Module => mpm,
539 llvm::PassKind::Other => {
540 diag_handler.err("Encountered LLVM pass kind we can't handle");
544 llvm::LLVMRustAddPass(pass_manager, pass);
548 if config.verify_llvm_ir { assert!(addpass("verify")); }
549 if !config.no_prepopulate_passes {
550 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
551 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
552 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
553 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal;
554 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
555 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
556 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
560 for pass in &config.passes {
562 diag_handler.warn(&format!("unknown pass `{}`, ignoring",
567 for pass in &cgcx.plugin_passes {
569 diag_handler.err(&format!("a plugin asked for LLVM pass \
570 `{}` but LLVM does not \
571 recognize it", pass));
575 diag_handler.abort_if_errors();
577 // Finally, run the actual optimization passes
578 time_ext(config.time_passes,
580 &format!("llvm function passes [{}]", module_name.unwrap()),
582 llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
584 timeline.record("fpm");
585 time_ext(config.time_passes,
587 &format!("llvm module passes [{}]", module_name.unwrap()),
589 llvm::LLVMRunPassManager(mpm, llmod)
592 // Deallocate managers that we're now done with
593 llvm::LLVMDisposePassManager(fpm);
594 llvm::LLVMDisposePassManager(mpm);
599 fn generate_lto_work(cgcx: &CodegenContext,
600 modules: Vec<ModuleCodegen>)
601 -> Vec<(WorkItem, u64)>
603 let mut timeline = cgcx.time_graph.as_ref().map(|tg| {
604 tg.start(CODEGEN_WORKER_TIMELINE,
605 CODEGEN_WORK_PACKAGE_KIND,
607 }).unwrap_or(Timeline::noop());
608 let lto_modules = lto::run(cgcx, modules, &mut timeline)
609 .unwrap_or_else(|e| e.raise());
611 lto_modules.into_iter().map(|module| {
612 let cost = module.cost();
613 (WorkItem::LTO(module), cost)
617 unsafe fn codegen(cgcx: &CodegenContext,
618 diag_handler: &Handler,
619 module: ModuleCodegen,
620 config: &ModuleConfig,
621 timeline: &mut Timeline)
622 -> Result<CompiledModule, FatalError>
624 timeline.record("codegen");
625 let (llmod, llcx, tm) = match module.source {
626 ModuleSource::Codegened(ref llvm) => (llvm.llmod, llvm.llcx, llvm.tm),
627 ModuleSource::Preexisting(_) => {
628 bug!("codegen: called with ModuleSource::Preexisting")
631 let module_name = module.name.clone();
632 let module_name = Some(&module_name[..]);
633 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
635 if cgcx.msvc_imps_needed {
636 create_msvc_imps(cgcx, llcx, llmod);
639 // A codegen-specific pass manager is used to generate object
640 // files for an LLVM module.
642 // Apparently each of these pass managers is a one-shot kind of
643 // thing, so we create a new one for each type of output. The
644 // pass manager passed to the closure should be ensured to not
645 // escape the closure itself, and the manager should only be
647 unsafe fn with_codegen<F, R>(tm: TargetMachineRef,
651 where F: FnOnce(PassManagerRef) -> R,
653 let cpm = llvm::LLVMCreatePassManager();
654 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
655 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
659 // If we don't have the integrated assembler, then we need to emit asm
660 // from LLVM and use `gcc` to create the object file.
661 let asm_to_obj = config.emit_obj && config.no_integrated_as;
663 // Change what we write and cleanup based on whether obj files are
664 // just llvm bitcode. In that case write bitcode, and possibly
665 // delete the bitcode if it wasn't requested. Don't generate the
666 // machine code, instead copy the .o file from the .bc
667 let write_bc = config.emit_bc || config.obj_is_bitcode;
668 let rm_bc = !config.emit_bc && config.obj_is_bitcode;
669 let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
670 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
672 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
673 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
676 if write_bc || config.emit_bc_compressed || config.embed_bitcode {
679 let data = if llvm::LLVMRustThinLTOAvailable() {
680 thin = ThinBuffer::new(llmod);
683 old = ModuleBuffer::new(llmod);
686 timeline.record("make-bc");
689 if let Err(e) = fs::write(&bc_out, data) {
690 diag_handler.err(&format!("failed to write bytecode: {}", e));
692 timeline.record("write-bc");
695 if config.embed_bitcode {
696 embed_bitcode(cgcx, llcx, llmod, Some(data));
697 timeline.record("embed-bc");
700 if config.emit_bc_compressed {
701 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
702 let data = bytecode::encode(&module.llmod_id, data);
703 if let Err(e) = fs::write(&dst, data) {
704 diag_handler.err(&format!("failed to write bytecode: {}", e));
706 timeline.record("compress-bc");
708 } else if config.embed_bitcode_marker {
709 embed_bitcode(cgcx, llcx, llmod, None);
712 time_ext(config.time_passes, None, &format!("codegen passes [{}]", module_name.unwrap()),
713 || -> Result<(), FatalError> {
715 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
716 let out = path2cstr(&out);
718 extern "C" fn demangle_callback(input_ptr: *const c_char,
720 output_ptr: *mut c_char,
721 output_len: size_t) -> size_t {
723 slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
726 let input = match str::from_utf8(input) {
731 let output = unsafe {
732 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
734 let mut cursor = io::Cursor::new(output);
736 let demangled = match rustc_demangle::try_demangle(input) {
741 if let Err(_) = write!(cursor, "{:#}", demangled) {
742 // Possible only if provided buffer is not big enough
746 cursor.position() as size_t
749 with_codegen(tm, llmod, config.no_builtins, |cpm| {
750 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
751 llvm::LLVMDisposePassManager(cpm);
753 timeline.record("ir");
756 if config.emit_asm || asm_to_obj {
757 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
759 // We can't use the same module for asm and binary output, because that triggers
760 // various errors like invalid IR or broken binaries, so we might have to clone the
761 // module to produce the asm output
762 let llmod = if config.emit_obj {
763 llvm::LLVMCloneModule(llmod)
767 with_codegen(tm, llmod, config.no_builtins, |cpm| {
768 write_output_file(diag_handler, tm, cpm, llmod, &path,
769 llvm::FileType::AssemblyFile)
772 llvm::LLVMDisposeModule(llmod);
774 timeline.record("asm");
778 with_codegen(tm, llmod, config.no_builtins, |cpm| {
779 write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
780 llvm::FileType::ObjectFile)
782 timeline.record("obj");
783 } else if asm_to_obj {
784 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
785 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
786 timeline.record("asm_to_obj");
788 if !config.emit_asm && !cgcx.save_temps {
789 drop(fs::remove_file(&assembly));
797 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
798 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
799 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
804 debug!("removing_bitcode {:?}", bc_out);
805 if let Err(e) = fs::remove_file(&bc_out) {
806 diag_handler.err(&format!("failed to remove bitcode: {}", e));
811 Ok(module.into_compiled_module(config.emit_obj,
813 config.emit_bc_compressed,
814 &cgcx.output_filenames))
817 /// Embed the bitcode of an LLVM module in the LLVM module itself.
819 /// This is done primarily for iOS where it appears to be standard to compile C
820 /// code at least with `-fembed-bitcode` which creates two sections in the
823 /// * __LLVM,__bitcode
824 /// * __LLVM,__cmdline
826 /// It appears *both* of these sections are necessary to get the linker to
827 /// recognize what's going on. For us though we just always throw in an empty
830 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
831 /// embed an empty section.
833 /// Basically all of this is us attempting to follow in the footsteps of clang
834 /// on iOS. See #35968 for lots more info.
835 unsafe fn embed_bitcode(cgcx: &CodegenContext,
838 bitcode: Option<&[u8]>) {
839 let llconst = C_bytes_in_context(llcx, bitcode.unwrap_or(&[]));
840 let llglobal = llvm::LLVMAddGlobal(
842 val_ty(llconst).to_ref(),
843 "rustc.embedded.module\0".as_ptr() as *const _,
845 llvm::LLVMSetInitializer(llglobal, llconst);
847 let is_apple = cgcx.opts.target_triple.triple().contains("-ios") ||
848 cgcx.opts.target_triple.triple().contains("-darwin");
850 let section = if is_apple {
855 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
856 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
857 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
859 let llconst = C_bytes_in_context(llcx, &[]);
860 let llglobal = llvm::LLVMAddGlobal(
862 val_ty(llconst).to_ref(),
863 "rustc.embedded.cmdline\0".as_ptr() as *const _,
865 llvm::LLVMSetInitializer(llglobal, llconst);
866 let section = if is_apple {
871 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
872 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
875 pub(crate) struct CompiledModules {
876 pub modules: Vec<CompiledModule>,
877 pub metadata_module: CompiledModule,
878 pub allocator_module: Option<CompiledModule>,
881 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
882 sess.crate_types.borrow().contains(&config::CrateTypeRlib) &&
883 sess.opts.output_types.contains_key(&OutputType::Exe)
886 pub fn start_async_codegen(tcx: TyCtxt,
887 time_graph: Option<TimeGraph>,
889 metadata: EncodedMetadata,
890 coordinator_receive: Receiver<Box<dyn Any + Send>>,
894 let crate_name = tcx.crate_name(LOCAL_CRATE);
895 let no_builtins = attr::contains_name(&tcx.hir.krate().attrs, "no_builtins");
896 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir.krate().attrs,
897 "windows_subsystem");
898 let windows_subsystem = subsystem.map(|subsystem| {
899 if subsystem != "windows" && subsystem != "console" {
900 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
901 `windows` and `console` are allowed",
904 subsystem.to_string()
907 let linker_info = LinkerInfo::new(tcx);
908 let crate_info = CrateInfo::new(tcx);
910 // Figure out what we actually need to build.
911 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
912 let mut metadata_config = ModuleConfig::new(vec![]);
913 let mut allocator_config = ModuleConfig::new(vec![]);
915 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
917 Sanitizer::Address => {
918 modules_config.passes.push("asan".to_owned());
919 modules_config.passes.push("asan-module".to_owned());
921 Sanitizer::Memory => {
922 modules_config.passes.push("msan".to_owned())
924 Sanitizer::Thread => {
925 modules_config.passes.push("tsan".to_owned())
931 if sess.opts.debugging_opts.profile {
932 modules_config.passes.push("insert-gcov-profiling".to_owned())
935 modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
936 modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
938 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
939 modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
941 // Save all versions of the bytecode if we're saving our temporaries.
942 if sess.opts.cg.save_temps {
943 modules_config.emit_no_opt_bc = true;
944 modules_config.emit_bc = true;
945 modules_config.emit_lto_bc = true;
946 metadata_config.emit_bc = true;
947 allocator_config.emit_bc = true;
950 // Emit compressed bitcode files for the crate if we're emitting an rlib.
951 // Whenever an rlib is created, the bitcode is inserted into the archive in
952 // order to allow LTO against it.
953 if need_crate_bitcode_for_rlib(sess) {
954 modules_config.emit_bc_compressed = true;
955 allocator_config.emit_bc_compressed = true;
958 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
959 tcx.sess.target.target.options.no_integrated_as;
961 for output_type in sess.opts.output_types.keys() {
963 OutputType::Bitcode => { modules_config.emit_bc = true; }
964 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
965 OutputType::Assembly => {
966 modules_config.emit_asm = true;
967 // If we're not using the LLVM assembler, this function
968 // could be invoked specially with output_type_assembly, so
969 // in this case we still want the metadata object file.
970 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
971 metadata_config.emit_obj = true;
972 allocator_config.emit_obj = true;
975 OutputType::Object => { modules_config.emit_obj = true; }
976 OutputType::Metadata => { metadata_config.emit_obj = true; }
978 modules_config.emit_obj = true;
979 metadata_config.emit_obj = true;
980 allocator_config.emit_obj = true;
982 OutputType::Mir => {}
983 OutputType::DepInfo => {}
987 modules_config.set_flags(sess, no_builtins);
988 metadata_config.set_flags(sess, no_builtins);
989 allocator_config.set_flags(sess, no_builtins);
991 // Exclude metadata and allocator modules from time_passes output, since
992 // they throw off the "LLVM passes" measurement.
993 metadata_config.time_passes = false;
994 allocator_config.time_passes = false;
996 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
997 let (codegen_worker_send, codegen_worker_receive) = channel();
999 let coordinator_thread = start_executing_work(tcx,
1002 codegen_worker_send,
1003 coordinator_receive,
1005 sess.jobserver.clone(),
1007 Arc::new(modules_config),
1008 Arc::new(metadata_config),
1009 Arc::new(allocator_config));
1020 coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
1021 codegen_worker_receive,
1022 shared_emitter_main,
1023 future: coordinator_thread,
1024 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1028 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
1030 compiled_modules: &CompiledModules
1031 ) -> FxHashMap<WorkProductId, WorkProduct> {
1032 let mut work_products = FxHashMap::default();
1034 if sess.opts.incremental.is_none() {
1035 return work_products;
1038 for module in compiled_modules.modules.iter() {
1039 let mut files = vec![];
1041 if let Some(ref path) = module.object {
1042 files.push((WorkProductFileKind::Object, path.clone()));
1044 if let Some(ref path) = module.bytecode {
1045 files.push((WorkProductFileKind::Bytecode, path.clone()));
1047 if let Some(ref path) = module.bytecode_compressed {
1048 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
1051 if let Some((id, product)) =
1052 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
1053 work_products.insert(id, product);
1060 fn produce_final_output_artifacts(sess: &Session,
1061 compiled_modules: &CompiledModules,
1062 crate_output: &OutputFilenames) {
1063 let mut user_wants_bitcode = false;
1064 let mut user_wants_objects = false;
1066 // Produce final compile outputs.
1067 let copy_gracefully = |from: &Path, to: &Path| {
1068 if let Err(e) = fs::copy(from, to) {
1069 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
1073 let copy_if_one_unit = |output_type: OutputType,
1074 keep_numbered: bool| {
1075 if compiled_modules.modules.len() == 1 {
1076 // 1) Only one codegen unit. In this case it's no difficulty
1077 // to copy `foo.0.x` to `foo.x`.
1078 let module_name = Some(&compiled_modules.modules[0].name[..]);
1079 let path = crate_output.temp_path(output_type, module_name);
1080 copy_gracefully(&path,
1081 &crate_output.path(output_type));
1082 if !sess.opts.cg.save_temps && !keep_numbered {
1083 // The user just wants `foo.x`, not `foo.#module-name#.x`.
1084 remove(sess, &path);
1087 let ext = crate_output.temp_path(output_type, None)
1094 if crate_output.outputs.contains_key(&output_type) {
1095 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
1096 // no good solution for this case, so warn the user.
1097 sess.warn(&format!("ignoring emit path because multiple .{} files \
1098 were produced", ext));
1099 } else if crate_output.single_output_file.is_some() {
1100 // 3) Multiple codegen units, with `-o some_name`. We have
1101 // no good solution for this case, so warn the user.
1102 sess.warn(&format!("ignoring -o because multiple .{} files \
1103 were produced", ext));
1105 // 4) Multiple codegen units, but no explicit name. We
1106 // just leave the `foo.0.x` files in place.
1107 // (We don't have to do any work in this case.)
1112 // Flag to indicate whether the user explicitly requested bitcode.
1113 // Otherwise, we produced it only as a temporary output, and will need
1114 // to get rid of it.
1115 for output_type in crate_output.outputs.keys() {
1116 match *output_type {
1117 OutputType::Bitcode => {
1118 user_wants_bitcode = true;
1119 // Copy to .bc, but always keep the .0.bc. There is a later
1120 // check to figure out if we should delete .0.bc files, or keep
1121 // them for making an rlib.
1122 copy_if_one_unit(OutputType::Bitcode, true);
1124 OutputType::LlvmAssembly => {
1125 copy_if_one_unit(OutputType::LlvmAssembly, false);
1127 OutputType::Assembly => {
1128 copy_if_one_unit(OutputType::Assembly, false);
1130 OutputType::Object => {
1131 user_wants_objects = true;
1132 copy_if_one_unit(OutputType::Object, true);
1135 OutputType::Metadata |
1137 OutputType::DepInfo => {}
1141 // Clean up unwanted temporary files.
1143 // We create the following files by default:
1144 // - #crate#.#module-name#.bc
1145 // - #crate#.#module-name#.o
1146 // - #crate#.crate.metadata.bc
1147 // - #crate#.crate.metadata.o
1148 // - #crate#.o (linked from crate.##.o)
1149 // - #crate#.bc (copied from crate.##.bc)
1150 // We may create additional files if requested by the user (through
1151 // `-C save-temps` or `--emit=` flags).
1153 if !sess.opts.cg.save_temps {
1154 // Remove the temporary .#module-name#.o objects. If the user didn't
1155 // explicitly request bitcode (with --emit=bc), and the bitcode is not
1156 // needed for building an rlib, then we must remove .#module-name#.bc as
1159 // Specific rules for keeping .#module-name#.bc:
1160 // - If the user requested bitcode (`user_wants_bitcode`), and
1161 // codegen_units > 1, then keep it.
1162 // - If the user requested bitcode but codegen_units == 1, then we
1163 // can toss .#module-name#.bc because we copied it to .bc earlier.
1164 // - If we're not building an rlib and the user didn't request
1165 // bitcode, then delete .#module-name#.bc.
1166 // If you change how this works, also update back::link::link_rlib,
1167 // where .#module-name#.bc files are (maybe) deleted after making an
1169 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
1171 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
1173 let keep_numbered_objects = needs_crate_object ||
1174 (user_wants_objects && sess.codegen_units() > 1);
1176 for module in compiled_modules.modules.iter() {
1177 if let Some(ref path) = module.object {
1178 if !keep_numbered_objects {
1183 if let Some(ref path) = module.bytecode {
1184 if !keep_numbered_bitcode {
1190 if !user_wants_bitcode {
1191 if let Some(ref path) = compiled_modules.metadata_module.bytecode {
1192 remove(sess, &path);
1195 if let Some(ref allocator_module) = compiled_modules.allocator_module {
1196 if let Some(ref path) = allocator_module.bytecode {
1203 // We leave the following files around by default:
1205 // - #crate#.crate.metadata.o
1207 // These are used in linking steps and will be cleaned up afterward.
1210 pub(crate) fn dump_incremental_data(codegen_results: &CodegenResults) {
1211 println!("[incremental] Re-using {} out of {} modules",
1212 codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
1213 codegen_results.modules.len());
1217 Optimize(ModuleCodegen),
1218 LTO(lto::LtoModuleCodegen),
1222 fn kind(&self) -> ModuleKind {
1224 WorkItem::Optimize(ref m) => m.kind,
1225 WorkItem::LTO(_) => ModuleKind::Regular,
1229 fn name(&self) -> String {
1231 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
1232 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
1237 enum WorkItemResult {
1238 Compiled(CompiledModule),
1239 NeedsLTO(ModuleCodegen),
1242 fn execute_work_item(cgcx: &CodegenContext,
1243 work_item: WorkItem,
1244 timeline: &mut Timeline)
1245 -> Result<WorkItemResult, FatalError>
1247 let diag_handler = cgcx.create_diag_handler();
1248 let config = cgcx.config(work_item.kind());
1249 let module = match work_item {
1250 WorkItem::Optimize(module) => module,
1251 WorkItem::LTO(mut lto) => {
1253 let module = lto.optimize(cgcx, timeline)?;
1254 let module = codegen(cgcx, &diag_handler, module, config, timeline)?;
1255 return Ok(WorkItemResult::Compiled(module))
1259 let module_name = module.name.clone();
1261 let pre_existing = match module.source {
1262 ModuleSource::Codegened(_) => None,
1263 ModuleSource::Preexisting(ref wp) => Some(wp.clone()),
1266 if let Some(wp) = pre_existing {
1267 let incr_comp_session_dir = cgcx.incr_comp_session_dir
1270 let name = &module.name;
1271 let mut object = None;
1272 let mut bytecode = None;
1273 let mut bytecode_compressed = None;
1274 for (kind, saved_file) in wp.saved_files {
1275 let obj_out = match kind {
1276 WorkProductFileKind::Object => {
1277 let path = cgcx.output_filenames.temp_path(OutputType::Object, Some(name));
1278 object = Some(path.clone());
1281 WorkProductFileKind::Bytecode => {
1282 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(name));
1283 bytecode = Some(path.clone());
1286 WorkProductFileKind::BytecodeCompressed => {
1287 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(name))
1288 .with_extension(RLIB_BYTECODE_EXTENSION);
1289 bytecode_compressed = Some(path.clone());
1293 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
1295 debug!("copying pre-existing module `{}` from {:?} to {}",
1299 match link_or_copy(&source_file, &obj_out) {
1302 diag_handler.err(&format!("unable to copy {} to {}: {}",
1303 source_file.display(),
1309 assert_eq!(object.is_some(), config.emit_obj);
1310 assert_eq!(bytecode.is_some(), config.emit_bc);
1311 assert_eq!(bytecode_compressed.is_some(), config.emit_bc_compressed);
1313 Ok(WorkItemResult::Compiled(CompiledModule {
1314 llmod_id: module.llmod_id.clone(),
1316 kind: ModuleKind::Regular,
1320 bytecode_compressed,
1323 debug!("llvm-optimizing {:?}", module_name);
1326 optimize(cgcx, &diag_handler, &module, config, timeline)?;
1328 // After we've done the initial round of optimizations we need to
1329 // decide whether to synchronously codegen this module or ship it
1330 // back to the coordinator thread for further LTO processing (which
1331 // has to wait for all the initial modules to be optimized).
1333 // Here we dispatch based on the `cgcx.lto` and kind of module we're
1335 let needs_lto = match cgcx.lto {
1338 // Here we've got a full crate graph LTO requested. We ignore
1339 // this, however, if the crate type is only an rlib as there's
1340 // no full crate graph to process, that'll happen later.
1342 // This use case currently comes up primarily for targets that
1343 // require LTO so the request for LTO is always unconditionally
1344 // passed down to the backend, but we don't actually want to do
1345 // anything about it yet until we've got a final product.
1346 Lto::Yes | Lto::Fat | Lto::Thin => {
1347 cgcx.crate_types.len() != 1 ||
1348 cgcx.crate_types[0] != config::CrateTypeRlib
1351 // When we're automatically doing ThinLTO for multi-codegen-unit
1352 // builds we don't actually want to LTO the allocator modules if
1353 // it shows up. This is due to various linker shenanigans that
1354 // we'll encounter later.
1356 // Additionally here's where we also factor in the current LLVM
1357 // version. If it doesn't support ThinLTO we skip this.
1359 module.kind != ModuleKind::Allocator &&
1360 llvm::LLVMRustThinLTOAvailable()
1364 // Metadata modules never participate in LTO regardless of the lto
1366 let needs_lto = needs_lto && module.kind != ModuleKind::Metadata;
1368 // Don't run LTO passes when cross-lang LTO is enabled. The linker
1369 // will do that for us in this case.
1370 let needs_lto = needs_lto &&
1371 !cgcx.opts.debugging_opts.cross_lang_lto.enabled();
1374 Ok(WorkItemResult::NeedsLTO(module))
1376 let module = codegen(cgcx, &diag_handler, module, config, timeline)?;
1377 Ok(WorkItemResult::Compiled(module))
1384 Token(io::Result<Acquired>),
1386 result: ModuleCodegen,
1390 result: Result<CompiledModule, ()>,
1394 llvm_work_item: WorkItem,
1403 code: Option<DiagnosticId>,
1407 #[derive(PartialEq, Clone, Copy, Debug)]
1408 enum MainThreadWorkerState {
1414 fn start_executing_work(tcx: TyCtxt,
1415 crate_info: &CrateInfo,
1416 shared_emitter: SharedEmitter,
1417 codegen_worker_send: Sender<Message>,
1418 coordinator_receive: Receiver<Box<dyn Any + Send>>,
1421 time_graph: Option<TimeGraph>,
1422 modules_config: Arc<ModuleConfig>,
1423 metadata_config: Arc<ModuleConfig>,
1424 allocator_config: Arc<ModuleConfig>)
1425 -> thread::JoinHandle<Result<CompiledModules, ()>> {
1426 let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1427 let sess = tcx.sess;
1429 // Compute the set of symbols we need to retain when doing LTO (if we need to)
1430 let exported_symbols = {
1431 let mut exported_symbols = FxHashMap();
1433 let copy_symbols = |cnum| {
1434 let symbols = tcx.exported_symbols(cnum)
1436 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1444 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1445 Some(Arc::new(exported_symbols))
1447 Lto::Yes | Lto::Fat | Lto::Thin => {
1448 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1449 for &cnum in tcx.crates().iter() {
1450 exported_symbols.insert(cnum, copy_symbols(cnum));
1452 Some(Arc::new(exported_symbols))
1457 // First up, convert our jobserver into a helper thread so we can use normal
1458 // mpsc channels to manage our messages and such.
1459 // After we've requested tokens then we'll, when we can,
1460 // get tokens on `coordinator_receive` which will
1461 // get managed in the main loop below.
1462 let coordinator_send2 = coordinator_send.clone();
1463 let helper = jobserver.into_helper_thread(move |token| {
1464 drop(coordinator_send2.send(Box::new(Message::Token(token))));
1465 }).expect("failed to spawn helper thread");
1467 let mut each_linked_rlib_for_lto = Vec::new();
1468 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1469 if link::ignored_for_lto(sess, crate_info, cnum) {
1472 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1475 let assembler_cmd = if modules_config.no_integrated_as {
1476 // HACK: currently we use linker (gcc) as our assembler
1477 let (name, mut cmd) = get_linker(sess);
1478 cmd.args(&sess.target.target.options.asm_args);
1479 Some(Arc::new(AssemblerCommand {
1487 let cgcx = CodegenContext {
1488 crate_types: sess.crate_types.borrow().clone(),
1489 each_linked_rlib_for_lto,
1491 no_landing_pads: sess.no_landing_pads(),
1492 fewer_names: sess.fewer_names(),
1493 save_temps: sess.opts.cg.save_temps,
1494 opts: Arc::new(sess.opts.clone()),
1495 time_passes: sess.time_passes(),
1497 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1498 remark: sess.opts.cg.remark.clone(),
1500 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1502 diag_emitter: shared_emitter.clone(),
1504 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1505 regular_module_config: modules_config,
1506 metadata_module_config: metadata_config,
1507 allocator_module_config: allocator_config,
1508 tm_factory: target_machine_factory(tcx.sess, false),
1510 msvc_imps_needed: msvc_imps_needed(tcx),
1511 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1512 debuginfo: tcx.sess.opts.debuginfo,
1516 // This is the "main loop" of parallel work happening for parallel codegen.
1517 // It's here that we manage parallelism, schedule work, and work with
1518 // messages coming from clients.
1520 // There are a few environmental pre-conditions that shape how the system
1523 // - Error reporting only can happen on the main thread because that's the
1524 // only place where we have access to the compiler `Session`.
1525 // - LLVM work can be done on any thread.
1526 // - Codegen can only happen on the main thread.
1527 // - Each thread doing substantial work most be in possession of a `Token`
1528 // from the `Jobserver`.
1529 // - The compiler process always holds one `Token`. Any additional `Tokens`
1530 // have to be requested from the `Jobserver`.
1534 // The error reporting restriction is handled separately from the rest: We
1535 // set up a `SharedEmitter` the holds an open channel to the main thread.
1536 // When an error occurs on any thread, the shared emitter will send the
1537 // error message to the receiver main thread (`SharedEmitterMain`). The
1538 // main thread will periodically query this error message queue and emit
1539 // any error messages it has received. It might even abort compilation if
1540 // has received a fatal error. In this case we rely on all other threads
1541 // being torn down automatically with the main thread.
1542 // Since the main thread will often be busy doing codegen work, error
1543 // reporting will be somewhat delayed, since the message queue can only be
1544 // checked in between to work packages.
1546 // Work Processing Infrastructure
1547 // ==============================
1548 // The work processing infrastructure knows three major actors:
1550 // - the coordinator thread,
1551 // - the main thread, and
1552 // - LLVM worker threads
1554 // The coordinator thread is running a message loop. It instructs the main
1555 // thread about what work to do when, and it will spawn off LLVM worker
1556 // threads as open LLVM WorkItems become available.
1558 // The job of the main thread is to codegen CGUs into LLVM work package
1559 // (since the main thread is the only thread that can do this). The main
1560 // thread will block until it receives a message from the coordinator, upon
1561 // which it will codegen one CGU, send it to the coordinator and block
1562 // again. This way the coordinator can control what the main thread is
1565 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1566 // available, it will spawn off a new LLVM worker thread and let it process
1567 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1568 // it will just shut down, which also frees all resources associated with
1569 // the given LLVM module, and sends a message to the coordinator that the
1570 // has been completed.
1574 // The scheduler's goal is to minimize the time it takes to complete all
1575 // work there is, however, we also want to keep memory consumption low
1576 // if possible. These two goals are at odds with each other: If memory
1577 // consumption were not an issue, we could just let the main thread produce
1578 // LLVM WorkItems at full speed, assuring maximal utilization of
1579 // Tokens/LLVM worker threads. However, since codegen usual is faster
1580 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1581 // WorkItem potentially holds on to a substantial amount of memory.
1583 // So the actual goal is to always produce just enough LLVM WorkItems as
1584 // not to starve our LLVM worker threads. That means, once we have enough
1585 // WorkItems in our queue, we can block the main thread, so it does not
1586 // produce more until we need them.
1588 // Doing LLVM Work on the Main Thread
1589 // ----------------------------------
1590 // Since the main thread owns the compiler processes implicit `Token`, it is
1591 // wasteful to keep it blocked without doing any work. Therefore, what we do
1592 // in this case is: We spawn off an additional LLVM worker thread that helps
1593 // reduce the queue. The work it is doing corresponds to the implicit
1594 // `Token`. The coordinator will mark the main thread as being busy with
1595 // LLVM work. (The actual work happens on another OS thread but we just care
1596 // about `Tokens`, not actual threads).
1598 // When any LLVM worker thread finishes while the main thread is marked as
1599 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1600 // of the just finished thread to the LLVM worker thread that is working on
1601 // behalf of the main thread's implicit Token, thus freeing up the main
1602 // thread again. The coordinator can then again decide what the main thread
1603 // should do. This allows the coordinator to make decisions at more points
1606 // Striking a Balance between Throughput and Memory Consumption
1607 // ------------------------------------------------------------
1608 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1609 // memory consumption as low as possible, are in conflict with each other,
1610 // we have to find a trade off between them. Right now, the goal is to keep
1611 // all workers busy, which means that no worker should find the queue empty
1612 // when it is ready to start.
1613 // How do we do achieve this? Good question :) We actually never know how
1614 // many `Tokens` are potentially available so it's hard to say how much to
1615 // fill up the queue before switching the main thread to LLVM work. Also we
1616 // currently don't have a means to estimate how long a running LLVM worker
1617 // will still be busy with it's current WorkItem. However, we know the
1618 // maximal count of available Tokens that makes sense (=the number of CPU
1619 // cores), so we can take a conservative guess. The heuristic we use here
1620 // is implemented in the `queue_full_enough()` function.
1622 // Some Background on Jobservers
1623 // -----------------------------
1624 // It's worth also touching on the management of parallelism here. We don't
1625 // want to just spawn a thread per work item because while that's optimal
1626 // parallelism it may overload a system with too many threads or violate our
1627 // configuration for the maximum amount of cpu to use for this process. To
1628 // manage this we use the `jobserver` crate.
1630 // Job servers are an artifact of GNU make and are used to manage
1631 // parallelism between processes. A jobserver is a glorified IPC semaphore
1632 // basically. Whenever we want to run some work we acquire the semaphore,
1633 // and whenever we're done with that work we release the semaphore. In this
1634 // manner we can ensure that the maximum number of parallel workers is
1635 // capped at any one point in time.
1637 // LTO and the coordinator thread
1638 // ------------------------------
1640 // The final job the coordinator thread is responsible for is managing LTO
1641 // and how that works. When LTO is requested what we'll to is collect all
1642 // optimized LLVM modules into a local vector on the coordinator. Once all
1643 // modules have been codegened and optimized we hand this to the `lto`
1644 // module for further optimization. The `lto` module will return back a list
1645 // of more modules to work on, which the coordinator will continue to spawn
1648 // Each LLVM module is automatically sent back to the coordinator for LTO if
1649 // necessary. There's already optimizations in place to avoid sending work
1650 // back to the coordinator if LTO isn't requested.
1651 return thread::spawn(move || {
1652 // We pretend to be within the top-level LLVM time-passes task here:
1655 let max_workers = ::num_cpus::get();
1656 let mut worker_id_counter = 0;
1657 let mut free_worker_ids = Vec::new();
1658 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1659 if let Some(id) = free_worker_ids.pop() {
1662 let id = worker_id_counter;
1663 worker_id_counter += 1;
1668 // This is where we collect codegen units that have gone all the way
1669 // through codegen and LLVM.
1670 let mut compiled_modules = vec![];
1671 let mut compiled_metadata_module = None;
1672 let mut compiled_allocator_module = None;
1673 let mut needs_lto = Vec::new();
1674 let mut started_lto = false;
1676 // This flag tracks whether all items have gone through codegens
1677 let mut codegen_done = false;
1679 // This is the queue of LLVM work items that still need processing.
1680 let mut work_items = Vec::<(WorkItem, u64)>::new();
1682 // This are the Jobserver Tokens we currently hold. Does not include
1683 // the implicit Token the compiler process owns no matter what.
1684 let mut tokens = Vec::new();
1686 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1687 let mut running = 0;
1689 let mut llvm_start_time = None;
1691 // Run the message loop while there's still anything that needs message
1693 while !codegen_done ||
1694 work_items.len() > 0 ||
1696 needs_lto.len() > 0 ||
1697 main_thread_worker_state != MainThreadWorkerState::Idle {
1699 // While there are still CGUs to be codegened, the coordinator has
1700 // to decide how to utilize the compiler processes implicit Token:
1701 // For codegenning more CGU or for running them through LLVM.
1703 if main_thread_worker_state == MainThreadWorkerState::Idle {
1704 if !queue_full_enough(work_items.len(), running, max_workers) {
1705 // The queue is not full enough, codegen more items:
1706 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1707 panic!("Could not send Message::CodegenItem to main thread")
1709 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1711 // The queue is full enough to not let the worker
1712 // threads starve. Use the implicit Token to do some
1714 let (item, _) = work_items.pop()
1715 .expect("queue empty - queue_full_enough() broken?");
1716 let cgcx = CodegenContext {
1717 worker: get_worker_id(&mut free_worker_ids),
1720 maybe_start_llvm_timer(cgcx.config(item.kind()),
1721 &mut llvm_start_time);
1722 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1723 spawn_work(cgcx, item);
1727 // If we've finished everything related to normal codegen
1728 // then it must be the case that we've got some LTO work to do.
1729 // Perform the serial work here of figuring out what we're
1730 // going to LTO and then push a bunch of work items onto our
1732 if work_items.len() == 0 &&
1734 main_thread_worker_state == MainThreadWorkerState::Idle {
1735 assert!(!started_lto);
1736 assert!(needs_lto.len() > 0);
1738 let modules = mem::replace(&mut needs_lto, Vec::new());
1739 for (work, cost) in generate_lto_work(&cgcx, modules) {
1740 let insertion_index = work_items
1741 .binary_search_by_key(&cost, |&(_, cost)| cost)
1742 .unwrap_or_else(|e| e);
1743 work_items.insert(insertion_index, (work, cost));
1744 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1745 helper.request_token();
1750 // In this branch, we know that everything has been codegened,
1751 // so it's just a matter of determining whether the implicit
1752 // Token is free to use for LLVM work.
1753 match main_thread_worker_state {
1754 MainThreadWorkerState::Idle => {
1755 if let Some((item, _)) = work_items.pop() {
1756 let cgcx = CodegenContext {
1757 worker: get_worker_id(&mut free_worker_ids),
1760 maybe_start_llvm_timer(cgcx.config(item.kind()),
1761 &mut llvm_start_time);
1762 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1763 spawn_work(cgcx, item);
1765 // There is no unstarted work, so let the main thread
1766 // take over for a running worker. Otherwise the
1767 // implicit token would just go to waste.
1768 // We reduce the `running` counter by one. The
1769 // `tokens.truncate()` below will take care of
1770 // giving the Token back.
1771 debug_assert!(running > 0);
1773 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1776 MainThreadWorkerState::Codegenning => {
1777 bug!("codegen worker should not be codegenning after \
1778 codegen was already completed")
1780 MainThreadWorkerState::LLVMing => {
1781 // Already making good use of that token
1786 // Spin up what work we can, only doing this while we've got available
1787 // parallelism slots and work left to spawn.
1788 while work_items.len() > 0 && running < tokens.len() {
1789 let (item, _) = work_items.pop().unwrap();
1791 maybe_start_llvm_timer(cgcx.config(item.kind()),
1792 &mut llvm_start_time);
1794 let cgcx = CodegenContext {
1795 worker: get_worker_id(&mut free_worker_ids),
1799 spawn_work(cgcx, item);
1803 // Relinquish accidentally acquired extra tokens
1804 tokens.truncate(running);
1806 let msg = coordinator_receive.recv().unwrap();
1807 match *msg.downcast::<Message>().ok().unwrap() {
1808 // Save the token locally and the next turn of the loop will use
1809 // this to spawn a new unit of work, or it may get dropped
1810 // immediately if we have no more work to spawn.
1811 Message::Token(token) => {
1816 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1817 // If the main thread token is used for LLVM work
1818 // at the moment, we turn that thread into a regular
1819 // LLVM worker thread, so the main thread is free
1820 // to react to codegen demand.
1821 main_thread_worker_state = MainThreadWorkerState::Idle;
1826 let msg = &format!("failed to acquire jobserver token: {}", e);
1827 shared_emitter.fatal(msg);
1828 // Exit the coordinator thread
1834 Message::CodegenDone { llvm_work_item, cost } => {
1835 // We keep the queue sorted by estimated processing cost,
1836 // so that more expensive items are processed earlier. This
1837 // is good for throughput as it gives the main thread more
1838 // time to fill up the queue and it avoids scheduling
1839 // expensive items to the end.
1840 // Note, however, that this is not ideal for memory
1841 // consumption, as LLVM module sizes are not evenly
1843 let insertion_index =
1844 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1845 let insertion_index = match insertion_index {
1846 Ok(idx) | Err(idx) => idx
1848 work_items.insert(insertion_index, (llvm_work_item, cost));
1850 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1851 helper.request_token();
1853 assert_eq!(main_thread_worker_state,
1854 MainThreadWorkerState::Codegenning);
1855 main_thread_worker_state = MainThreadWorkerState::Idle;
1858 Message::CodegenComplete => {
1859 codegen_done = true;
1860 assert_eq!(main_thread_worker_state,
1861 MainThreadWorkerState::Codegenning);
1862 main_thread_worker_state = MainThreadWorkerState::Idle;
1865 // If a thread exits successfully then we drop a token associated
1866 // with that worker and update our `running` count. We may later
1867 // re-acquire a token to continue running more work. We may also not
1868 // actually drop a token here if the worker was running with an
1869 // "ephemeral token"
1871 // Note that if the thread failed that means it panicked, so we
1872 // abort immediately.
1873 Message::Done { result: Ok(compiled_module), worker_id } => {
1874 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1875 main_thread_worker_state = MainThreadWorkerState::Idle;
1880 free_worker_ids.push(worker_id);
1882 match compiled_module.kind {
1883 ModuleKind::Regular => {
1884 compiled_modules.push(compiled_module);
1886 ModuleKind::Metadata => {
1887 assert!(compiled_metadata_module.is_none());
1888 compiled_metadata_module = Some(compiled_module);
1890 ModuleKind::Allocator => {
1891 assert!(compiled_allocator_module.is_none());
1892 compiled_allocator_module = Some(compiled_module);
1896 Message::NeedsLTO { result, worker_id } => {
1897 assert!(!started_lto);
1898 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1899 main_thread_worker_state = MainThreadWorkerState::Idle;
1904 free_worker_ids.push(worker_id);
1905 needs_lto.push(result);
1907 Message::Done { result: Err(()), worker_id: _ } => {
1908 shared_emitter.fatal("aborting due to worker thread failure");
1909 // Exit the coordinator thread
1912 Message::CodegenItem => {
1913 bug!("the coordinator should not receive codegen requests")
1918 if let Some(llvm_start_time) = llvm_start_time {
1919 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
1920 // This is the top-level timing for all of LLVM, set the time-depth
1923 print_time_passes_entry(cgcx.time_passes,
1928 // Regardless of what order these modules completed in, report them to
1929 // the backend in the same order every time to ensure that we're handing
1930 // out deterministic results.
1931 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1933 let compiled_metadata_module = compiled_metadata_module
1934 .expect("Metadata module not compiled?");
1936 Ok(CompiledModules {
1937 modules: compiled_modules,
1938 metadata_module: compiled_metadata_module,
1939 allocator_module: compiled_allocator_module,
1943 // A heuristic that determines if we have enough LLVM WorkItems in the
1944 // queue so that the main thread can do LLVM work instead of codegen
1945 fn queue_full_enough(items_in_queue: usize,
1946 workers_running: usize,
1947 max_workers: usize) -> bool {
1949 items_in_queue > 0 &&
1950 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1953 fn maybe_start_llvm_timer(config: &ModuleConfig,
1954 llvm_start_time: &mut Option<Instant>) {
1955 // We keep track of the -Ztime-passes output manually,
1956 // since the closure-based interface does not fit well here.
1957 if config.time_passes {
1958 if llvm_start_time.is_none() {
1959 *llvm_start_time = Some(Instant::now());
1965 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1966 pub const CODEGEN_WORKER_TIMELINE: time_graph::TimelineId =
1967 time_graph::TimelineId(CODEGEN_WORKER_ID);
1968 pub const CODEGEN_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1969 time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
1970 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1971 time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
1973 fn spawn_work(cgcx: CodegenContext, work: WorkItem) {
1974 let depth = time_depth();
1976 thread::spawn(move || {
1977 set_time_depth(depth);
1979 // Set up a destructor which will fire off a message that we're done as
1982 coordinator_send: Sender<Box<dyn Any + Send>>,
1983 result: Option<WorkItemResult>,
1986 impl Drop for Bomb {
1987 fn drop(&mut self) {
1988 let worker_id = self.worker_id;
1989 let msg = match self.result.take() {
1990 Some(WorkItemResult::Compiled(m)) => {
1991 Message::Done { result: Ok(m), worker_id }
1993 Some(WorkItemResult::NeedsLTO(m)) => {
1994 Message::NeedsLTO { result: m, worker_id }
1996 None => Message::Done { result: Err(()), worker_id }
1998 drop(self.coordinator_send.send(Box::new(msg)));
2002 let mut bomb = Bomb {
2003 coordinator_send: cgcx.coordinator_send.clone(),
2005 worker_id: cgcx.worker,
2008 // Execute the work itself, and if it finishes successfully then flag
2009 // ourselves as a success as well.
2011 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
2012 // as a diagnostic was already sent off to the main thread - just
2013 // surface that there was an error in this worker.
2015 let timeline = cgcx.time_graph.as_ref().map(|tg| {
2016 tg.start(time_graph::TimelineId(cgcx.worker),
2017 LLVM_WORK_PACKAGE_KIND,
2020 let mut timeline = timeline.unwrap_or(Timeline::noop());
2021 execute_work_item(&cgcx, work, &mut timeline).ok()
2026 pub fn run_assembler(cgcx: &CodegenContext, handler: &Handler, assembly: &Path, object: &Path) {
2027 let assembler = cgcx.assembler_cmd
2029 .expect("cgcx.assembler_cmd is missing?");
2031 let pname = &assembler.name;
2032 let mut cmd = assembler.cmd.clone();
2033 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
2034 debug!("{:?}", cmd);
2036 match cmd.output() {
2038 if !prog.status.success() {
2039 let mut note = prog.stderr.clone();
2040 note.extend_from_slice(&prog.stdout);
2042 handler.struct_err(&format!("linking with `{}` failed: {}",
2045 .note(&format!("{:?}", &cmd))
2046 .note(str::from_utf8(¬e[..]).unwrap())
2048 handler.abort_if_errors();
2052 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
2053 handler.abort_if_errors();
2058 pub unsafe fn with_llvm_pmb(llmod: ModuleRef,
2059 config: &ModuleConfig,
2060 opt_level: llvm::CodeGenOptLevel,
2061 prepare_for_thin_lto: bool,
2062 f: &mut dyn FnMut(llvm::PassManagerBuilderRef)) {
2065 // Create the PassManagerBuilder for LLVM. We configure it with
2066 // reasonable defaults and prepare it to actually populate the pass
2068 let builder = llvm::LLVMPassManagerBuilderCreate();
2069 let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
2070 let inline_threshold = config.inline_threshold;
2072 let pgo_gen_path = config.pgo_gen.as_ref().map(|s| {
2073 let s = if s.is_empty() { "default_%m.profraw" } else { s };
2074 CString::new(s.as_bytes()).unwrap()
2077 let pgo_use_path = if config.pgo_use.is_empty() {
2080 Some(CString::new(config.pgo_use.as_bytes()).unwrap())
2083 llvm::LLVMRustConfigurePassManagerBuilder(
2086 config.merge_functions,
2087 config.vectorize_slp,
2088 config.vectorize_loop,
2089 prepare_for_thin_lto,
2090 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2091 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2094 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
2096 if opt_size != llvm::CodeGenOptSizeNone {
2097 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
2100 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
2102 // Here we match what clang does (kinda). For O0 we only inline
2103 // always-inline functions (but don't add lifetime intrinsics), at O1 we
2104 // inline with lifetime intrinsics, and O2+ we add an inliner with a
2105 // thresholds copied from clang.
2106 match (opt_level, opt_size, inline_threshold) {
2108 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
2110 (llvm::CodeGenOptLevel::Aggressive, ..) => {
2111 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
2113 (_, llvm::CodeGenOptSizeDefault, _) => {
2114 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
2116 (_, llvm::CodeGenOptSizeAggressive, _) => {
2117 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
2119 (llvm::CodeGenOptLevel::None, ..) => {
2120 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
2122 (llvm::CodeGenOptLevel::Less, ..) => {
2123 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
2125 (llvm::CodeGenOptLevel::Default, ..) => {
2126 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
2128 (llvm::CodeGenOptLevel::Other, ..) => {
2129 bug!("CodeGenOptLevel::Other selected")
2134 llvm::LLVMPassManagerBuilderDispose(builder);
2138 enum SharedEmitterMessage {
2139 Diagnostic(Diagnostic),
2140 InlineAsmError(u32, String),
2146 pub struct SharedEmitter {
2147 sender: Sender<SharedEmitterMessage>,
2150 pub struct SharedEmitterMain {
2151 receiver: Receiver<SharedEmitterMessage>,
2154 impl SharedEmitter {
2155 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
2156 let (sender, receiver) = channel();
2158 (SharedEmitter { sender }, SharedEmitterMain { receiver })
2161 fn inline_asm_error(&self, cookie: u32, msg: String) {
2162 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
2165 fn fatal(&self, msg: &str) {
2166 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2170 impl Emitter for SharedEmitter {
2171 fn emit(&mut self, db: &DiagnosticBuilder) {
2172 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2174 code: db.code.clone(),
2177 for child in &db.children {
2178 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2179 msg: child.message(),
2184 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
2188 impl SharedEmitterMain {
2189 pub fn check(&self, sess: &Session, blocking: bool) {
2191 let message = if blocking {
2192 match self.receiver.recv() {
2193 Ok(message) => Ok(message),
2197 match self.receiver.try_recv() {
2198 Ok(message) => Ok(message),
2204 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2205 let handler = sess.diagnostic();
2208 handler.emit_with_code(&MultiSpan::new(),
2214 handler.emit(&MultiSpan::new(),
2220 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
2221 match Mark::from_u32(cookie).expn_info() {
2222 Some(ei) => sess.span_err(ei.call_site, &msg),
2223 None => sess.err(&msg),
2226 Ok(SharedEmitterMessage::AbortIfErrors) => {
2227 sess.abort_if_errors();
2229 Ok(SharedEmitterMessage::Fatal(msg)) => {
2241 pub struct OngoingCodegen {
2244 metadata: EncodedMetadata,
2245 windows_subsystem: Option<String>,
2246 linker_info: LinkerInfo,
2247 crate_info: CrateInfo,
2248 time_graph: Option<TimeGraph>,
2249 coordinator_send: Sender<Box<dyn Any + Send>>,
2250 codegen_worker_receive: Receiver<Message>,
2251 shared_emitter_main: SharedEmitterMain,
2252 future: thread::JoinHandle<Result<CompiledModules, ()>>,
2253 output_filenames: Arc<OutputFilenames>,
2256 impl OngoingCodegen {
2260 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
2261 self.shared_emitter_main.check(sess, true);
2262 let compiled_modules = match self.future.join() {
2263 Ok(Ok(compiled_modules)) => compiled_modules,
2265 sess.abort_if_errors();
2266 panic!("expected abort due to worker thread errors")
2269 sess.fatal("Error during codegen/LLVM phase.");
2273 sess.abort_if_errors();
2275 if let Some(time_graph) = self.time_graph {
2276 time_graph.dump(&format!("{}-timings", self.crate_name));
2279 let work_products = copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
2282 produce_final_output_artifacts(sess,
2284 &self.output_filenames);
2286 // FIXME: time_llvm_passes support - does this use a global context or
2288 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
2289 unsafe { llvm::LLVMRustPrintPassTimings(); }
2293 crate_name: self.crate_name,
2295 metadata: self.metadata,
2296 windows_subsystem: self.windows_subsystem,
2297 linker_info: self.linker_info,
2298 crate_info: self.crate_info,
2300 modules: compiled_modules.modules,
2301 allocator_module: compiled_modules.allocator_module,
2302 metadata_module: compiled_modules.metadata_module,
2306 pub(crate) fn submit_pre_codegened_module_to_llvm(&self,
2308 module: ModuleCodegen) {
2309 self.wait_for_signal_to_codegen_item();
2310 self.check_for_errors(tcx.sess);
2312 // These are generally cheap and won't through off scheduling.
2314 submit_codegened_module_to_llvm(tcx, module, cost);
2317 pub fn codegen_finished(&self, tcx: TyCtxt) {
2318 self.wait_for_signal_to_codegen_item();
2319 self.check_for_errors(tcx.sess);
2320 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete)));
2323 pub fn check_for_errors(&self, sess: &Session) {
2324 self.shared_emitter_main.check(sess, false);
2327 pub fn wait_for_signal_to_codegen_item(&self) {
2328 match self.codegen_worker_receive.recv() {
2329 Ok(Message::CodegenItem) => {
2332 Ok(_) => panic!("unexpected message"),
2334 // One of the LLVM threads must have panicked, fall through so
2335 // error handling can be reached.
2341 pub(crate) fn submit_codegened_module_to_llvm(tcx: TyCtxt,
2342 module: ModuleCodegen,
2344 let llvm_work_item = WorkItem::Optimize(module);
2345 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2351 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
2352 tcx.sess.target.target.options.is_like_msvc &&
2353 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib)
2356 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2357 // This is required to satisfy `dllimport` references to static data in .rlibs
2358 // when using MSVC linker. We do this only for data, as linker can fix up
2359 // code references on its own.
2360 // See #26591, #27438
2361 fn create_msvc_imps(cgcx: &CodegenContext, llcx: ContextRef, llmod: ModuleRef) {
2362 if !cgcx.msvc_imps_needed {
2365 // The x86 ABI seems to require that leading underscores are added to symbol
2366 // names, so we need an extra underscore on 32-bit. There's also a leading
2367 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2368 // underscores added in front).
2369 let prefix = if cgcx.target_pointer_width == "32" {
2375 let i8p_ty = Type::i8p_llcx(llcx);
2376 let globals = base::iter_globals(llmod)
2378 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
2379 llvm::LLVMIsDeclaration(val) == 0
2382 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2383 let mut imp_name = prefix.as_bytes().to_vec();
2384 imp_name.extend(name.to_bytes());
2385 let imp_name = CString::new(imp_name).unwrap();
2388 .collect::<Vec<_>>();
2389 for (imp_name, val) in globals {
2390 let imp = llvm::LLVMAddGlobal(llmod,
2392 imp_name.as_ptr() as *const _);
2393 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
2394 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);