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, Sanitizer, Lto};
24 use rustc::session::Session;
25 use rustc::util::nodemap::FxHashMap;
26 use time_graph::{self, TimeGraph, Timeline};
27 use llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
28 use {CodegenResults, ModuleSource, ModuleCodegen, CompiledModule, ModuleKind};
30 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
31 use rustc::ty::TyCtxt;
32 use rustc::util::common::{time_ext, time_depth, set_time_depth, print_time_passes_entry};
33 use rustc::util::common::path2cstr;
34 use rustc::util::fs::{link_or_copy};
35 use errors::{self, Handler, Level, DiagnosticBuilder, FatalError, DiagnosticId};
36 use errors::emitter::{Emitter};
38 use syntax::ext::hygiene::Mark;
39 use syntax_pos::MultiSpan;
40 use syntax_pos::symbol::Symbol;
42 use context::{is_pie_binary, get_reloc_model};
43 use common::{C_bytes_in_context, val_ty};
44 use jobserver::{Client, Acquired};
48 use std::ffi::{CString, CStr};
50 use std::io::{self, Write};
52 use std::path::{Path, PathBuf};
55 use std::sync::mpsc::{channel, Sender, Receiver};
57 use std::time::Instant;
59 use libc::{c_uint, c_void, c_char, size_t};
61 pub const RELOC_MODEL_ARGS : [(&'static str, llvm::RelocMode); 7] = [
62 ("pic", llvm::RelocMode::PIC),
63 ("static", llvm::RelocMode::Static),
64 ("default", llvm::RelocMode::Default),
65 ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
66 ("ropi", llvm::RelocMode::ROPI),
67 ("rwpi", llvm::RelocMode::RWPI),
68 ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
71 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
72 ("small", llvm::CodeModel::Small),
73 ("kernel", llvm::CodeModel::Kernel),
74 ("medium", llvm::CodeModel::Medium),
75 ("large", llvm::CodeModel::Large),
78 pub const TLS_MODEL_ARGS : [(&'static str, llvm::ThreadLocalMode); 4] = [
79 ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
80 ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
81 ("initial-exec", llvm::ThreadLocalMode::InitialExec),
82 ("local-exec", llvm::ThreadLocalMode::LocalExec),
85 pub fn llvm_err(handler: &errors::Handler, msg: String) -> FatalError {
86 match llvm::last_error() {
87 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
88 None => handler.fatal(&msg),
92 pub fn write_output_file(
93 handler: &errors::Handler,
94 target: &'ll llvm::TargetMachine,
95 pm: &llvm::PassManager<'ll>,
98 file_type: llvm::FileType) -> Result<(), FatalError> {
100 let output_c = path2cstr(output);
101 let result = llvm::LLVMRustWriteOutputFile(
102 target, pm, m, output_c.as_ptr(), file_type);
103 if result.into_result().is_err() {
104 let msg = format!("could not write output to {}", output.display());
105 Err(llvm_err(handler, msg))
112 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
114 config::OptLevel::No => llvm::CodeGenOptLevel::None,
115 config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
116 config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
117 config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
118 _ => llvm::CodeGenOptLevel::Default,
122 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
124 config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
125 config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
126 _ => llvm::CodeGenOptSizeNone,
130 pub fn create_target_machine(
133 ) -> &'static mut llvm::TargetMachine {
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<&'static mut llvm::TargetMachine, 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 format!("Could not create LLVM TargetMachine for triple: {}",
204 triple.to_str().unwrap())
209 /// Module-specific configuration for `optimize_and_codegen`.
210 pub struct ModuleConfig {
211 /// Names of additional optimization passes to run.
213 /// Some(level) to optimize at a certain level, or None to run
214 /// absolutely no optimizations (used for the metadata module).
215 pub opt_level: Option<llvm::CodeGenOptLevel>,
217 /// Some(level) to optimize binary size, or None to not affect program size.
218 opt_size: Option<llvm::CodeGenOptSize>,
220 pgo_gen: Option<String>,
223 // Flags indicating which outputs to produce.
224 emit_no_opt_bc: bool,
226 emit_bc_compressed: bool,
231 // Miscellaneous flags. These are mostly copied from command-line
233 pub verify_llvm_ir: bool,
234 no_prepopulate_passes: bool,
237 vectorize_loop: bool,
239 merge_functions: bool,
240 inline_threshold: Option<usize>,
241 // Instead of creating an object file by doing LLVM codegen, just
242 // make the object file bitcode. Provides easy compatibility with
243 // emscripten's ecc compiler, when used as the linker.
244 obj_is_bitcode: bool,
245 no_integrated_as: bool,
247 embed_bitcode_marker: bool,
251 fn new(passes: Vec<String>) -> ModuleConfig {
258 pgo_use: String::new(),
260 emit_no_opt_bc: false,
262 emit_bc_compressed: false,
267 obj_is_bitcode: false,
268 embed_bitcode: false,
269 embed_bitcode_marker: false,
270 no_integrated_as: false,
272 verify_llvm_ir: false,
273 no_prepopulate_passes: false,
276 vectorize_loop: false,
277 vectorize_slp: false,
278 merge_functions: false,
279 inline_threshold: None
283 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
284 self.verify_llvm_ir = sess.verify_llvm_ir();
285 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
286 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
287 self.time_passes = sess.time_passes();
288 self.inline_threshold = sess.opts.cg.inline_threshold;
289 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
290 sess.opts.debugging_opts.cross_lang_lto.enabled();
291 let embed_bitcode = sess.target.target.options.embed_bitcode ||
292 sess.opts.debugging_opts.embed_bitcode;
294 match sess.opts.optimize {
295 config::OptLevel::No |
296 config::OptLevel::Less => {
297 self.embed_bitcode_marker = embed_bitcode;
299 _ => self.embed_bitcode = embed_bitcode,
303 // Copy what clang does by turning on loop vectorization at O2 and
304 // slp vectorization at O3. Otherwise configure other optimization aspects
305 // of this pass manager builder.
306 // Turn off vectorization for emscripten, as it's not very well supported.
307 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
308 (sess.opts.optimize == config::OptLevel::Default ||
309 sess.opts.optimize == config::OptLevel::Aggressive) &&
310 !sess.target.target.options.is_like_emscripten;
312 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
313 sess.opts.optimize == config::OptLevel::Aggressive &&
314 !sess.target.target.options.is_like_emscripten;
316 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
317 sess.opts.optimize == config::OptLevel::Aggressive;
321 /// Assembler name and command used by codegen when no_integrated_as is enabled
322 struct AssemblerCommand {
327 /// Additional resources used by optimize_and_codegen (not module specific)
329 pub struct CodegenContext {
330 // Resouces needed when running LTO
331 pub time_passes: bool,
333 pub no_landing_pads: bool,
334 pub save_temps: bool,
335 pub fewer_names: bool,
336 pub exported_symbols: Option<Arc<ExportedSymbols>>,
337 pub opts: Arc<config::Options>,
338 pub crate_types: Vec<config::CrateType>,
339 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
340 output_filenames: Arc<OutputFilenames>,
341 regular_module_config: Arc<ModuleConfig>,
342 metadata_module_config: Arc<ModuleConfig>,
343 allocator_module_config: Arc<ModuleConfig>,
344 pub tm_factory: Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>,
345 pub msvc_imps_needed: bool,
346 pub target_pointer_width: String,
347 debuginfo: config::DebugInfo,
349 // Number of cgus excluding the allocator/metadata modules
350 pub total_cgus: usize,
351 // Handler to use for diagnostics produced during codegen.
352 pub diag_emitter: SharedEmitter,
353 // LLVM passes added by plugins.
354 pub plugin_passes: Vec<String>,
355 // LLVM optimizations for which we want to print remarks.
357 // Worker thread number
359 // The incremental compilation session directory, or None if we are not
360 // compiling incrementally
361 pub incr_comp_session_dir: Option<PathBuf>,
362 // Channel back to the main control thread to send messages to
363 coordinator_send: Sender<Box<dyn Any + Send>>,
364 // A reference to the TimeGraph so we can register timings. None means that
365 // measuring is disabled.
366 time_graph: Option<TimeGraph>,
367 // The assembler command if no_integrated_as option is enabled, None otherwise
368 assembler_cmd: Option<Arc<AssemblerCommand>>,
371 impl CodegenContext {
372 pub fn create_diag_handler(&self) -> Handler {
373 Handler::with_emitter(true, false, Box::new(self.diag_emitter.clone()))
376 pub(crate) fn config(&self, kind: ModuleKind) -> &ModuleConfig {
378 ModuleKind::Regular => &self.regular_module_config,
379 ModuleKind::Metadata => &self.metadata_module_config,
380 ModuleKind::Allocator => &self.allocator_module_config,
384 pub(crate) fn save_temp_bitcode(&self, module: &ModuleCodegen, name: &str) {
385 if !self.save_temps {
389 let ext = format!("{}.bc", name);
390 let cgu = Some(&module.name[..]);
391 let path = self.output_filenames.temp_path_ext(&ext, cgu);
392 let cstr = path2cstr(&path);
393 let llmod = module.llvm().unwrap().llmod();
394 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
399 pub struct DiagnosticHandlers<'a> {
400 data: *mut (&'a CodegenContext, &'a Handler),
401 llcx: &'a llvm::Context,
404 impl<'a> DiagnosticHandlers<'a> {
405 pub fn new(cgcx: &'a CodegenContext,
406 handler: &'a Handler,
407 llcx: &'a llvm::Context) -> Self {
408 let data = Box::into_raw(Box::new((cgcx, handler)));
410 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data as *mut _);
411 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data as *mut _);
413 DiagnosticHandlers { data, llcx }
417 impl<'a> Drop for DiagnosticHandlers<'a> {
419 use std::ptr::null_mut;
421 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
422 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
423 drop(Box::from_raw(self.data));
428 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext,
431 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_string());
434 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
440 let (cgcx, _) = *(user as *const (&CodegenContext, &Handler));
442 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
443 .expect("non-UTF8 SMDiagnostic");
445 report_inline_asm(cgcx, &msg, cookie);
448 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
452 let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler));
454 match llvm::diagnostic::Diagnostic::unpack(info) {
455 llvm::diagnostic::InlineAsm(inline) => {
456 report_inline_asm(cgcx,
457 &llvm::twine_to_string(inline.message),
461 llvm::diagnostic::Optimization(opt) => {
462 let enabled = match cgcx.remark {
464 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
468 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
477 llvm::diagnostic::PGO(diagnostic_ref) |
478 llvm::diagnostic::Linker(diagnostic_ref) => {
479 let msg = llvm::build_string(|s| {
480 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
481 }).expect("non-UTF8 diagnostic");
482 diag_handler.warn(&msg);
484 llvm::diagnostic::UnknownDiagnostic(..) => {},
488 // Unsafe due to LLVM calls.
489 unsafe fn optimize(cgcx: &CodegenContext,
490 diag_handler: &Handler,
491 module: &ModuleCodegen,
492 config: &ModuleConfig,
493 timeline: &mut Timeline)
494 -> Result<(), FatalError>
496 let (llmod, llcx, tm) = match module.source {
497 ModuleSource::Codegened(ref llvm) => (llvm.llmod(), &*llvm.llcx, &*llvm.tm),
498 ModuleSource::Preexisting(_) => {
499 bug!("optimize_and_codegen: called with ModuleSource::Preexisting")
503 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
505 let module_name = module.name.clone();
506 let module_name = Some(&module_name[..]);
508 if config.emit_no_opt_bc {
509 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
510 let out = path2cstr(&out);
511 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
514 if config.opt_level.is_some() {
515 // Create the two optimizing pass managers. These mirror what clang
516 // does, and are by populated by LLVM's default PassManagerBuilder.
517 // Each manager has a different set of passes, but they also share
518 // some common passes.
519 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
520 let mpm = llvm::LLVMCreatePassManager();
523 // If we're verifying or linting, add them to the function pass
525 let addpass = |pass_name: &str| {
526 let pass_name = CString::new(pass_name).unwrap();
527 let pass = match llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr()) {
529 None => return false,
531 let pass_manager = match llvm::LLVMRustPassKind(pass) {
532 llvm::PassKind::Function => &*fpm,
533 llvm::PassKind::Module => &*mpm,
534 llvm::PassKind::Other => {
535 diag_handler.err("Encountered LLVM pass kind we can't handle");
539 llvm::LLVMRustAddPass(pass_manager, pass);
543 if config.verify_llvm_ir { assert!(addpass("verify")); }
544 if !config.no_prepopulate_passes {
545 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
546 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
547 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
548 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal;
549 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
550 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
551 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
555 for pass in &config.passes {
557 diag_handler.warn(&format!("unknown pass `{}`, ignoring",
562 for pass in &cgcx.plugin_passes {
564 diag_handler.err(&format!("a plugin asked for LLVM pass \
565 `{}` but LLVM does not \
566 recognize it", pass));
571 diag_handler.abort_if_errors();
573 // Finally, run the actual optimization passes
574 time_ext(config.time_passes,
576 &format!("llvm function passes [{}]", module_name.unwrap()),
578 llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
580 timeline.record("fpm");
581 time_ext(config.time_passes,
583 &format!("llvm module passes [{}]", module_name.unwrap()),
585 llvm::LLVMRunPassManager(mpm, llmod)
588 // Deallocate managers that we're now done with
589 llvm::LLVMDisposePassManager(fpm);
590 llvm::LLVMDisposePassManager(mpm);
595 fn generate_lto_work(cgcx: &CodegenContext,
596 modules: Vec<ModuleCodegen>)
597 -> Vec<(WorkItem, u64)>
599 let mut timeline = cgcx.time_graph.as_ref().map(|tg| {
600 tg.start(CODEGEN_WORKER_TIMELINE,
601 CODEGEN_WORK_PACKAGE_KIND,
603 }).unwrap_or(Timeline::noop());
604 let lto_modules = lto::run(cgcx, modules, &mut timeline)
605 .unwrap_or_else(|e| e.raise());
607 lto_modules.into_iter().map(|module| {
608 let cost = module.cost();
609 (WorkItem::LTO(module), cost)
613 unsafe fn codegen(cgcx: &CodegenContext,
614 diag_handler: &Handler,
615 module: ModuleCodegen,
616 config: &ModuleConfig,
617 timeline: &mut Timeline)
618 -> Result<CompiledModule, FatalError>
620 timeline.record("codegen");
622 let (llmod, llcx, tm) = match module.source {
623 ModuleSource::Codegened(ref llvm) => (llvm.llmod(), &*llvm.llcx, &*llvm.tm),
624 ModuleSource::Preexisting(_) => {
625 bug!("codegen: called with ModuleSource::Preexisting")
628 let module_name = module.name.clone();
629 let module_name = Some(&module_name[..]);
630 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
632 if cgcx.msvc_imps_needed {
633 create_msvc_imps(cgcx, llcx, llmod);
636 // A codegen-specific pass manager is used to generate object
637 // files for an LLVM module.
639 // Apparently each of these pass managers is a one-shot kind of
640 // thing, so we create a new one for each type of output. The
641 // pass manager passed to the closure should be ensured to not
642 // escape the closure itself, and the manager should only be
644 unsafe fn with_codegen<'ll, F, R>(tm: &'ll llvm::TargetMachine,
645 llmod: &'ll llvm::Module,
648 where F: FnOnce(&'ll mut PassManager<'ll>) -> R,
650 let cpm = llvm::LLVMCreatePassManager();
651 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
652 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
656 // If we don't have the integrated assembler, then we need to emit asm
657 // from LLVM and use `gcc` to create the object file.
658 let asm_to_obj = config.emit_obj && config.no_integrated_as;
660 // Change what we write and cleanup based on whether obj files are
661 // just llvm bitcode. In that case write bitcode, and possibly
662 // delete the bitcode if it wasn't requested. Don't generate the
663 // machine code, instead copy the .o file from the .bc
664 let write_bc = config.emit_bc || config.obj_is_bitcode;
665 let rm_bc = !config.emit_bc && config.obj_is_bitcode;
666 let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
667 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
669 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
670 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
673 if write_bc || config.emit_bc_compressed || config.embed_bitcode {
676 let data = if llvm::LLVMRustThinLTOAvailable() {
677 thin = ThinBuffer::new(llmod);
680 old = ModuleBuffer::new(llmod);
683 timeline.record("make-bc");
686 if let Err(e) = fs::write(&bc_out, data) {
687 diag_handler.err(&format!("failed to write bytecode: {}", e));
689 timeline.record("write-bc");
692 if config.embed_bitcode {
693 embed_bitcode(cgcx, llcx, llmod, Some(data));
694 timeline.record("embed-bc");
697 if config.emit_bc_compressed {
698 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
699 let data = bytecode::encode(&module.llmod_id, data);
700 if let Err(e) = fs::write(&dst, data) {
701 diag_handler.err(&format!("failed to write bytecode: {}", e));
703 timeline.record("compress-bc");
705 } else if config.embed_bitcode_marker {
706 embed_bitcode(cgcx, llcx, llmod, None);
709 time_ext(config.time_passes, None, &format!("codegen passes [{}]", module_name.unwrap()),
710 || -> Result<(), FatalError> {
712 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
713 let out = path2cstr(&out);
715 extern "C" fn demangle_callback(input_ptr: *const c_char,
717 output_ptr: *mut c_char,
718 output_len: size_t) -> size_t {
720 slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
723 let input = match str::from_utf8(input) {
728 let output = unsafe {
729 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
731 let mut cursor = io::Cursor::new(output);
733 let demangled = match rustc_demangle::try_demangle(input) {
738 if let Err(_) = write!(cursor, "{:#}", demangled) {
739 // Possible only if provided buffer is not big enough
743 cursor.position() as size_t
746 with_codegen(tm, llmod, config.no_builtins, |cpm| {
747 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
748 llvm::LLVMDisposePassManager(cpm);
750 timeline.record("ir");
753 if config.emit_asm || asm_to_obj {
754 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
756 // We can't use the same module for asm and binary output, because that triggers
757 // various errors like invalid IR or broken binaries, so we might have to clone the
758 // module to produce the asm output
759 let llmod = if config.emit_obj {
760 llvm::LLVMCloneModule(llmod)
764 with_codegen(tm, llmod, config.no_builtins, |cpm| {
765 write_output_file(diag_handler, tm, cpm, llmod, &path,
766 llvm::FileType::AssemblyFile)
768 timeline.record("asm");
772 with_codegen(tm, llmod, config.no_builtins, |cpm| {
773 write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
774 llvm::FileType::ObjectFile)
776 timeline.record("obj");
777 } else if asm_to_obj {
778 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
779 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
780 timeline.record("asm_to_obj");
782 if !config.emit_asm && !cgcx.save_temps {
783 drop(fs::remove_file(&assembly));
791 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
792 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
793 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
798 debug!("removing_bitcode {:?}", bc_out);
799 if let Err(e) = fs::remove_file(&bc_out) {
800 diag_handler.err(&format!("failed to remove bitcode: {}", e));
806 Ok(module.into_compiled_module(config.emit_obj,
808 config.emit_bc_compressed,
809 &cgcx.output_filenames))
812 /// Embed the bitcode of an LLVM module in the LLVM module itself.
814 /// This is done primarily for iOS where it appears to be standard to compile C
815 /// code at least with `-fembed-bitcode` which creates two sections in the
818 /// * __LLVM,__bitcode
819 /// * __LLVM,__cmdline
821 /// It appears *both* of these sections are necessary to get the linker to
822 /// recognize what's going on. For us though we just always throw in an empty
825 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
826 /// embed an empty section.
828 /// Basically all of this is us attempting to follow in the footsteps of clang
829 /// on iOS. See #35968 for lots more info.
830 unsafe fn embed_bitcode(cgcx: &CodegenContext,
831 llcx: &llvm::Context,
832 llmod: &llvm::Module,
833 bitcode: Option<&[u8]>) {
834 let llconst = C_bytes_in_context(llcx, bitcode.unwrap_or(&[]));
835 let llglobal = llvm::LLVMAddGlobal(
838 "rustc.embedded.module\0".as_ptr() as *const _,
840 llvm::LLVMSetInitializer(llglobal, llconst);
842 let is_apple = cgcx.opts.target_triple.triple().contains("-ios") ||
843 cgcx.opts.target_triple.triple().contains("-darwin");
845 let section = if is_apple {
850 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
851 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
852 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
854 let llconst = C_bytes_in_context(llcx, &[]);
855 let llglobal = llvm::LLVMAddGlobal(
858 "rustc.embedded.cmdline\0".as_ptr() as *const _,
860 llvm::LLVMSetInitializer(llglobal, llconst);
861 let section = if is_apple {
866 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
867 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
870 pub(crate) struct CompiledModules {
871 pub modules: Vec<CompiledModule>,
872 pub metadata_module: CompiledModule,
873 pub allocator_module: Option<CompiledModule>,
876 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
877 sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
878 sess.opts.output_types.contains_key(&OutputType::Exe)
881 pub fn start_async_codegen(tcx: TyCtxt,
882 time_graph: Option<TimeGraph>,
884 metadata: EncodedMetadata,
885 coordinator_receive: Receiver<Box<dyn Any + Send>>,
889 let crate_name = tcx.crate_name(LOCAL_CRATE);
890 let no_builtins = attr::contains_name(&tcx.hir.krate().attrs, "no_builtins");
891 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir.krate().attrs,
892 "windows_subsystem");
893 let windows_subsystem = subsystem.map(|subsystem| {
894 if subsystem != "windows" && subsystem != "console" {
895 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
896 `windows` and `console` are allowed",
899 subsystem.to_string()
902 let linker_info = LinkerInfo::new(tcx);
903 let crate_info = CrateInfo::new(tcx);
905 // Figure out what we actually need to build.
906 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
907 let mut metadata_config = ModuleConfig::new(vec![]);
908 let mut allocator_config = ModuleConfig::new(vec![]);
910 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
912 Sanitizer::Address => {
913 modules_config.passes.push("asan".to_owned());
914 modules_config.passes.push("asan-module".to_owned());
916 Sanitizer::Memory => {
917 modules_config.passes.push("msan".to_owned())
919 Sanitizer::Thread => {
920 modules_config.passes.push("tsan".to_owned())
926 if sess.opts.debugging_opts.profile {
927 modules_config.passes.push("insert-gcov-profiling".to_owned())
930 modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
931 modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
933 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
934 modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
936 // Save all versions of the bytecode if we're saving our temporaries.
937 if sess.opts.cg.save_temps {
938 modules_config.emit_no_opt_bc = true;
939 modules_config.emit_bc = true;
940 modules_config.emit_lto_bc = true;
941 metadata_config.emit_bc = true;
942 allocator_config.emit_bc = true;
945 // Emit compressed bitcode files for the crate if we're emitting an rlib.
946 // Whenever an rlib is created, the bitcode is inserted into the archive in
947 // order to allow LTO against it.
948 if need_crate_bitcode_for_rlib(sess) {
949 modules_config.emit_bc_compressed = true;
950 allocator_config.emit_bc_compressed = true;
953 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
954 tcx.sess.target.target.options.no_integrated_as;
956 for output_type in sess.opts.output_types.keys() {
958 OutputType::Bitcode => { modules_config.emit_bc = true; }
959 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
960 OutputType::Assembly => {
961 modules_config.emit_asm = true;
962 // If we're not using the LLVM assembler, this function
963 // could be invoked specially with output_type_assembly, so
964 // in this case we still want the metadata object file.
965 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
966 metadata_config.emit_obj = true;
967 allocator_config.emit_obj = true;
970 OutputType::Object => { modules_config.emit_obj = true; }
971 OutputType::Metadata => { metadata_config.emit_obj = true; }
973 modules_config.emit_obj = true;
974 metadata_config.emit_obj = true;
975 allocator_config.emit_obj = true;
977 OutputType::Mir => {}
978 OutputType::DepInfo => {}
982 modules_config.set_flags(sess, no_builtins);
983 metadata_config.set_flags(sess, no_builtins);
984 allocator_config.set_flags(sess, no_builtins);
986 // Exclude metadata and allocator modules from time_passes output, since
987 // they throw off the "LLVM passes" measurement.
988 metadata_config.time_passes = false;
989 allocator_config.time_passes = false;
991 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
992 let (codegen_worker_send, codegen_worker_receive) = channel();
994 let coordinator_thread = start_executing_work(tcx,
1000 sess.jobserver.clone(),
1002 Arc::new(modules_config),
1003 Arc::new(metadata_config),
1004 Arc::new(allocator_config));
1015 coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
1016 codegen_worker_receive,
1017 shared_emitter_main,
1018 future: coordinator_thread,
1019 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1023 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
1025 compiled_modules: &CompiledModules
1026 ) -> FxHashMap<WorkProductId, WorkProduct> {
1027 let mut work_products = FxHashMap::default();
1029 if sess.opts.incremental.is_none() {
1030 return work_products;
1033 for module in compiled_modules.modules.iter() {
1034 let mut files = vec![];
1036 if let Some(ref path) = module.object {
1037 files.push((WorkProductFileKind::Object, path.clone()));
1039 if let Some(ref path) = module.bytecode {
1040 files.push((WorkProductFileKind::Bytecode, path.clone()));
1042 if let Some(ref path) = module.bytecode_compressed {
1043 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
1046 if let Some((id, product)) =
1047 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
1048 work_products.insert(id, product);
1055 fn produce_final_output_artifacts(sess: &Session,
1056 compiled_modules: &CompiledModules,
1057 crate_output: &OutputFilenames) {
1058 let mut user_wants_bitcode = false;
1059 let mut user_wants_objects = false;
1061 // Produce final compile outputs.
1062 let copy_gracefully = |from: &Path, to: &Path| {
1063 if let Err(e) = fs::copy(from, to) {
1064 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
1068 let copy_if_one_unit = |output_type: OutputType,
1069 keep_numbered: bool| {
1070 if compiled_modules.modules.len() == 1 {
1071 // 1) Only one codegen unit. In this case it's no difficulty
1072 // to copy `foo.0.x` to `foo.x`.
1073 let module_name = Some(&compiled_modules.modules[0].name[..]);
1074 let path = crate_output.temp_path(output_type, module_name);
1075 copy_gracefully(&path,
1076 &crate_output.path(output_type));
1077 if !sess.opts.cg.save_temps && !keep_numbered {
1078 // The user just wants `foo.x`, not `foo.#module-name#.x`.
1079 remove(sess, &path);
1082 let ext = crate_output.temp_path(output_type, None)
1089 if crate_output.outputs.contains_key(&output_type) {
1090 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
1091 // no good solution for this case, so warn the user.
1092 sess.warn(&format!("ignoring emit path because multiple .{} files \
1093 were produced", ext));
1094 } else if crate_output.single_output_file.is_some() {
1095 // 3) Multiple codegen units, with `-o some_name`. We have
1096 // no good solution for this case, so warn the user.
1097 sess.warn(&format!("ignoring -o because multiple .{} files \
1098 were produced", ext));
1100 // 4) Multiple codegen units, but no explicit name. We
1101 // just leave the `foo.0.x` files in place.
1102 // (We don't have to do any work in this case.)
1107 // Flag to indicate whether the user explicitly requested bitcode.
1108 // Otherwise, we produced it only as a temporary output, and will need
1109 // to get rid of it.
1110 for output_type in crate_output.outputs.keys() {
1111 match *output_type {
1112 OutputType::Bitcode => {
1113 user_wants_bitcode = true;
1114 // Copy to .bc, but always keep the .0.bc. There is a later
1115 // check to figure out if we should delete .0.bc files, or keep
1116 // them for making an rlib.
1117 copy_if_one_unit(OutputType::Bitcode, true);
1119 OutputType::LlvmAssembly => {
1120 copy_if_one_unit(OutputType::LlvmAssembly, false);
1122 OutputType::Assembly => {
1123 copy_if_one_unit(OutputType::Assembly, false);
1125 OutputType::Object => {
1126 user_wants_objects = true;
1127 copy_if_one_unit(OutputType::Object, true);
1130 OutputType::Metadata |
1132 OutputType::DepInfo => {}
1136 // Clean up unwanted temporary files.
1138 // We create the following files by default:
1139 // - #crate#.#module-name#.bc
1140 // - #crate#.#module-name#.o
1141 // - #crate#.crate.metadata.bc
1142 // - #crate#.crate.metadata.o
1143 // - #crate#.o (linked from crate.##.o)
1144 // - #crate#.bc (copied from crate.##.bc)
1145 // We may create additional files if requested by the user (through
1146 // `-C save-temps` or `--emit=` flags).
1148 if !sess.opts.cg.save_temps {
1149 // Remove the temporary .#module-name#.o objects. If the user didn't
1150 // explicitly request bitcode (with --emit=bc), and the bitcode is not
1151 // needed for building an rlib, then we must remove .#module-name#.bc as
1154 // Specific rules for keeping .#module-name#.bc:
1155 // - If the user requested bitcode (`user_wants_bitcode`), and
1156 // codegen_units > 1, then keep it.
1157 // - If the user requested bitcode but codegen_units == 1, then we
1158 // can toss .#module-name#.bc because we copied it to .bc earlier.
1159 // - If we're not building an rlib and the user didn't request
1160 // bitcode, then delete .#module-name#.bc.
1161 // If you change how this works, also update back::link::link_rlib,
1162 // where .#module-name#.bc files are (maybe) deleted after making an
1164 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
1166 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
1168 let keep_numbered_objects = needs_crate_object ||
1169 (user_wants_objects && sess.codegen_units() > 1);
1171 for module in compiled_modules.modules.iter() {
1172 if let Some(ref path) = module.object {
1173 if !keep_numbered_objects {
1178 if let Some(ref path) = module.bytecode {
1179 if !keep_numbered_bitcode {
1185 if !user_wants_bitcode {
1186 if let Some(ref path) = compiled_modules.metadata_module.bytecode {
1187 remove(sess, &path);
1190 if let Some(ref allocator_module) = compiled_modules.allocator_module {
1191 if let Some(ref path) = allocator_module.bytecode {
1198 // We leave the following files around by default:
1200 // - #crate#.crate.metadata.o
1202 // These are used in linking steps and will be cleaned up afterward.
1205 pub(crate) fn dump_incremental_data(codegen_results: &CodegenResults) {
1206 println!("[incremental] Re-using {} out of {} modules",
1207 codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
1208 codegen_results.modules.len());
1212 Optimize(ModuleCodegen),
1213 LTO(lto::LtoModuleCodegen),
1217 fn kind(&self) -> ModuleKind {
1219 WorkItem::Optimize(ref m) => m.kind,
1220 WorkItem::LTO(_) => ModuleKind::Regular,
1224 fn name(&self) -> String {
1226 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
1227 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
1232 enum WorkItemResult {
1233 Compiled(CompiledModule),
1234 NeedsLTO(ModuleCodegen),
1237 fn execute_work_item(cgcx: &CodegenContext,
1238 work_item: WorkItem,
1239 timeline: &mut Timeline)
1240 -> Result<WorkItemResult, FatalError>
1242 let diag_handler = cgcx.create_diag_handler();
1243 let config = cgcx.config(work_item.kind());
1244 let module = match work_item {
1245 WorkItem::Optimize(module) => module,
1246 WorkItem::LTO(mut lto) => {
1248 let module = lto.optimize(cgcx, timeline)?;
1249 let module = codegen(cgcx, &diag_handler, module, config, timeline)?;
1250 return Ok(WorkItemResult::Compiled(module))
1254 let module_name = module.name.clone();
1256 let pre_existing = match module.source {
1257 ModuleSource::Codegened(_) => None,
1258 ModuleSource::Preexisting(ref wp) => Some(wp.clone()),
1261 if let Some(wp) = pre_existing {
1262 let incr_comp_session_dir = cgcx.incr_comp_session_dir
1265 let name = &module.name;
1266 let mut object = None;
1267 let mut bytecode = None;
1268 let mut bytecode_compressed = None;
1269 for (kind, saved_file) in wp.saved_files {
1270 let obj_out = match kind {
1271 WorkProductFileKind::Object => {
1272 let path = cgcx.output_filenames.temp_path(OutputType::Object, Some(name));
1273 object = Some(path.clone());
1276 WorkProductFileKind::Bytecode => {
1277 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(name));
1278 bytecode = Some(path.clone());
1281 WorkProductFileKind::BytecodeCompressed => {
1282 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(name))
1283 .with_extension(RLIB_BYTECODE_EXTENSION);
1284 bytecode_compressed = Some(path.clone());
1288 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
1290 debug!("copying pre-existing module `{}` from {:?} to {}",
1294 match link_or_copy(&source_file, &obj_out) {
1297 diag_handler.err(&format!("unable to copy {} to {}: {}",
1298 source_file.display(),
1304 assert_eq!(object.is_some(), config.emit_obj);
1305 assert_eq!(bytecode.is_some(), config.emit_bc);
1306 assert_eq!(bytecode_compressed.is_some(), config.emit_bc_compressed);
1308 Ok(WorkItemResult::Compiled(CompiledModule {
1309 llmod_id: module.llmod_id.clone(),
1311 kind: ModuleKind::Regular,
1315 bytecode_compressed,
1318 debug!("llvm-optimizing {:?}", module_name);
1321 optimize(cgcx, &diag_handler, &module, config, timeline)?;
1323 // After we've done the initial round of optimizations we need to
1324 // decide whether to synchronously codegen this module or ship it
1325 // back to the coordinator thread for further LTO processing (which
1326 // has to wait for all the initial modules to be optimized).
1328 // Here we dispatch based on the `cgcx.lto` and kind of module we're
1330 let needs_lto = match cgcx.lto {
1333 // Here we've got a full crate graph LTO requested. We ignore
1334 // this, however, if the crate type is only an rlib as there's
1335 // no full crate graph to process, that'll happen later.
1337 // This use case currently comes up primarily for targets that
1338 // require LTO so the request for LTO is always unconditionally
1339 // passed down to the backend, but we don't actually want to do
1340 // anything about it yet until we've got a final product.
1341 Lto::Yes | Lto::Fat | Lto::Thin => {
1342 cgcx.crate_types.len() != 1 ||
1343 cgcx.crate_types[0] != config::CrateType::Rlib
1346 // When we're automatically doing ThinLTO for multi-codegen-unit
1347 // builds we don't actually want to LTO the allocator modules if
1348 // it shows up. This is due to various linker shenanigans that
1349 // we'll encounter later.
1351 // Additionally here's where we also factor in the current LLVM
1352 // version. If it doesn't support ThinLTO we skip this.
1354 module.kind != ModuleKind::Allocator &&
1355 llvm::LLVMRustThinLTOAvailable()
1359 // Metadata modules never participate in LTO regardless of the lto
1361 let needs_lto = needs_lto && module.kind != ModuleKind::Metadata;
1363 // Don't run LTO passes when cross-lang LTO is enabled. The linker
1364 // will do that for us in this case.
1365 let needs_lto = needs_lto &&
1366 !cgcx.opts.debugging_opts.cross_lang_lto.enabled();
1369 Ok(WorkItemResult::NeedsLTO(module))
1371 let module = codegen(cgcx, &diag_handler, module, config, timeline)?;
1372 Ok(WorkItemResult::Compiled(module))
1379 Token(io::Result<Acquired>),
1381 result: ModuleCodegen,
1385 result: Result<CompiledModule, ()>,
1389 llvm_work_item: WorkItem,
1398 code: Option<DiagnosticId>,
1402 #[derive(PartialEq, Clone, Copy, Debug)]
1403 enum MainThreadWorkerState {
1409 fn start_executing_work(tcx: TyCtxt,
1410 crate_info: &CrateInfo,
1411 shared_emitter: SharedEmitter,
1412 codegen_worker_send: Sender<Message>,
1413 coordinator_receive: Receiver<Box<dyn Any + Send>>,
1416 time_graph: Option<TimeGraph>,
1417 modules_config: Arc<ModuleConfig>,
1418 metadata_config: Arc<ModuleConfig>,
1419 allocator_config: Arc<ModuleConfig>)
1420 -> thread::JoinHandle<Result<CompiledModules, ()>> {
1421 let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1422 let sess = tcx.sess;
1424 // Compute the set of symbols we need to retain when doing LTO (if we need to)
1425 let exported_symbols = {
1426 let mut exported_symbols = FxHashMap();
1428 let copy_symbols = |cnum| {
1429 let symbols = tcx.exported_symbols(cnum)
1431 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1439 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1440 Some(Arc::new(exported_symbols))
1442 Lto::Yes | Lto::Fat | Lto::Thin => {
1443 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1444 for &cnum in tcx.crates().iter() {
1445 exported_symbols.insert(cnum, copy_symbols(cnum));
1447 Some(Arc::new(exported_symbols))
1452 // First up, convert our jobserver into a helper thread so we can use normal
1453 // mpsc channels to manage our messages and such.
1454 // After we've requested tokens then we'll, when we can,
1455 // get tokens on `coordinator_receive` which will
1456 // get managed in the main loop below.
1457 let coordinator_send2 = coordinator_send.clone();
1458 let helper = jobserver.into_helper_thread(move |token| {
1459 drop(coordinator_send2.send(Box::new(Message::Token(token))));
1460 }).expect("failed to spawn helper thread");
1462 let mut each_linked_rlib_for_lto = Vec::new();
1463 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1464 if link::ignored_for_lto(sess, crate_info, cnum) {
1467 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1470 let assembler_cmd = if modules_config.no_integrated_as {
1471 // HACK: currently we use linker (gcc) as our assembler
1472 let (name, mut cmd) = get_linker(sess);
1473 cmd.args(&sess.target.target.options.asm_args);
1474 Some(Arc::new(AssemblerCommand {
1482 let cgcx = CodegenContext {
1483 crate_types: sess.crate_types.borrow().clone(),
1484 each_linked_rlib_for_lto,
1486 no_landing_pads: sess.no_landing_pads(),
1487 fewer_names: sess.fewer_names(),
1488 save_temps: sess.opts.cg.save_temps,
1489 opts: Arc::new(sess.opts.clone()),
1490 time_passes: sess.time_passes(),
1492 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1493 remark: sess.opts.cg.remark.clone(),
1495 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1497 diag_emitter: shared_emitter.clone(),
1499 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1500 regular_module_config: modules_config,
1501 metadata_module_config: metadata_config,
1502 allocator_module_config: allocator_config,
1503 tm_factory: target_machine_factory(tcx.sess, false),
1505 msvc_imps_needed: msvc_imps_needed(tcx),
1506 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1507 debuginfo: tcx.sess.opts.debuginfo,
1511 // This is the "main loop" of parallel work happening for parallel codegen.
1512 // It's here that we manage parallelism, schedule work, and work with
1513 // messages coming from clients.
1515 // There are a few environmental pre-conditions that shape how the system
1518 // - Error reporting only can happen on the main thread because that's the
1519 // only place where we have access to the compiler `Session`.
1520 // - LLVM work can be done on any thread.
1521 // - Codegen can only happen on the main thread.
1522 // - Each thread doing substantial work most be in possession of a `Token`
1523 // from the `Jobserver`.
1524 // - The compiler process always holds one `Token`. Any additional `Tokens`
1525 // have to be requested from the `Jobserver`.
1529 // The error reporting restriction is handled separately from the rest: We
1530 // set up a `SharedEmitter` the holds an open channel to the main thread.
1531 // When an error occurs on any thread, the shared emitter will send the
1532 // error message to the receiver main thread (`SharedEmitterMain`). The
1533 // main thread will periodically query this error message queue and emit
1534 // any error messages it has received. It might even abort compilation if
1535 // has received a fatal error. In this case we rely on all other threads
1536 // being torn down automatically with the main thread.
1537 // Since the main thread will often be busy doing codegen work, error
1538 // reporting will be somewhat delayed, since the message queue can only be
1539 // checked in between to work packages.
1541 // Work Processing Infrastructure
1542 // ==============================
1543 // The work processing infrastructure knows three major actors:
1545 // - the coordinator thread,
1546 // - the main thread, and
1547 // - LLVM worker threads
1549 // The coordinator thread is running a message loop. It instructs the main
1550 // thread about what work to do when, and it will spawn off LLVM worker
1551 // threads as open LLVM WorkItems become available.
1553 // The job of the main thread is to codegen CGUs into LLVM work package
1554 // (since the main thread is the only thread that can do this). The main
1555 // thread will block until it receives a message from the coordinator, upon
1556 // which it will codegen one CGU, send it to the coordinator and block
1557 // again. This way the coordinator can control what the main thread is
1560 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1561 // available, it will spawn off a new LLVM worker thread and let it process
1562 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1563 // it will just shut down, which also frees all resources associated with
1564 // the given LLVM module, and sends a message to the coordinator that the
1565 // has been completed.
1569 // The scheduler's goal is to minimize the time it takes to complete all
1570 // work there is, however, we also want to keep memory consumption low
1571 // if possible. These two goals are at odds with each other: If memory
1572 // consumption were not an issue, we could just let the main thread produce
1573 // LLVM WorkItems at full speed, assuring maximal utilization of
1574 // Tokens/LLVM worker threads. However, since codegen usual is faster
1575 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1576 // WorkItem potentially holds on to a substantial amount of memory.
1578 // So the actual goal is to always produce just enough LLVM WorkItems as
1579 // not to starve our LLVM worker threads. That means, once we have enough
1580 // WorkItems in our queue, we can block the main thread, so it does not
1581 // produce more until we need them.
1583 // Doing LLVM Work on the Main Thread
1584 // ----------------------------------
1585 // Since the main thread owns the compiler processes implicit `Token`, it is
1586 // wasteful to keep it blocked without doing any work. Therefore, what we do
1587 // in this case is: We spawn off an additional LLVM worker thread that helps
1588 // reduce the queue. The work it is doing corresponds to the implicit
1589 // `Token`. The coordinator will mark the main thread as being busy with
1590 // LLVM work. (The actual work happens on another OS thread but we just care
1591 // about `Tokens`, not actual threads).
1593 // When any LLVM worker thread finishes while the main thread is marked as
1594 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1595 // of the just finished thread to the LLVM worker thread that is working on
1596 // behalf of the main thread's implicit Token, thus freeing up the main
1597 // thread again. The coordinator can then again decide what the main thread
1598 // should do. This allows the coordinator to make decisions at more points
1601 // Striking a Balance between Throughput and Memory Consumption
1602 // ------------------------------------------------------------
1603 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1604 // memory consumption as low as possible, are in conflict with each other,
1605 // we have to find a trade off between them. Right now, the goal is to keep
1606 // all workers busy, which means that no worker should find the queue empty
1607 // when it is ready to start.
1608 // How do we do achieve this? Good question :) We actually never know how
1609 // many `Tokens` are potentially available so it's hard to say how much to
1610 // fill up the queue before switching the main thread to LLVM work. Also we
1611 // currently don't have a means to estimate how long a running LLVM worker
1612 // will still be busy with it's current WorkItem. However, we know the
1613 // maximal count of available Tokens that makes sense (=the number of CPU
1614 // cores), so we can take a conservative guess. The heuristic we use here
1615 // is implemented in the `queue_full_enough()` function.
1617 // Some Background on Jobservers
1618 // -----------------------------
1619 // It's worth also touching on the management of parallelism here. We don't
1620 // want to just spawn a thread per work item because while that's optimal
1621 // parallelism it may overload a system with too many threads or violate our
1622 // configuration for the maximum amount of cpu to use for this process. To
1623 // manage this we use the `jobserver` crate.
1625 // Job servers are an artifact of GNU make and are used to manage
1626 // parallelism between processes. A jobserver is a glorified IPC semaphore
1627 // basically. Whenever we want to run some work we acquire the semaphore,
1628 // and whenever we're done with that work we release the semaphore. In this
1629 // manner we can ensure that the maximum number of parallel workers is
1630 // capped at any one point in time.
1632 // LTO and the coordinator thread
1633 // ------------------------------
1635 // The final job the coordinator thread is responsible for is managing LTO
1636 // and how that works. When LTO is requested what we'll to is collect all
1637 // optimized LLVM modules into a local vector on the coordinator. Once all
1638 // modules have been codegened and optimized we hand this to the `lto`
1639 // module for further optimization. The `lto` module will return back a list
1640 // of more modules to work on, which the coordinator will continue to spawn
1643 // Each LLVM module is automatically sent back to the coordinator for LTO if
1644 // necessary. There's already optimizations in place to avoid sending work
1645 // back to the coordinator if LTO isn't requested.
1646 return thread::spawn(move || {
1647 // We pretend to be within the top-level LLVM time-passes task here:
1650 let max_workers = ::num_cpus::get();
1651 let mut worker_id_counter = 0;
1652 let mut free_worker_ids = Vec::new();
1653 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1654 if let Some(id) = free_worker_ids.pop() {
1657 let id = worker_id_counter;
1658 worker_id_counter += 1;
1663 // This is where we collect codegen units that have gone all the way
1664 // through codegen and LLVM.
1665 let mut compiled_modules = vec![];
1666 let mut compiled_metadata_module = None;
1667 let mut compiled_allocator_module = None;
1668 let mut needs_lto = Vec::new();
1669 let mut started_lto = false;
1671 // This flag tracks whether all items have gone through codegens
1672 let mut codegen_done = false;
1674 // This is the queue of LLVM work items that still need processing.
1675 let mut work_items = Vec::<(WorkItem, u64)>::new();
1677 // This are the Jobserver Tokens we currently hold. Does not include
1678 // the implicit Token the compiler process owns no matter what.
1679 let mut tokens = Vec::new();
1681 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1682 let mut running = 0;
1684 let mut llvm_start_time = None;
1686 // Run the message loop while there's still anything that needs message
1688 while !codegen_done ||
1689 work_items.len() > 0 ||
1691 needs_lto.len() > 0 ||
1692 main_thread_worker_state != MainThreadWorkerState::Idle {
1694 // While there are still CGUs to be codegened, the coordinator has
1695 // to decide how to utilize the compiler processes implicit Token:
1696 // For codegenning more CGU or for running them through LLVM.
1698 if main_thread_worker_state == MainThreadWorkerState::Idle {
1699 if !queue_full_enough(work_items.len(), running, max_workers) {
1700 // The queue is not full enough, codegen more items:
1701 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1702 panic!("Could not send Message::CodegenItem to main thread")
1704 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1706 // The queue is full enough to not let the worker
1707 // threads starve. Use the implicit Token to do some
1709 let (item, _) = work_items.pop()
1710 .expect("queue empty - queue_full_enough() broken?");
1711 let cgcx = CodegenContext {
1712 worker: get_worker_id(&mut free_worker_ids),
1715 maybe_start_llvm_timer(cgcx.config(item.kind()),
1716 &mut llvm_start_time);
1717 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1718 spawn_work(cgcx, item);
1722 // If we've finished everything related to normal codegen
1723 // then it must be the case that we've got some LTO work to do.
1724 // Perform the serial work here of figuring out what we're
1725 // going to LTO and then push a bunch of work items onto our
1727 if work_items.len() == 0 &&
1729 main_thread_worker_state == MainThreadWorkerState::Idle {
1730 assert!(!started_lto);
1731 assert!(needs_lto.len() > 0);
1733 let modules = mem::replace(&mut needs_lto, Vec::new());
1734 for (work, cost) in generate_lto_work(&cgcx, modules) {
1735 let insertion_index = work_items
1736 .binary_search_by_key(&cost, |&(_, cost)| cost)
1737 .unwrap_or_else(|e| e);
1738 work_items.insert(insertion_index, (work, cost));
1739 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1740 helper.request_token();
1745 // In this branch, we know that everything has been codegened,
1746 // so it's just a matter of determining whether the implicit
1747 // Token is free to use for LLVM work.
1748 match main_thread_worker_state {
1749 MainThreadWorkerState::Idle => {
1750 if let Some((item, _)) = work_items.pop() {
1751 let cgcx = CodegenContext {
1752 worker: get_worker_id(&mut free_worker_ids),
1755 maybe_start_llvm_timer(cgcx.config(item.kind()),
1756 &mut llvm_start_time);
1757 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1758 spawn_work(cgcx, item);
1760 // There is no unstarted work, so let the main thread
1761 // take over for a running worker. Otherwise the
1762 // implicit token would just go to waste.
1763 // We reduce the `running` counter by one. The
1764 // `tokens.truncate()` below will take care of
1765 // giving the Token back.
1766 debug_assert!(running > 0);
1768 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1771 MainThreadWorkerState::Codegenning => {
1772 bug!("codegen worker should not be codegenning after \
1773 codegen was already completed")
1775 MainThreadWorkerState::LLVMing => {
1776 // Already making good use of that token
1781 // Spin up what work we can, only doing this while we've got available
1782 // parallelism slots and work left to spawn.
1783 while work_items.len() > 0 && running < tokens.len() {
1784 let (item, _) = work_items.pop().unwrap();
1786 maybe_start_llvm_timer(cgcx.config(item.kind()),
1787 &mut llvm_start_time);
1789 let cgcx = CodegenContext {
1790 worker: get_worker_id(&mut free_worker_ids),
1794 spawn_work(cgcx, item);
1798 // Relinquish accidentally acquired extra tokens
1799 tokens.truncate(running);
1801 let msg = coordinator_receive.recv().unwrap();
1802 match *msg.downcast::<Message>().ok().unwrap() {
1803 // Save the token locally and the next turn of the loop will use
1804 // this to spawn a new unit of work, or it may get dropped
1805 // immediately if we have no more work to spawn.
1806 Message::Token(token) => {
1811 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1812 // If the main thread token is used for LLVM work
1813 // at the moment, we turn that thread into a regular
1814 // LLVM worker thread, so the main thread is free
1815 // to react to codegen demand.
1816 main_thread_worker_state = MainThreadWorkerState::Idle;
1821 let msg = &format!("failed to acquire jobserver token: {}", e);
1822 shared_emitter.fatal(msg);
1823 // Exit the coordinator thread
1829 Message::CodegenDone { llvm_work_item, cost } => {
1830 // We keep the queue sorted by estimated processing cost,
1831 // so that more expensive items are processed earlier. This
1832 // is good for throughput as it gives the main thread more
1833 // time to fill up the queue and it avoids scheduling
1834 // expensive items to the end.
1835 // Note, however, that this is not ideal for memory
1836 // consumption, as LLVM module sizes are not evenly
1838 let insertion_index =
1839 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1840 let insertion_index = match insertion_index {
1841 Ok(idx) | Err(idx) => idx
1843 work_items.insert(insertion_index, (llvm_work_item, cost));
1845 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1846 helper.request_token();
1848 assert_eq!(main_thread_worker_state,
1849 MainThreadWorkerState::Codegenning);
1850 main_thread_worker_state = MainThreadWorkerState::Idle;
1853 Message::CodegenComplete => {
1854 codegen_done = true;
1855 assert_eq!(main_thread_worker_state,
1856 MainThreadWorkerState::Codegenning);
1857 main_thread_worker_state = MainThreadWorkerState::Idle;
1860 // If a thread exits successfully then we drop a token associated
1861 // with that worker and update our `running` count. We may later
1862 // re-acquire a token to continue running more work. We may also not
1863 // actually drop a token here if the worker was running with an
1864 // "ephemeral token"
1866 // Note that if the thread failed that means it panicked, so we
1867 // abort immediately.
1868 Message::Done { result: Ok(compiled_module), worker_id } => {
1869 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1870 main_thread_worker_state = MainThreadWorkerState::Idle;
1875 free_worker_ids.push(worker_id);
1877 match compiled_module.kind {
1878 ModuleKind::Regular => {
1879 compiled_modules.push(compiled_module);
1881 ModuleKind::Metadata => {
1882 assert!(compiled_metadata_module.is_none());
1883 compiled_metadata_module = Some(compiled_module);
1885 ModuleKind::Allocator => {
1886 assert!(compiled_allocator_module.is_none());
1887 compiled_allocator_module = Some(compiled_module);
1891 Message::NeedsLTO { result, worker_id } => {
1892 assert!(!started_lto);
1893 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1894 main_thread_worker_state = MainThreadWorkerState::Idle;
1899 free_worker_ids.push(worker_id);
1900 needs_lto.push(result);
1902 Message::Done { result: Err(()), worker_id: _ } => {
1903 shared_emitter.fatal("aborting due to worker thread failure");
1904 // Exit the coordinator thread
1907 Message::CodegenItem => {
1908 bug!("the coordinator should not receive codegen requests")
1913 if let Some(llvm_start_time) = llvm_start_time {
1914 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
1915 // This is the top-level timing for all of LLVM, set the time-depth
1918 print_time_passes_entry(cgcx.time_passes,
1923 // Regardless of what order these modules completed in, report them to
1924 // the backend in the same order every time to ensure that we're handing
1925 // out deterministic results.
1926 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1928 let compiled_metadata_module = compiled_metadata_module
1929 .expect("Metadata module not compiled?");
1931 Ok(CompiledModules {
1932 modules: compiled_modules,
1933 metadata_module: compiled_metadata_module,
1934 allocator_module: compiled_allocator_module,
1938 // A heuristic that determines if we have enough LLVM WorkItems in the
1939 // queue so that the main thread can do LLVM work instead of codegen
1940 fn queue_full_enough(items_in_queue: usize,
1941 workers_running: usize,
1942 max_workers: usize) -> bool {
1944 items_in_queue > 0 &&
1945 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1948 fn maybe_start_llvm_timer(config: &ModuleConfig,
1949 llvm_start_time: &mut Option<Instant>) {
1950 // We keep track of the -Ztime-passes output manually,
1951 // since the closure-based interface does not fit well here.
1952 if config.time_passes {
1953 if llvm_start_time.is_none() {
1954 *llvm_start_time = Some(Instant::now());
1960 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1961 pub const CODEGEN_WORKER_TIMELINE: time_graph::TimelineId =
1962 time_graph::TimelineId(CODEGEN_WORKER_ID);
1963 pub const CODEGEN_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1964 time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
1965 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1966 time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
1968 fn spawn_work(cgcx: CodegenContext, work: WorkItem) {
1969 let depth = time_depth();
1971 thread::spawn(move || {
1972 set_time_depth(depth);
1974 // Set up a destructor which will fire off a message that we're done as
1977 coordinator_send: Sender<Box<dyn Any + Send>>,
1978 result: Option<WorkItemResult>,
1981 impl Drop for Bomb {
1982 fn drop(&mut self) {
1983 let worker_id = self.worker_id;
1984 let msg = match self.result.take() {
1985 Some(WorkItemResult::Compiled(m)) => {
1986 Message::Done { result: Ok(m), worker_id }
1988 Some(WorkItemResult::NeedsLTO(m)) => {
1989 Message::NeedsLTO { result: m, worker_id }
1991 None => Message::Done { result: Err(()), worker_id }
1993 drop(self.coordinator_send.send(Box::new(msg)));
1997 let mut bomb = Bomb {
1998 coordinator_send: cgcx.coordinator_send.clone(),
2000 worker_id: cgcx.worker,
2003 // Execute the work itself, and if it finishes successfully then flag
2004 // ourselves as a success as well.
2006 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
2007 // as a diagnostic was already sent off to the main thread - just
2008 // surface that there was an error in this worker.
2010 let timeline = cgcx.time_graph.as_ref().map(|tg| {
2011 tg.start(time_graph::TimelineId(cgcx.worker),
2012 LLVM_WORK_PACKAGE_KIND,
2015 let mut timeline = timeline.unwrap_or(Timeline::noop());
2016 execute_work_item(&cgcx, work, &mut timeline).ok()
2021 pub fn run_assembler(cgcx: &CodegenContext, handler: &Handler, assembly: &Path, object: &Path) {
2022 let assembler = cgcx.assembler_cmd
2024 .expect("cgcx.assembler_cmd is missing?");
2026 let pname = &assembler.name;
2027 let mut cmd = assembler.cmd.clone();
2028 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
2029 debug!("{:?}", cmd);
2031 match cmd.output() {
2033 if !prog.status.success() {
2034 let mut note = prog.stderr.clone();
2035 note.extend_from_slice(&prog.stdout);
2037 handler.struct_err(&format!("linking with `{}` failed: {}",
2040 .note(&format!("{:?}", &cmd))
2041 .note(str::from_utf8(¬e[..]).unwrap())
2043 handler.abort_if_errors();
2047 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
2048 handler.abort_if_errors();
2053 pub unsafe fn with_llvm_pmb(llmod: &llvm::Module,
2054 config: &ModuleConfig,
2055 opt_level: llvm::CodeGenOptLevel,
2056 prepare_for_thin_lto: bool,
2057 f: &mut dyn FnMut(&llvm::PassManagerBuilder)) {
2060 // Create the PassManagerBuilder for LLVM. We configure it with
2061 // reasonable defaults and prepare it to actually populate the pass
2063 let builder = llvm::LLVMPassManagerBuilderCreate();
2064 let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
2065 let inline_threshold = config.inline_threshold;
2067 let pgo_gen_path = config.pgo_gen.as_ref().map(|s| {
2068 let s = if s.is_empty() { "default_%m.profraw" } else { s };
2069 CString::new(s.as_bytes()).unwrap()
2072 let pgo_use_path = if config.pgo_use.is_empty() {
2075 Some(CString::new(config.pgo_use.as_bytes()).unwrap())
2078 llvm::LLVMRustConfigurePassManagerBuilder(
2081 config.merge_functions,
2082 config.vectorize_slp,
2083 config.vectorize_loop,
2084 prepare_for_thin_lto,
2085 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2086 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2089 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
2091 if opt_size != llvm::CodeGenOptSizeNone {
2092 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
2095 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
2097 // Here we match what clang does (kinda). For O0 we only inline
2098 // always-inline functions (but don't add lifetime intrinsics), at O1 we
2099 // inline with lifetime intrinsics, and O2+ we add an inliner with a
2100 // thresholds copied from clang.
2101 match (opt_level, opt_size, inline_threshold) {
2103 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
2105 (llvm::CodeGenOptLevel::Aggressive, ..) => {
2106 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
2108 (_, llvm::CodeGenOptSizeDefault, _) => {
2109 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
2111 (_, llvm::CodeGenOptSizeAggressive, _) => {
2112 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
2114 (llvm::CodeGenOptLevel::None, ..) => {
2115 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
2117 (llvm::CodeGenOptLevel::Less, ..) => {
2118 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
2120 (llvm::CodeGenOptLevel::Default, ..) => {
2121 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
2123 (llvm::CodeGenOptLevel::Other, ..) => {
2124 bug!("CodeGenOptLevel::Other selected")
2129 llvm::LLVMPassManagerBuilderDispose(builder);
2133 enum SharedEmitterMessage {
2134 Diagnostic(Diagnostic),
2135 InlineAsmError(u32, String),
2141 pub struct SharedEmitter {
2142 sender: Sender<SharedEmitterMessage>,
2145 pub struct SharedEmitterMain {
2146 receiver: Receiver<SharedEmitterMessage>,
2149 impl SharedEmitter {
2150 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
2151 let (sender, receiver) = channel();
2153 (SharedEmitter { sender }, SharedEmitterMain { receiver })
2156 fn inline_asm_error(&self, cookie: u32, msg: String) {
2157 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
2160 fn fatal(&self, msg: &str) {
2161 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2165 impl Emitter for SharedEmitter {
2166 fn emit(&mut self, db: &DiagnosticBuilder) {
2167 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2169 code: db.code.clone(),
2172 for child in &db.children {
2173 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2174 msg: child.message(),
2179 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
2183 impl SharedEmitterMain {
2184 pub fn check(&self, sess: &Session, blocking: bool) {
2186 let message = if blocking {
2187 match self.receiver.recv() {
2188 Ok(message) => Ok(message),
2192 match self.receiver.try_recv() {
2193 Ok(message) => Ok(message),
2199 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2200 let handler = sess.diagnostic();
2203 handler.emit_with_code(&MultiSpan::new(),
2209 handler.emit(&MultiSpan::new(),
2215 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
2216 match Mark::from_u32(cookie).expn_info() {
2217 Some(ei) => sess.span_err(ei.call_site, &msg),
2218 None => sess.err(&msg),
2221 Ok(SharedEmitterMessage::AbortIfErrors) => {
2222 sess.abort_if_errors();
2224 Ok(SharedEmitterMessage::Fatal(msg)) => {
2236 pub struct OngoingCodegen {
2239 metadata: EncodedMetadata,
2240 windows_subsystem: Option<String>,
2241 linker_info: LinkerInfo,
2242 crate_info: CrateInfo,
2243 time_graph: Option<TimeGraph>,
2244 coordinator_send: Sender<Box<dyn Any + Send>>,
2245 codegen_worker_receive: Receiver<Message>,
2246 shared_emitter_main: SharedEmitterMain,
2247 future: thread::JoinHandle<Result<CompiledModules, ()>>,
2248 output_filenames: Arc<OutputFilenames>,
2251 impl OngoingCodegen {
2255 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
2256 self.shared_emitter_main.check(sess, true);
2257 let compiled_modules = match self.future.join() {
2258 Ok(Ok(compiled_modules)) => compiled_modules,
2260 sess.abort_if_errors();
2261 panic!("expected abort due to worker thread errors")
2264 sess.fatal("Error during codegen/LLVM phase.");
2268 sess.abort_if_errors();
2270 if let Some(time_graph) = self.time_graph {
2271 time_graph.dump(&format!("{}-timings", self.crate_name));
2274 let work_products = copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
2277 produce_final_output_artifacts(sess,
2279 &self.output_filenames);
2281 // FIXME: time_llvm_passes support - does this use a global context or
2283 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
2284 unsafe { llvm::LLVMRustPrintPassTimings(); }
2288 crate_name: self.crate_name,
2290 metadata: self.metadata,
2291 windows_subsystem: self.windows_subsystem,
2292 linker_info: self.linker_info,
2293 crate_info: self.crate_info,
2295 modules: compiled_modules.modules,
2296 allocator_module: compiled_modules.allocator_module,
2297 metadata_module: compiled_modules.metadata_module,
2301 pub(crate) fn submit_pre_codegened_module_to_llvm(&self,
2303 module: ModuleCodegen) {
2304 self.wait_for_signal_to_codegen_item();
2305 self.check_for_errors(tcx.sess);
2307 // These are generally cheap and won't through off scheduling.
2309 submit_codegened_module_to_llvm(tcx, module, cost);
2312 pub fn codegen_finished(&self, tcx: TyCtxt) {
2313 self.wait_for_signal_to_codegen_item();
2314 self.check_for_errors(tcx.sess);
2315 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete)));
2318 pub fn check_for_errors(&self, sess: &Session) {
2319 self.shared_emitter_main.check(sess, false);
2322 pub fn wait_for_signal_to_codegen_item(&self) {
2323 match self.codegen_worker_receive.recv() {
2324 Ok(Message::CodegenItem) => {
2327 Ok(_) => panic!("unexpected message"),
2329 // One of the LLVM threads must have panicked, fall through so
2330 // error handling can be reached.
2336 pub(crate) fn submit_codegened_module_to_llvm(tcx: TyCtxt,
2337 module: ModuleCodegen,
2339 let llvm_work_item = WorkItem::Optimize(module);
2340 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2346 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
2347 tcx.sess.target.target.options.is_like_msvc &&
2348 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib)
2351 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2352 // This is required to satisfy `dllimport` references to static data in .rlibs
2353 // when using MSVC linker. We do this only for data, as linker can fix up
2354 // code references on its own.
2355 // See #26591, #27438
2356 fn create_msvc_imps(cgcx: &CodegenContext, llcx: &llvm::Context, llmod: &llvm::Module) {
2357 if !cgcx.msvc_imps_needed {
2360 // The x86 ABI seems to require that leading underscores are added to symbol
2361 // names, so we need an extra underscore on 32-bit. There's also a leading
2362 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2363 // underscores added in front).
2364 let prefix = if cgcx.target_pointer_width == "32" {
2370 let i8p_ty = Type::i8p_llcx(llcx);
2371 let globals = base::iter_globals(llmod)
2373 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
2374 llvm::LLVMIsDeclaration(val) == 0
2377 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2378 let mut imp_name = prefix.as_bytes().to_vec();
2379 imp_name.extend(name.to_bytes());
2380 let imp_name = CString::new(imp_name).unwrap();
2383 .collect::<Vec<_>>();
2384 for (imp_name, val) in globals {
2385 let imp = llvm::LLVMAddGlobal(llmod,
2387 imp_name.as_ptr() as *const _);
2388 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
2389 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);