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, ThinBuffer, SerializedModule};
14 use back::link::{self, get_linker, remove};
18 use rustc_incremental::{copy_cgu_workproducts_to_incr_comp_cache_dir,
19 in_incr_comp_dir, in_incr_comp_dir_sess};
20 use rustc::dep_graph::{WorkProduct, WorkProductId, WorkProductFileKind};
21 use rustc::dep_graph::cgu_reuse_tracker::CguReuseTracker;
22 use rustc::middle::cstore::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};
29 use {CodegenResults, ModuleCodegen, CompiledModule, ModuleKind, // ModuleLlvm,
32 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
33 use rustc::ty::TyCtxt;
34 use rustc::util::common::{time_ext, time_depth, set_time_depth, print_time_passes_entry};
35 use rustc_fs_util::{path2cstr, link_or_copy};
36 use rustc_data_structures::small_c_str::SmallCStr;
37 use rustc_data_structures::svh::Svh;
38 use rustc_codegen_utils::command::Command;
39 use rustc_codegen_utils::linker::LinkerInfo;
40 use rustc_codegen_utils::symbol_export::ExportedSymbols;
41 use errors::{self, Handler, Level, DiagnosticBuilder, FatalError, DiagnosticId};
42 use errors::emitter::{Emitter};
44 use syntax::ext::hygiene::Mark;
45 use syntax_pos::MultiSpan;
46 use syntax_pos::symbol::Symbol;
48 use context::{is_pie_binary, get_reloc_model};
49 use common::{C_bytes_in_context, val_ty};
50 use jobserver::{Client, Acquired};
55 use std::ffi::{CString, CStr};
57 use std::io::{self, Write};
59 use std::path::{Path, PathBuf};
62 use std::sync::mpsc::{channel, Sender, Receiver};
64 use std::time::Instant;
66 use libc::{c_uint, c_void, c_char, size_t};
68 pub const RELOC_MODEL_ARGS : [(&str, llvm::RelocMode); 7] = [
69 ("pic", llvm::RelocMode::PIC),
70 ("static", llvm::RelocMode::Static),
71 ("default", llvm::RelocMode::Default),
72 ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
73 ("ropi", llvm::RelocMode::ROPI),
74 ("rwpi", llvm::RelocMode::RWPI),
75 ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
78 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
79 ("small", llvm::CodeModel::Small),
80 ("kernel", llvm::CodeModel::Kernel),
81 ("medium", llvm::CodeModel::Medium),
82 ("large", llvm::CodeModel::Large),
85 pub const TLS_MODEL_ARGS : [(&str, llvm::ThreadLocalMode); 4] = [
86 ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
87 ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
88 ("initial-exec", llvm::ThreadLocalMode::InitialExec),
89 ("local-exec", llvm::ThreadLocalMode::LocalExec),
92 const PRE_THIN_LTO_BC_EXT: &str = "pre-thin-lto.bc";
94 pub fn llvm_err(handler: &errors::Handler, msg: &str) -> FatalError {
95 match llvm::last_error() {
96 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
97 None => handler.fatal(&msg),
101 pub fn write_output_file(
102 handler: &errors::Handler,
103 target: &'ll llvm::TargetMachine,
104 pm: &llvm::PassManager<'ll>,
105 m: &'ll llvm::Module,
107 file_type: llvm::FileType) -> Result<(), FatalError> {
109 let output_c = path2cstr(output);
110 let result = llvm::LLVMRustWriteOutputFile(target, pm, m, output_c.as_ptr(), file_type);
111 if result.into_result().is_err() {
112 let msg = format!("could not write output to {}", output.display());
113 Err(llvm_err(handler, &msg))
120 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
122 config::OptLevel::No => llvm::CodeGenOptLevel::None,
123 config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
124 config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
125 config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
126 _ => llvm::CodeGenOptLevel::Default,
130 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
132 config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
133 config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
134 _ => llvm::CodeGenOptSizeNone,
138 pub fn create_target_machine(
141 ) -> &'static mut llvm::TargetMachine {
142 target_machine_factory(sess, find_features)().unwrap_or_else(|err| {
143 llvm_err(sess.diagnostic(), &err).raise()
147 // If find_features is true this won't access `sess.crate_types` by assuming
148 // that `is_pie_binary` is false. When we discover LLVM target features
149 // `sess.crate_types` is uninitialized so we cannot access it.
150 pub fn target_machine_factory(sess: &Session, find_features: bool)
151 -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>
153 let reloc_model = get_reloc_model(sess);
155 let opt_level = get_llvm_opt_level(sess.opts.optimize);
156 let use_softfp = sess.opts.cg.soft_float;
158 let ffunction_sections = sess.target.target.options.function_sections;
159 let fdata_sections = ffunction_sections;
161 let code_model_arg = sess.opts.cg.code_model.as_ref().or(
162 sess.target.target.options.code_model.as_ref(),
165 let code_model = match code_model_arg {
167 match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
170 sess.err(&format!("{:?} is not a valid code model",
172 sess.abort_if_errors();
177 None => llvm::CodeModel::None,
180 let features = attributes::llvm_target_features(sess).collect::<Vec<_>>();
181 let mut singlethread = sess.target.target.options.singlethread;
183 // On the wasm target once the `atomics` feature is enabled that means that
184 // we're no longer single-threaded, or otherwise we don't want LLVM to
185 // lower atomic operations to single-threaded operations.
187 sess.target.target.llvm_target.contains("wasm32") &&
188 features.iter().any(|s| *s == "+atomics")
190 singlethread = false;
193 let triple = SmallCStr::new(&sess.target.target.llvm_target);
194 let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
195 let features = features.join(",");
196 let features = CString::new(features).unwrap();
197 let is_pie_binary = !find_features && is_pie_binary(sess);
198 let trap_unreachable = sess.target.target.options.trap_unreachable;
199 let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
201 let asm_comments = sess.asm_comments();
205 llvm::LLVMRustCreateTargetMachine(
206 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
217 emit_stack_size_section,
222 format!("Could not create LLVM TargetMachine for triple: {}",
223 triple.to_str().unwrap())
228 /// Module-specific configuration for `optimize_and_codegen`.
229 pub struct ModuleConfig {
230 /// Names of additional optimization passes to run.
232 /// Some(level) to optimize at a certain level, or None to run
233 /// absolutely no optimizations (used for the metadata module).
234 pub opt_level: Option<llvm::CodeGenOptLevel>,
236 /// Some(level) to optimize binary size, or None to not affect program size.
237 opt_size: Option<llvm::CodeGenOptSize>,
239 pgo_gen: Option<String>,
242 // Flags indicating which outputs to produce.
243 pub emit_pre_thin_lto_bc: bool,
244 emit_no_opt_bc: bool,
246 emit_bc_compressed: bool,
251 // Miscellaneous flags. These are mostly copied from command-line
253 pub verify_llvm_ir: bool,
254 no_prepopulate_passes: bool,
257 vectorize_loop: bool,
259 merge_functions: bool,
260 inline_threshold: Option<usize>,
261 // Instead of creating an object file by doing LLVM codegen, just
262 // make the object file bitcode. Provides easy compatibility with
263 // emscripten's ecc compiler, when used as the linker.
264 obj_is_bitcode: bool,
265 no_integrated_as: bool,
267 embed_bitcode_marker: bool,
271 fn new(passes: Vec<String>) -> ModuleConfig {
278 pgo_use: String::new(),
280 emit_no_opt_bc: false,
281 emit_pre_thin_lto_bc: false,
283 emit_bc_compressed: false,
288 obj_is_bitcode: false,
289 embed_bitcode: false,
290 embed_bitcode_marker: false,
291 no_integrated_as: false,
293 verify_llvm_ir: false,
294 no_prepopulate_passes: false,
297 vectorize_loop: false,
298 vectorize_slp: false,
299 merge_functions: false,
300 inline_threshold: None
304 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
305 self.verify_llvm_ir = sess.verify_llvm_ir();
306 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
307 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
308 self.time_passes = sess.time_passes();
309 self.inline_threshold = sess.opts.cg.inline_threshold;
310 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
311 sess.opts.debugging_opts.cross_lang_lto.enabled();
312 let embed_bitcode = sess.target.target.options.embed_bitcode ||
313 sess.opts.debugging_opts.embed_bitcode;
315 match sess.opts.optimize {
316 config::OptLevel::No |
317 config::OptLevel::Less => {
318 self.embed_bitcode_marker = embed_bitcode;
320 _ => self.embed_bitcode = embed_bitcode,
324 // Copy what clang does by turning on loop vectorization at O2 and
325 // slp vectorization at O3. Otherwise configure other optimization aspects
326 // of this pass manager builder.
327 // Turn off vectorization for emscripten, as it's not very well supported.
328 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
329 (sess.opts.optimize == config::OptLevel::Default ||
330 sess.opts.optimize == config::OptLevel::Aggressive) &&
331 !sess.target.target.options.is_like_emscripten;
333 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
334 sess.opts.optimize == config::OptLevel::Aggressive &&
335 !sess.target.target.options.is_like_emscripten;
337 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
338 sess.opts.optimize == config::OptLevel::Aggressive;
341 pub fn bitcode_needed(&self) -> bool {
342 self.emit_bc || self.obj_is_bitcode
343 || self.emit_bc_compressed || self.embed_bitcode
347 /// Assembler name and command used by codegen when no_integrated_as is enabled
348 struct AssemblerCommand {
353 /// Additional resources used by optimize_and_codegen (not module specific)
355 pub struct CodegenContext {
356 // Resources needed when running LTO
357 pub time_passes: bool,
359 pub no_landing_pads: bool,
360 pub save_temps: bool,
361 pub fewer_names: bool,
362 pub exported_symbols: Option<Arc<ExportedSymbols>>,
363 pub opts: Arc<config::Options>,
364 pub crate_types: Vec<config::CrateType>,
365 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
366 output_filenames: Arc<OutputFilenames>,
367 regular_module_config: Arc<ModuleConfig>,
368 metadata_module_config: Arc<ModuleConfig>,
369 allocator_module_config: Arc<ModuleConfig>,
370 pub tm_factory: Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>,
371 pub msvc_imps_needed: bool,
372 pub target_pointer_width: String,
373 debuginfo: config::DebugInfo,
375 // Number of cgus excluding the allocator/metadata modules
376 pub total_cgus: usize,
377 // Handler to use for diagnostics produced during codegen.
378 pub diag_emitter: SharedEmitter,
379 // LLVM passes added by plugins.
380 pub plugin_passes: Vec<String>,
381 // LLVM optimizations for which we want to print remarks.
383 // Worker thread number
385 // The incremental compilation session directory, or None if we are not
386 // compiling incrementally
387 pub incr_comp_session_dir: Option<PathBuf>,
388 // Used to update CGU re-use information during the thinlto phase.
389 pub cgu_reuse_tracker: CguReuseTracker,
390 // Channel back to the main control thread to send messages to
391 coordinator_send: Sender<Box<dyn Any + Send>>,
392 // A reference to the TimeGraph so we can register timings. None means that
393 // measuring is disabled.
394 time_graph: Option<TimeGraph>,
395 // The assembler command if no_integrated_as option is enabled, None otherwise
396 assembler_cmd: Option<Arc<AssemblerCommand>>,
399 impl CodegenContext {
400 pub fn create_diag_handler(&self) -> Handler {
401 Handler::with_emitter(true, false, Box::new(self.diag_emitter.clone()))
404 pub(crate) fn config(&self, kind: ModuleKind) -> &ModuleConfig {
406 ModuleKind::Regular => &self.regular_module_config,
407 ModuleKind::Metadata => &self.metadata_module_config,
408 ModuleKind::Allocator => &self.allocator_module_config,
412 pub(crate) fn save_temp_bitcode(&self, module: &ModuleCodegen, name: &str) {
413 if !self.save_temps {
417 let ext = format!("{}.bc", name);
418 let cgu = Some(&module.name[..]);
419 let path = self.output_filenames.temp_path_ext(&ext, cgu);
420 let cstr = path2cstr(&path);
421 let llmod = module.module_llvm.llmod();
422 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
427 pub struct DiagnosticHandlers<'a> {
428 data: *mut (&'a CodegenContext, &'a Handler),
429 llcx: &'a llvm::Context,
432 impl<'a> DiagnosticHandlers<'a> {
433 pub fn new(cgcx: &'a CodegenContext,
434 handler: &'a Handler,
435 llcx: &'a llvm::Context) -> Self {
436 let data = Box::into_raw(Box::new((cgcx, handler)));
438 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data as *mut _);
439 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data as *mut _);
441 DiagnosticHandlers { data, llcx }
445 impl<'a> Drop for DiagnosticHandlers<'a> {
447 use std::ptr::null_mut;
449 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
450 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
451 drop(Box::from_raw(self.data));
456 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext,
459 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_owned());
462 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
468 let (cgcx, _) = *(user as *const (&CodegenContext, &Handler));
470 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
471 .expect("non-UTF8 SMDiagnostic");
473 report_inline_asm(cgcx, &msg, cookie);
476 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
480 let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler));
482 match llvm::diagnostic::Diagnostic::unpack(info) {
483 llvm::diagnostic::InlineAsm(inline) => {
484 report_inline_asm(cgcx,
485 &llvm::twine_to_string(inline.message),
489 llvm::diagnostic::Optimization(opt) => {
490 let enabled = match cgcx.remark {
492 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
496 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
505 llvm::diagnostic::PGO(diagnostic_ref) |
506 llvm::diagnostic::Linker(diagnostic_ref) => {
507 let msg = llvm::build_string(|s| {
508 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
509 }).expect("non-UTF8 diagnostic");
510 diag_handler.warn(&msg);
512 llvm::diagnostic::UnknownDiagnostic(..) => {},
516 // Unsafe due to LLVM calls.
517 unsafe fn optimize(cgcx: &CodegenContext,
518 diag_handler: &Handler,
519 module: &ModuleCodegen,
520 config: &ModuleConfig,
521 timeline: &mut Timeline)
522 -> Result<(), FatalError>
524 let llmod = module.module_llvm.llmod();
525 let llcx = &*module.module_llvm.llcx;
526 let tm = &*module.module_llvm.tm;
527 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
529 let module_name = module.name.clone();
530 let module_name = Some(&module_name[..]);
532 if config.emit_no_opt_bc {
533 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
534 let out = path2cstr(&out);
535 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
538 if config.opt_level.is_some() {
539 // Create the two optimizing pass managers. These mirror what clang
540 // does, and are by populated by LLVM's default PassManagerBuilder.
541 // Each manager has a different set of passes, but they also share
542 // some common passes.
543 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
544 let mpm = llvm::LLVMCreatePassManager();
547 // If we're verifying or linting, add them to the function pass
549 let addpass = |pass_name: &str| {
550 let pass_name = SmallCStr::new(pass_name);
551 let pass = match llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr()) {
553 None => return false,
555 let pass_manager = match llvm::LLVMRustPassKind(pass) {
556 llvm::PassKind::Function => &*fpm,
557 llvm::PassKind::Module => &*mpm,
558 llvm::PassKind::Other => {
559 diag_handler.err("Encountered LLVM pass kind we can't handle");
563 llvm::LLVMRustAddPass(pass_manager, pass);
567 if config.verify_llvm_ir { assert!(addpass("verify")); }
569 // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
570 // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
571 // we'll get errors in LLVM.
572 let using_thin_buffers = config.bitcode_needed();
573 let mut have_name_anon_globals_pass = false;
574 if !config.no_prepopulate_passes {
575 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
576 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
577 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
578 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal ||
579 (cgcx.lto != Lto::Fat && cgcx.opts.debugging_opts.cross_lang_lto.enabled());
580 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
581 if using_thin_buffers && !prepare_for_thin_lto {
582 assert!(addpass("name-anon-globals"));
583 have_name_anon_globals_pass = true;
585 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
586 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
587 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
591 for pass in &config.passes {
593 diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass));
595 if pass == "name-anon-globals" {
596 have_name_anon_globals_pass = true;
600 for pass in &cgcx.plugin_passes {
602 diag_handler.err(&format!("a plugin asked for LLVM pass \
603 `{}` but LLVM does not \
604 recognize it", pass));
606 if pass == "name-anon-globals" {
607 have_name_anon_globals_pass = true;
611 if using_thin_buffers && !have_name_anon_globals_pass {
612 // As described above, this will probably cause an error in LLVM
613 if config.no_prepopulate_passes {
614 diag_handler.err("The current compilation is going to use thin LTO buffers \
615 without running LLVM's NameAnonGlobals pass. \
616 This will likely cause errors in LLVM. Consider adding \
617 -C passes=name-anon-globals to the compiler command line.");
619 bug!("We are using thin LTO buffers without running the NameAnonGlobals pass. \
620 This will likely cause errors in LLVM and should never happen.");
625 diag_handler.abort_if_errors();
627 // Finally, run the actual optimization passes
628 time_ext(config.time_passes,
630 &format!("llvm function passes [{}]", module_name.unwrap()),
632 llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
634 timeline.record("fpm");
635 time_ext(config.time_passes,
637 &format!("llvm module passes [{}]", module_name.unwrap()),
639 llvm::LLVMRunPassManager(mpm, llmod)
642 // Deallocate managers that we're now done with
643 llvm::LLVMDisposePassManager(fpm);
644 llvm::LLVMDisposePassManager(mpm);
649 fn generate_lto_work(cgcx: &CodegenContext,
650 modules: Vec<ModuleCodegen>,
651 import_only_modules: Vec<(SerializedModule, WorkProduct)>)
652 -> Vec<(WorkItem, u64)>
654 let mut timeline = cgcx.time_graph.as_ref().map(|tg| {
655 tg.start(CODEGEN_WORKER_TIMELINE,
656 CODEGEN_WORK_PACKAGE_KIND,
658 }).unwrap_or(Timeline::noop());
659 let (lto_modules, copy_jobs) = lto::run(cgcx, modules, import_only_modules, &mut timeline)
660 .unwrap_or_else(|e| e.raise());
662 let lto_modules = lto_modules.into_iter().map(|module| {
663 let cost = module.cost();
664 (WorkItem::LTO(module), cost)
667 let copy_jobs = copy_jobs.into_iter().map(|wp| {
668 (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
669 name: wp.cgu_name.clone(),
674 lto_modules.chain(copy_jobs).collect()
677 unsafe fn codegen(cgcx: &CodegenContext,
678 diag_handler: &Handler,
679 module: ModuleCodegen,
680 config: &ModuleConfig,
681 timeline: &mut Timeline)
682 -> Result<CompiledModule, FatalError>
684 timeline.record("codegen");
686 let llmod = module.module_llvm.llmod();
687 let llcx = &*module.module_llvm.llcx;
688 let tm = &*module.module_llvm.tm;
689 let module_name = module.name.clone();
690 let module_name = Some(&module_name[..]);
691 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
693 if cgcx.msvc_imps_needed {
694 create_msvc_imps(cgcx, llcx, llmod);
697 // A codegen-specific pass manager is used to generate object
698 // files for an LLVM module.
700 // Apparently each of these pass managers is a one-shot kind of
701 // thing, so we create a new one for each type of output. The
702 // pass manager passed to the closure should be ensured to not
703 // escape the closure itself, and the manager should only be
705 unsafe fn with_codegen<'ll, F, R>(tm: &'ll llvm::TargetMachine,
706 llmod: &'ll llvm::Module,
709 where F: FnOnce(&'ll mut PassManager<'ll>) -> R,
711 let cpm = llvm::LLVMCreatePassManager();
712 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
713 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
717 // If we don't have the integrated assembler, then we need to emit asm
718 // from LLVM and use `gcc` to create the object file.
719 let asm_to_obj = config.emit_obj && config.no_integrated_as;
721 // Change what we write and cleanup based on whether obj files are
722 // just llvm bitcode. In that case write bitcode, and possibly
723 // delete the bitcode if it wasn't requested. Don't generate the
724 // machine code, instead copy the .o file from the .bc
725 let write_bc = config.emit_bc || config.obj_is_bitcode;
726 let rm_bc = !config.emit_bc && config.obj_is_bitcode;
727 let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
728 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
730 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
731 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
734 if write_bc || config.emit_bc_compressed || config.embed_bitcode {
735 let thin = ThinBuffer::new(llmod);
736 let data = thin.data();
737 timeline.record("make-bc");
740 if let Err(e) = fs::write(&bc_out, data) {
741 diag_handler.err(&format!("failed to write bytecode: {}", e));
743 timeline.record("write-bc");
746 if config.embed_bitcode {
747 embed_bitcode(cgcx, llcx, llmod, Some(data));
748 timeline.record("embed-bc");
751 if config.emit_bc_compressed {
752 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
753 let data = bytecode::encode(&module.name, data);
754 if let Err(e) = fs::write(&dst, data) {
755 diag_handler.err(&format!("failed to write bytecode: {}", e));
757 timeline.record("compress-bc");
759 } else if config.embed_bitcode_marker {
760 embed_bitcode(cgcx, llcx, llmod, None);
763 time_ext(config.time_passes, None, &format!("codegen passes [{}]", module_name.unwrap()),
764 || -> Result<(), FatalError> {
766 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
767 let out = path2cstr(&out);
769 extern "C" fn demangle_callback(input_ptr: *const c_char,
771 output_ptr: *mut c_char,
772 output_len: size_t) -> size_t {
774 slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
777 let input = match str::from_utf8(input) {
782 let output = unsafe {
783 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
785 let mut cursor = io::Cursor::new(output);
787 let demangled = match rustc_demangle::try_demangle(input) {
792 if let Err(_) = write!(cursor, "{:#}", demangled) {
793 // Possible only if provided buffer is not big enough
797 cursor.position() as size_t
800 with_codegen(tm, llmod, config.no_builtins, |cpm| {
801 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
802 llvm::LLVMDisposePassManager(cpm);
804 timeline.record("ir");
807 if config.emit_asm || asm_to_obj {
808 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
810 // We can't use the same module for asm and binary output, because that triggers
811 // various errors like invalid IR or broken binaries, so we might have to clone the
812 // module to produce the asm output
813 let llmod = if config.emit_obj {
814 llvm::LLVMCloneModule(llmod)
818 with_codegen(tm, llmod, config.no_builtins, |cpm| {
819 write_output_file(diag_handler, tm, cpm, llmod, &path,
820 llvm::FileType::AssemblyFile)
822 timeline.record("asm");
826 with_codegen(tm, llmod, config.no_builtins, |cpm| {
827 write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
828 llvm::FileType::ObjectFile)
830 timeline.record("obj");
831 } else if asm_to_obj {
832 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
833 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
834 timeline.record("asm_to_obj");
836 if !config.emit_asm && !cgcx.save_temps {
837 drop(fs::remove_file(&assembly));
845 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
846 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
847 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
852 debug!("removing_bitcode {:?}", bc_out);
853 if let Err(e) = fs::remove_file(&bc_out) {
854 diag_handler.err(&format!("failed to remove bitcode: {}", e));
860 Ok(module.into_compiled_module(config.emit_obj,
862 config.emit_bc_compressed,
863 &cgcx.output_filenames))
866 /// Embed the bitcode of an LLVM module in the LLVM module itself.
868 /// This is done primarily for iOS where it appears to be standard to compile C
869 /// code at least with `-fembed-bitcode` which creates two sections in the
872 /// * __LLVM,__bitcode
873 /// * __LLVM,__cmdline
875 /// It appears *both* of these sections are necessary to get the linker to
876 /// recognize what's going on. For us though we just always throw in an empty
879 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
880 /// embed an empty section.
882 /// Basically all of this is us attempting to follow in the footsteps of clang
883 /// on iOS. See #35968 for lots more info.
884 unsafe fn embed_bitcode(cgcx: &CodegenContext,
885 llcx: &llvm::Context,
886 llmod: &llvm::Module,
887 bitcode: Option<&[u8]>) {
888 let llconst = C_bytes_in_context(llcx, bitcode.unwrap_or(&[]));
889 let llglobal = llvm::LLVMAddGlobal(
892 "rustc.embedded.module\0".as_ptr() as *const _,
894 llvm::LLVMSetInitializer(llglobal, llconst);
896 let is_apple = cgcx.opts.target_triple.triple().contains("-ios") ||
897 cgcx.opts.target_triple.triple().contains("-darwin");
899 let section = if is_apple {
904 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
905 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
906 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
908 let llconst = C_bytes_in_context(llcx, &[]);
909 let llglobal = llvm::LLVMAddGlobal(
912 "rustc.embedded.cmdline\0".as_ptr() as *const _,
914 llvm::LLVMSetInitializer(llglobal, llconst);
915 let section = if is_apple {
920 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
921 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
924 pub(crate) struct CompiledModules {
925 pub modules: Vec<CompiledModule>,
926 pub metadata_module: CompiledModule,
927 pub allocator_module: Option<CompiledModule>,
930 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
931 sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
932 sess.opts.output_types.contains_key(&OutputType::Exe)
935 fn need_pre_thin_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
936 if sess.opts.incremental.is_none() {
944 Lto::ThinLocal => true,
948 pub fn start_async_codegen(tcx: TyCtxt,
949 time_graph: Option<TimeGraph>,
950 metadata: EncodedMetadata,
951 coordinator_receive: Receiver<Box<dyn Any + Send>>,
955 let crate_name = tcx.crate_name(LOCAL_CRATE);
956 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
957 let no_builtins = attr::contains_name(&tcx.hir.krate().attrs, "no_builtins");
958 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir.krate().attrs,
959 "windows_subsystem");
960 let windows_subsystem = subsystem.map(|subsystem| {
961 if subsystem != "windows" && subsystem != "console" {
962 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
963 `windows` and `console` are allowed",
966 subsystem.to_string()
969 let linker_info = LinkerInfo::new(tcx);
970 let crate_info = CrateInfo::new(tcx);
972 // Figure out what we actually need to build.
973 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
974 let mut metadata_config = ModuleConfig::new(vec![]);
975 let mut allocator_config = ModuleConfig::new(vec![]);
977 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
979 Sanitizer::Address => {
980 modules_config.passes.push("asan".to_owned());
981 modules_config.passes.push("asan-module".to_owned());
983 Sanitizer::Memory => {
984 modules_config.passes.push("msan".to_owned())
986 Sanitizer::Thread => {
987 modules_config.passes.push("tsan".to_owned())
993 if sess.opts.debugging_opts.profile {
994 modules_config.passes.push("insert-gcov-profiling".to_owned())
997 modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
998 modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
1000 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
1001 modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
1003 // Save all versions of the bytecode if we're saving our temporaries.
1004 if sess.opts.cg.save_temps {
1005 modules_config.emit_no_opt_bc = true;
1006 modules_config.emit_pre_thin_lto_bc = true;
1007 modules_config.emit_bc = true;
1008 modules_config.emit_lto_bc = true;
1009 metadata_config.emit_bc = true;
1010 allocator_config.emit_bc = true;
1013 // Emit compressed bitcode files for the crate if we're emitting an rlib.
1014 // Whenever an rlib is created, the bitcode is inserted into the archive in
1015 // order to allow LTO against it.
1016 if need_crate_bitcode_for_rlib(sess) {
1017 modules_config.emit_bc_compressed = true;
1018 allocator_config.emit_bc_compressed = true;
1021 modules_config.emit_pre_thin_lto_bc =
1022 need_pre_thin_lto_bitcode_for_incr_comp(sess);
1024 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
1025 tcx.sess.target.target.options.no_integrated_as;
1027 for output_type in sess.opts.output_types.keys() {
1028 match *output_type {
1029 OutputType::Bitcode => { modules_config.emit_bc = true; }
1030 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
1031 OutputType::Assembly => {
1032 modules_config.emit_asm = true;
1033 // If we're not using the LLVM assembler, this function
1034 // could be invoked specially with output_type_assembly, so
1035 // in this case we still want the metadata object file.
1036 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
1037 metadata_config.emit_obj = true;
1038 allocator_config.emit_obj = true;
1041 OutputType::Object => { modules_config.emit_obj = true; }
1042 OutputType::Metadata => { metadata_config.emit_obj = true; }
1043 OutputType::Exe => {
1044 modules_config.emit_obj = true;
1045 metadata_config.emit_obj = true;
1046 allocator_config.emit_obj = true;
1048 OutputType::Mir => {}
1049 OutputType::DepInfo => {}
1053 modules_config.set_flags(sess, no_builtins);
1054 metadata_config.set_flags(sess, no_builtins);
1055 allocator_config.set_flags(sess, no_builtins);
1057 // Exclude metadata and allocator modules from time_passes output, since
1058 // they throw off the "LLVM passes" measurement.
1059 metadata_config.time_passes = false;
1060 allocator_config.time_passes = false;
1062 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
1063 let (codegen_worker_send, codegen_worker_receive) = channel();
1065 let coordinator_thread = start_executing_work(tcx,
1068 codegen_worker_send,
1069 coordinator_receive,
1071 sess.jobserver.clone(),
1073 Arc::new(modules_config),
1074 Arc::new(metadata_config),
1075 Arc::new(allocator_config));
1086 coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
1087 codegen_worker_receive,
1088 shared_emitter_main,
1089 future: coordinator_thread,
1090 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1094 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
1096 compiled_modules: &CompiledModules,
1097 ) -> FxHashMap<WorkProductId, WorkProduct> {
1098 let mut work_products = FxHashMap::default();
1100 if sess.opts.incremental.is_none() {
1101 return work_products;
1104 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
1105 let mut files = vec![];
1107 if let Some(ref path) = module.object {
1108 files.push((WorkProductFileKind::Object, path.clone()));
1110 if let Some(ref path) = module.bytecode {
1111 files.push((WorkProductFileKind::Bytecode, path.clone()));
1113 if let Some(ref path) = module.bytecode_compressed {
1114 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
1117 if let Some((id, product)) =
1118 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files)
1120 work_products.insert(id, product);
1127 fn produce_final_output_artifacts(sess: &Session,
1128 compiled_modules: &CompiledModules,
1129 crate_output: &OutputFilenames) {
1130 let mut user_wants_bitcode = false;
1131 let mut user_wants_objects = false;
1133 // Produce final compile outputs.
1134 let copy_gracefully = |from: &Path, to: &Path| {
1135 if let Err(e) = fs::copy(from, to) {
1136 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
1140 let copy_if_one_unit = |output_type: OutputType,
1141 keep_numbered: bool| {
1142 if compiled_modules.modules.len() == 1 {
1143 // 1) Only one codegen unit. In this case it's no difficulty
1144 // to copy `foo.0.x` to `foo.x`.
1145 let module_name = Some(&compiled_modules.modules[0].name[..]);
1146 let path = crate_output.temp_path(output_type, module_name);
1147 copy_gracefully(&path,
1148 &crate_output.path(output_type));
1149 if !sess.opts.cg.save_temps && !keep_numbered {
1150 // The user just wants `foo.x`, not `foo.#module-name#.x`.
1151 remove(sess, &path);
1154 let ext = crate_output.temp_path(output_type, None)
1161 if crate_output.outputs.contains_key(&output_type) {
1162 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
1163 // no good solution for this case, so warn the user.
1164 sess.warn(&format!("ignoring emit path because multiple .{} files \
1165 were produced", ext));
1166 } else if crate_output.single_output_file.is_some() {
1167 // 3) Multiple codegen units, with `-o some_name`. We have
1168 // no good solution for this case, so warn the user.
1169 sess.warn(&format!("ignoring -o because multiple .{} files \
1170 were produced", ext));
1172 // 4) Multiple codegen units, but no explicit name. We
1173 // just leave the `foo.0.x` files in place.
1174 // (We don't have to do any work in this case.)
1179 // Flag to indicate whether the user explicitly requested bitcode.
1180 // Otherwise, we produced it only as a temporary output, and will need
1181 // to get rid of it.
1182 for output_type in crate_output.outputs.keys() {
1183 match *output_type {
1184 OutputType::Bitcode => {
1185 user_wants_bitcode = true;
1186 // Copy to .bc, but always keep the .0.bc. There is a later
1187 // check to figure out if we should delete .0.bc files, or keep
1188 // them for making an rlib.
1189 copy_if_one_unit(OutputType::Bitcode, true);
1191 OutputType::LlvmAssembly => {
1192 copy_if_one_unit(OutputType::LlvmAssembly, false);
1194 OutputType::Assembly => {
1195 copy_if_one_unit(OutputType::Assembly, false);
1197 OutputType::Object => {
1198 user_wants_objects = true;
1199 copy_if_one_unit(OutputType::Object, true);
1202 OutputType::Metadata |
1204 OutputType::DepInfo => {}
1208 // Clean up unwanted temporary files.
1210 // We create the following files by default:
1211 // - #crate#.#module-name#.bc
1212 // - #crate#.#module-name#.o
1213 // - #crate#.crate.metadata.bc
1214 // - #crate#.crate.metadata.o
1215 // - #crate#.o (linked from crate.##.o)
1216 // - #crate#.bc (copied from crate.##.bc)
1217 // We may create additional files if requested by the user (through
1218 // `-C save-temps` or `--emit=` flags).
1220 if !sess.opts.cg.save_temps {
1221 // Remove the temporary .#module-name#.o objects. If the user didn't
1222 // explicitly request bitcode (with --emit=bc), and the bitcode is not
1223 // needed for building an rlib, then we must remove .#module-name#.bc as
1226 // Specific rules for keeping .#module-name#.bc:
1227 // - If the user requested bitcode (`user_wants_bitcode`), and
1228 // codegen_units > 1, then keep it.
1229 // - If the user requested bitcode but codegen_units == 1, then we
1230 // can toss .#module-name#.bc because we copied it to .bc earlier.
1231 // - If we're not building an rlib and the user didn't request
1232 // bitcode, then delete .#module-name#.bc.
1233 // If you change how this works, also update back::link::link_rlib,
1234 // where .#module-name#.bc files are (maybe) deleted after making an
1236 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
1238 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
1240 let keep_numbered_objects = needs_crate_object ||
1241 (user_wants_objects && sess.codegen_units() > 1);
1243 for module in compiled_modules.modules.iter() {
1244 if let Some(ref path) = module.object {
1245 if !keep_numbered_objects {
1250 if let Some(ref path) = module.bytecode {
1251 if !keep_numbered_bitcode {
1257 if !user_wants_bitcode {
1258 if let Some(ref path) = compiled_modules.metadata_module.bytecode {
1259 remove(sess, &path);
1262 if let Some(ref allocator_module) = compiled_modules.allocator_module {
1263 if let Some(ref path) = allocator_module.bytecode {
1270 // We leave the following files around by default:
1272 // - #crate#.crate.metadata.o
1274 // These are used in linking steps and will be cleaned up afterward.
1277 pub(crate) fn dump_incremental_data(_codegen_results: &CodegenResults) {
1278 // FIXME(mw): This does not work at the moment because the situation has
1279 // become more complicated due to incremental LTO. Now a CGU
1280 // can have more than two caching states.
1281 // println!("[incremental] Re-using {} out of {} modules",
1282 // codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
1283 // codegen_results.modules.len());
1287 /// Optimize a newly codegened, totally unoptimized module.
1288 Optimize(ModuleCodegen),
1289 /// Copy the post-LTO artifacts from the incremental cache to the output
1291 CopyPostLtoArtifacts(CachedModuleCodegen),
1292 /// Perform (Thin)LTO on the given module.
1293 LTO(lto::LtoModuleCodegen),
1297 fn module_kind(&self) -> ModuleKind {
1299 WorkItem::Optimize(ref m) => m.kind,
1300 WorkItem::CopyPostLtoArtifacts(_) |
1301 WorkItem::LTO(_) => ModuleKind::Regular,
1305 fn name(&self) -> String {
1307 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
1308 WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
1309 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
1314 enum WorkItemResult {
1315 Compiled(CompiledModule),
1316 NeedsLTO(ModuleCodegen),
1319 fn execute_work_item(cgcx: &CodegenContext,
1320 work_item: WorkItem,
1321 timeline: &mut Timeline)
1322 -> Result<WorkItemResult, FatalError>
1324 let module_config = cgcx.config(work_item.module_kind());
1327 WorkItem::Optimize(module) => {
1328 execute_optimize_work_item(cgcx, module, module_config, timeline)
1330 WorkItem::CopyPostLtoArtifacts(module) => {
1331 execute_copy_from_cache_work_item(cgcx, module, module_config, timeline)
1333 WorkItem::LTO(module) => {
1334 execute_lto_work_item(cgcx, module, module_config, timeline)
1339 fn execute_optimize_work_item(cgcx: &CodegenContext,
1340 module: ModuleCodegen,
1341 module_config: &ModuleConfig,
1342 timeline: &mut Timeline)
1343 -> Result<WorkItemResult, FatalError>
1345 let diag_handler = cgcx.create_diag_handler();
1348 optimize(cgcx, &diag_handler, &module, module_config, timeline)?;
1351 let linker_does_lto = cgcx.opts.debugging_opts.cross_lang_lto.enabled();
1353 // After we've done the initial round of optimizations we need to
1354 // decide whether to synchronously codegen this module or ship it
1355 // back to the coordinator thread for further LTO processing (which
1356 // has to wait for all the initial modules to be optimized).
1358 // Here we dispatch based on the `cgcx.lto` and kind of module we're
1360 let needs_lto = match cgcx.lto {
1363 // If the linker does LTO, we don't have to do it. Note that we
1364 // keep doing full LTO, if it is requested, as not to break the
1365 // assumption that the output will be a single module.
1366 Lto::Thin | Lto::ThinLocal if linker_does_lto => false,
1368 // Here we've got a full crate graph LTO requested. We ignore
1369 // this, however, if the crate type is only an rlib as there's
1370 // no full crate graph to process, that'll happen later.
1372 // This use case currently comes up primarily for targets that
1373 // require LTO so the request for LTO is always unconditionally
1374 // passed down to the backend, but we don't actually want to do
1375 // anything about it yet until we've got a final product.
1376 Lto::Fat | Lto::Thin => {
1377 cgcx.crate_types.len() != 1 ||
1378 cgcx.crate_types[0] != config::CrateType::Rlib
1381 // When we're automatically doing ThinLTO for multi-codegen-unit
1382 // builds we don't actually want to LTO the allocator modules if
1383 // it shows up. This is due to various linker shenanigans that
1384 // we'll encounter later.
1386 module.kind != ModuleKind::Allocator
1390 // Metadata modules never participate in LTO regardless of the lto
1392 let needs_lto = needs_lto && module.kind != ModuleKind::Metadata;
1395 Ok(WorkItemResult::NeedsLTO(module))
1397 let module = unsafe {
1398 codegen(cgcx, &diag_handler, module, module_config, timeline)?
1400 Ok(WorkItemResult::Compiled(module))
1404 fn execute_copy_from_cache_work_item(cgcx: &CodegenContext,
1405 module: CachedModuleCodegen,
1406 module_config: &ModuleConfig,
1408 -> Result<WorkItemResult, FatalError>
1410 let incr_comp_session_dir = cgcx.incr_comp_session_dir
1413 let mut object = None;
1414 let mut bytecode = None;
1415 let mut bytecode_compressed = None;
1416 for (kind, saved_file) in &module.source.saved_files {
1417 let obj_out = match kind {
1418 WorkProductFileKind::Object => {
1419 let path = cgcx.output_filenames.temp_path(OutputType::Object,
1420 Some(&module.name));
1421 object = Some(path.clone());
1424 WorkProductFileKind::Bytecode => {
1425 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1426 Some(&module.name));
1427 bytecode = Some(path.clone());
1430 WorkProductFileKind::BytecodeCompressed => {
1431 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1433 .with_extension(RLIB_BYTECODE_EXTENSION);
1434 bytecode_compressed = Some(path.clone());
1438 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
1440 debug!("copying pre-existing module `{}` from {:?} to {}",
1444 if let Err(err) = link_or_copy(&source_file, &obj_out) {
1445 let diag_handler = cgcx.create_diag_handler();
1446 diag_handler.err(&format!("unable to copy {} to {}: {}",
1447 source_file.display(),
1453 assert_eq!(object.is_some(), module_config.emit_obj);
1454 assert_eq!(bytecode.is_some(), module_config.emit_bc);
1455 assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
1457 Ok(WorkItemResult::Compiled(CompiledModule {
1459 kind: ModuleKind::Regular,
1462 bytecode_compressed,
1466 fn execute_lto_work_item(cgcx: &CodegenContext,
1467 mut module: lto::LtoModuleCodegen,
1468 module_config: &ModuleConfig,
1469 timeline: &mut Timeline)
1470 -> Result<WorkItemResult, FatalError>
1472 let diag_handler = cgcx.create_diag_handler();
1475 let module = module.optimize(cgcx, timeline)?;
1476 let module = codegen(cgcx, &diag_handler, module, module_config, timeline)?;
1477 Ok(WorkItemResult::Compiled(module))
1482 Token(io::Result<Acquired>),
1484 result: ModuleCodegen,
1488 result: Result<CompiledModule, ()>,
1492 llvm_work_item: WorkItem,
1495 AddImportOnlyModule {
1496 module_data: SerializedModule,
1497 work_product: WorkProduct,
1506 code: Option<DiagnosticId>,
1510 #[derive(PartialEq, Clone, Copy, Debug)]
1511 enum MainThreadWorkerState {
1517 fn start_executing_work(tcx: TyCtxt,
1518 crate_info: &CrateInfo,
1519 shared_emitter: SharedEmitter,
1520 codegen_worker_send: Sender<Message>,
1521 coordinator_receive: Receiver<Box<dyn Any + Send>>,
1524 time_graph: Option<TimeGraph>,
1525 modules_config: Arc<ModuleConfig>,
1526 metadata_config: Arc<ModuleConfig>,
1527 allocator_config: Arc<ModuleConfig>)
1528 -> thread::JoinHandle<Result<CompiledModules, ()>> {
1529 let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1530 let sess = tcx.sess;
1532 // Compute the set of symbols we need to retain when doing LTO (if we need to)
1533 let exported_symbols = {
1534 let mut exported_symbols = FxHashMap::default();
1536 let copy_symbols = |cnum| {
1537 let symbols = tcx.exported_symbols(cnum)
1539 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1547 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1548 Some(Arc::new(exported_symbols))
1550 Lto::Fat | Lto::Thin => {
1551 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1552 for &cnum in tcx.crates().iter() {
1553 exported_symbols.insert(cnum, copy_symbols(cnum));
1555 Some(Arc::new(exported_symbols))
1560 // First up, convert our jobserver into a helper thread so we can use normal
1561 // mpsc channels to manage our messages and such.
1562 // After we've requested tokens then we'll, when we can,
1563 // get tokens on `coordinator_receive` which will
1564 // get managed in the main loop below.
1565 let coordinator_send2 = coordinator_send.clone();
1566 let helper = jobserver.into_helper_thread(move |token| {
1567 drop(coordinator_send2.send(Box::new(Message::Token(token))));
1568 }).expect("failed to spawn helper thread");
1570 let mut each_linked_rlib_for_lto = Vec::new();
1571 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1572 if link::ignored_for_lto(sess, crate_info, cnum) {
1575 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1578 let assembler_cmd = if modules_config.no_integrated_as {
1579 // HACK: currently we use linker (gcc) as our assembler
1580 let (linker, flavor) = link::linker_and_flavor(sess);
1582 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1583 cmd.args(&sess.target.target.options.asm_args);
1585 Some(Arc::new(AssemblerCommand { name, cmd }))
1590 let cgcx = CodegenContext {
1591 crate_types: sess.crate_types.borrow().clone(),
1592 each_linked_rlib_for_lto,
1594 no_landing_pads: sess.no_landing_pads(),
1595 fewer_names: sess.fewer_names(),
1596 save_temps: sess.opts.cg.save_temps,
1597 opts: Arc::new(sess.opts.clone()),
1598 time_passes: sess.time_passes(),
1600 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1601 remark: sess.opts.cg.remark.clone(),
1603 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1604 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1606 diag_emitter: shared_emitter.clone(),
1608 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1609 regular_module_config: modules_config,
1610 metadata_module_config: metadata_config,
1611 allocator_module_config: allocator_config,
1612 tm_factory: target_machine_factory(tcx.sess, false),
1614 msvc_imps_needed: msvc_imps_needed(tcx),
1615 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1616 debuginfo: tcx.sess.opts.debuginfo,
1620 // This is the "main loop" of parallel work happening for parallel codegen.
1621 // It's here that we manage parallelism, schedule work, and work with
1622 // messages coming from clients.
1624 // There are a few environmental pre-conditions that shape how the system
1627 // - Error reporting only can happen on the main thread because that's the
1628 // only place where we have access to the compiler `Session`.
1629 // - LLVM work can be done on any thread.
1630 // - Codegen can only happen on the main thread.
1631 // - Each thread doing substantial work most be in possession of a `Token`
1632 // from the `Jobserver`.
1633 // - The compiler process always holds one `Token`. Any additional `Tokens`
1634 // have to be requested from the `Jobserver`.
1638 // The error reporting restriction is handled separately from the rest: We
1639 // set up a `SharedEmitter` the holds an open channel to the main thread.
1640 // When an error occurs on any thread, the shared emitter will send the
1641 // error message to the receiver main thread (`SharedEmitterMain`). The
1642 // main thread will periodically query this error message queue and emit
1643 // any error messages it has received. It might even abort compilation if
1644 // has received a fatal error. In this case we rely on all other threads
1645 // being torn down automatically with the main thread.
1646 // Since the main thread will often be busy doing codegen work, error
1647 // reporting will be somewhat delayed, since the message queue can only be
1648 // checked in between to work packages.
1650 // Work Processing Infrastructure
1651 // ==============================
1652 // The work processing infrastructure knows three major actors:
1654 // - the coordinator thread,
1655 // - the main thread, and
1656 // - LLVM worker threads
1658 // The coordinator thread is running a message loop. It instructs the main
1659 // thread about what work to do when, and it will spawn off LLVM worker
1660 // threads as open LLVM WorkItems become available.
1662 // The job of the main thread is to codegen CGUs into LLVM work package
1663 // (since the main thread is the only thread that can do this). The main
1664 // thread will block until it receives a message from the coordinator, upon
1665 // which it will codegen one CGU, send it to the coordinator and block
1666 // again. This way the coordinator can control what the main thread is
1669 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1670 // available, it will spawn off a new LLVM worker thread and let it process
1671 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1672 // it will just shut down, which also frees all resources associated with
1673 // the given LLVM module, and sends a message to the coordinator that the
1674 // has been completed.
1678 // The scheduler's goal is to minimize the time it takes to complete all
1679 // work there is, however, we also want to keep memory consumption low
1680 // if possible. These two goals are at odds with each other: If memory
1681 // consumption were not an issue, we could just let the main thread produce
1682 // LLVM WorkItems at full speed, assuring maximal utilization of
1683 // Tokens/LLVM worker threads. However, since codegen usual is faster
1684 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1685 // WorkItem potentially holds on to a substantial amount of memory.
1687 // So the actual goal is to always produce just enough LLVM WorkItems as
1688 // not to starve our LLVM worker threads. That means, once we have enough
1689 // WorkItems in our queue, we can block the main thread, so it does not
1690 // produce more until we need them.
1692 // Doing LLVM Work on the Main Thread
1693 // ----------------------------------
1694 // Since the main thread owns the compiler processes implicit `Token`, it is
1695 // wasteful to keep it blocked without doing any work. Therefore, what we do
1696 // in this case is: We spawn off an additional LLVM worker thread that helps
1697 // reduce the queue. The work it is doing corresponds to the implicit
1698 // `Token`. The coordinator will mark the main thread as being busy with
1699 // LLVM work. (The actual work happens on another OS thread but we just care
1700 // about `Tokens`, not actual threads).
1702 // When any LLVM worker thread finishes while the main thread is marked as
1703 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1704 // of the just finished thread to the LLVM worker thread that is working on
1705 // behalf of the main thread's implicit Token, thus freeing up the main
1706 // thread again. The coordinator can then again decide what the main thread
1707 // should do. This allows the coordinator to make decisions at more points
1710 // Striking a Balance between Throughput and Memory Consumption
1711 // ------------------------------------------------------------
1712 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1713 // memory consumption as low as possible, are in conflict with each other,
1714 // we have to find a trade off between them. Right now, the goal is to keep
1715 // all workers busy, which means that no worker should find the queue empty
1716 // when it is ready to start.
1717 // How do we do achieve this? Good question :) We actually never know how
1718 // many `Tokens` are potentially available so it's hard to say how much to
1719 // fill up the queue before switching the main thread to LLVM work. Also we
1720 // currently don't have a means to estimate how long a running LLVM worker
1721 // will still be busy with it's current WorkItem. However, we know the
1722 // maximal count of available Tokens that makes sense (=the number of CPU
1723 // cores), so we can take a conservative guess. The heuristic we use here
1724 // is implemented in the `queue_full_enough()` function.
1726 // Some Background on Jobservers
1727 // -----------------------------
1728 // It's worth also touching on the management of parallelism here. We don't
1729 // want to just spawn a thread per work item because while that's optimal
1730 // parallelism it may overload a system with too many threads or violate our
1731 // configuration for the maximum amount of cpu to use for this process. To
1732 // manage this we use the `jobserver` crate.
1734 // Job servers are an artifact of GNU make and are used to manage
1735 // parallelism between processes. A jobserver is a glorified IPC semaphore
1736 // basically. Whenever we want to run some work we acquire the semaphore,
1737 // and whenever we're done with that work we release the semaphore. In this
1738 // manner we can ensure that the maximum number of parallel workers is
1739 // capped at any one point in time.
1741 // LTO and the coordinator thread
1742 // ------------------------------
1744 // The final job the coordinator thread is responsible for is managing LTO
1745 // and how that works. When LTO is requested what we'll to is collect all
1746 // optimized LLVM modules into a local vector on the coordinator. Once all
1747 // modules have been codegened and optimized we hand this to the `lto`
1748 // module for further optimization. The `lto` module will return back a list
1749 // of more modules to work on, which the coordinator will continue to spawn
1752 // Each LLVM module is automatically sent back to the coordinator for LTO if
1753 // necessary. There's already optimizations in place to avoid sending work
1754 // back to the coordinator if LTO isn't requested.
1755 return thread::spawn(move || {
1756 // We pretend to be within the top-level LLVM time-passes task here:
1759 let max_workers = ::num_cpus::get();
1760 let mut worker_id_counter = 0;
1761 let mut free_worker_ids = Vec::new();
1762 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1763 if let Some(id) = free_worker_ids.pop() {
1766 let id = worker_id_counter;
1767 worker_id_counter += 1;
1772 // This is where we collect codegen units that have gone all the way
1773 // through codegen and LLVM.
1774 let mut compiled_modules = vec![];
1775 let mut compiled_metadata_module = None;
1776 let mut compiled_allocator_module = None;
1777 let mut needs_lto = Vec::new();
1778 let mut lto_import_only_modules = Vec::new();
1779 let mut started_lto = false;
1780 let mut codegen_aborted = false;
1782 // This flag tracks whether all items have gone through codegens
1783 let mut codegen_done = false;
1785 // This is the queue of LLVM work items that still need processing.
1786 let mut work_items = Vec::<(WorkItem, u64)>::new();
1788 // This are the Jobserver Tokens we currently hold. Does not include
1789 // the implicit Token the compiler process owns no matter what.
1790 let mut tokens = Vec::new();
1792 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1793 let mut running = 0;
1795 let mut llvm_start_time = None;
1797 // Run the message loop while there's still anything that needs message
1798 // processing. Note that as soon as codegen is aborted we simply want to
1799 // wait for all existing work to finish, so many of the conditions here
1800 // only apply if codegen hasn't been aborted as they represent pending
1802 while !codegen_done ||
1804 (!codegen_aborted && (
1805 work_items.len() > 0 ||
1806 needs_lto.len() > 0 ||
1807 lto_import_only_modules.len() > 0 ||
1808 main_thread_worker_state != MainThreadWorkerState::Idle
1812 // While there are still CGUs to be codegened, the coordinator has
1813 // to decide how to utilize the compiler processes implicit Token:
1814 // For codegenning more CGU or for running them through LLVM.
1816 if main_thread_worker_state == MainThreadWorkerState::Idle {
1817 if !queue_full_enough(work_items.len(), running, max_workers) {
1818 // The queue is not full enough, codegen more items:
1819 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1820 panic!("Could not send Message::CodegenItem to main thread")
1822 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1824 // The queue is full enough to not let the worker
1825 // threads starve. Use the implicit Token to do some
1827 let (item, _) = work_items.pop()
1828 .expect("queue empty - queue_full_enough() broken?");
1829 let cgcx = CodegenContext {
1830 worker: get_worker_id(&mut free_worker_ids),
1833 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1834 &mut llvm_start_time);
1835 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1836 spawn_work(cgcx, item);
1839 } else if codegen_aborted {
1840 // don't queue up any more work if codegen was aborted, we're
1841 // just waiting for our existing children to finish
1843 // If we've finished everything related to normal codegen
1844 // then it must be the case that we've got some LTO work to do.
1845 // Perform the serial work here of figuring out what we're
1846 // going to LTO and then push a bunch of work items onto our
1848 if work_items.len() == 0 &&
1850 main_thread_worker_state == MainThreadWorkerState::Idle {
1851 assert!(!started_lto);
1852 assert!(needs_lto.len() + lto_import_only_modules.len() > 0);
1854 let modules = mem::replace(&mut needs_lto, Vec::new());
1855 let import_only_modules =
1856 mem::replace(&mut lto_import_only_modules, Vec::new());
1857 for (work, cost) in generate_lto_work(&cgcx, modules, import_only_modules) {
1858 let insertion_index = work_items
1859 .binary_search_by_key(&cost, |&(_, cost)| cost)
1860 .unwrap_or_else(|e| e);
1861 work_items.insert(insertion_index, (work, cost));
1862 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1863 helper.request_token();
1868 // In this branch, we know that everything has been codegened,
1869 // so it's just a matter of determining whether the implicit
1870 // Token is free to use for LLVM work.
1871 match main_thread_worker_state {
1872 MainThreadWorkerState::Idle => {
1873 if let Some((item, _)) = work_items.pop() {
1874 let cgcx = CodegenContext {
1875 worker: get_worker_id(&mut free_worker_ids),
1878 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1879 &mut llvm_start_time);
1880 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1881 spawn_work(cgcx, item);
1883 // There is no unstarted work, so let the main thread
1884 // take over for a running worker. Otherwise the
1885 // implicit token would just go to waste.
1886 // We reduce the `running` counter by one. The
1887 // `tokens.truncate()` below will take care of
1888 // giving the Token back.
1889 debug_assert!(running > 0);
1891 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1894 MainThreadWorkerState::Codegenning => {
1895 bug!("codegen worker should not be codegenning after \
1896 codegen was already completed")
1898 MainThreadWorkerState::LLVMing => {
1899 // Already making good use of that token
1904 // Spin up what work we can, only doing this while we've got available
1905 // parallelism slots and work left to spawn.
1906 while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1907 let (item, _) = work_items.pop().unwrap();
1909 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1910 &mut llvm_start_time);
1912 let cgcx = CodegenContext {
1913 worker: get_worker_id(&mut free_worker_ids),
1917 spawn_work(cgcx, item);
1921 // Relinquish accidentally acquired extra tokens
1922 tokens.truncate(running);
1924 let msg = coordinator_receive.recv().unwrap();
1925 match *msg.downcast::<Message>().ok().unwrap() {
1926 // Save the token locally and the next turn of the loop will use
1927 // this to spawn a new unit of work, or it may get dropped
1928 // immediately if we have no more work to spawn.
1929 Message::Token(token) => {
1934 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1935 // If the main thread token is used for LLVM work
1936 // at the moment, we turn that thread into a regular
1937 // LLVM worker thread, so the main thread is free
1938 // to react to codegen demand.
1939 main_thread_worker_state = MainThreadWorkerState::Idle;
1944 let msg = &format!("failed to acquire jobserver token: {}", e);
1945 shared_emitter.fatal(msg);
1946 // Exit the coordinator thread
1952 Message::CodegenDone { llvm_work_item, cost } => {
1953 // We keep the queue sorted by estimated processing cost,
1954 // so that more expensive items are processed earlier. This
1955 // is good for throughput as it gives the main thread more
1956 // time to fill up the queue and it avoids scheduling
1957 // expensive items to the end.
1958 // Note, however, that this is not ideal for memory
1959 // consumption, as LLVM module sizes are not evenly
1961 let insertion_index =
1962 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1963 let insertion_index = match insertion_index {
1964 Ok(idx) | Err(idx) => idx
1966 work_items.insert(insertion_index, (llvm_work_item, cost));
1968 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1969 helper.request_token();
1971 assert!(!codegen_aborted);
1972 assert_eq!(main_thread_worker_state,
1973 MainThreadWorkerState::Codegenning);
1974 main_thread_worker_state = MainThreadWorkerState::Idle;
1977 Message::CodegenComplete => {
1978 codegen_done = true;
1979 assert!(!codegen_aborted);
1980 assert_eq!(main_thread_worker_state,
1981 MainThreadWorkerState::Codegenning);
1982 main_thread_worker_state = MainThreadWorkerState::Idle;
1985 // If codegen is aborted that means translation was aborted due
1986 // to some normal-ish compiler error. In this situation we want
1987 // to exit as soon as possible, but we want to make sure all
1988 // existing work has finished. Flag codegen as being done, and
1989 // then conditions above will ensure no more work is spawned but
1990 // we'll keep executing this loop until `running` hits 0.
1991 Message::CodegenAborted => {
1992 assert!(!codegen_aborted);
1993 codegen_done = true;
1994 codegen_aborted = true;
1995 assert_eq!(main_thread_worker_state,
1996 MainThreadWorkerState::Codegenning);
1999 // If a thread exits successfully then we drop a token associated
2000 // with that worker and update our `running` count. We may later
2001 // re-acquire a token to continue running more work. We may also not
2002 // actually drop a token here if the worker was running with an
2003 // "ephemeral token"
2005 // Note that if the thread failed that means it panicked, so we
2006 // abort immediately.
2007 Message::Done { result: Ok(compiled_module), worker_id } => {
2008 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
2009 main_thread_worker_state = MainThreadWorkerState::Idle;
2014 free_worker_ids.push(worker_id);
2016 match compiled_module.kind {
2017 ModuleKind::Regular => {
2018 compiled_modules.push(compiled_module);
2020 ModuleKind::Metadata => {
2021 assert!(compiled_metadata_module.is_none());
2022 compiled_metadata_module = Some(compiled_module);
2024 ModuleKind::Allocator => {
2025 assert!(compiled_allocator_module.is_none());
2026 compiled_allocator_module = Some(compiled_module);
2030 Message::NeedsLTO { result, worker_id } => {
2031 assert!(!started_lto);
2032 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
2033 main_thread_worker_state = MainThreadWorkerState::Idle;
2037 free_worker_ids.push(worker_id);
2038 needs_lto.push(result);
2040 Message::AddImportOnlyModule { module_data, work_product } => {
2041 assert!(!started_lto);
2042 assert!(!codegen_done);
2043 assert_eq!(main_thread_worker_state,
2044 MainThreadWorkerState::Codegenning);
2045 lto_import_only_modules.push((module_data, work_product));
2046 main_thread_worker_state = MainThreadWorkerState::Idle;
2048 Message::Done { result: Err(()), worker_id: _ } => {
2049 bug!("worker thread panicked");
2051 Message::CodegenItem => {
2052 bug!("the coordinator should not receive codegen requests")
2057 if let Some(llvm_start_time) = llvm_start_time {
2058 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
2059 // This is the top-level timing for all of LLVM, set the time-depth
2062 print_time_passes_entry(cgcx.time_passes,
2067 // Regardless of what order these modules completed in, report them to
2068 // the backend in the same order every time to ensure that we're handing
2069 // out deterministic results.
2070 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
2072 let compiled_metadata_module = compiled_metadata_module
2073 .expect("Metadata module not compiled?");
2075 Ok(CompiledModules {
2076 modules: compiled_modules,
2077 metadata_module: compiled_metadata_module,
2078 allocator_module: compiled_allocator_module,
2082 // A heuristic that determines if we have enough LLVM WorkItems in the
2083 // queue so that the main thread can do LLVM work instead of codegen
2084 fn queue_full_enough(items_in_queue: usize,
2085 workers_running: usize,
2086 max_workers: usize) -> bool {
2088 items_in_queue > 0 &&
2089 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
2092 fn maybe_start_llvm_timer(config: &ModuleConfig,
2093 llvm_start_time: &mut Option<Instant>) {
2094 // We keep track of the -Ztime-passes output manually,
2095 // since the closure-based interface does not fit well here.
2096 if config.time_passes {
2097 if llvm_start_time.is_none() {
2098 *llvm_start_time = Some(Instant::now());
2104 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
2105 pub const CODEGEN_WORKER_TIMELINE: time_graph::TimelineId =
2106 time_graph::TimelineId(CODEGEN_WORKER_ID);
2107 pub const CODEGEN_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2108 time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
2109 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2110 time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
2112 fn spawn_work(cgcx: CodegenContext, work: WorkItem) {
2113 let depth = time_depth();
2115 thread::spawn(move || {
2116 set_time_depth(depth);
2118 // Set up a destructor which will fire off a message that we're done as
2121 coordinator_send: Sender<Box<dyn Any + Send>>,
2122 result: Option<WorkItemResult>,
2125 impl Drop for Bomb {
2126 fn drop(&mut self) {
2127 let worker_id = self.worker_id;
2128 let msg = match self.result.take() {
2129 Some(WorkItemResult::Compiled(m)) => {
2130 Message::Done { result: Ok(m), worker_id }
2132 Some(WorkItemResult::NeedsLTO(m)) => {
2133 Message::NeedsLTO { result: m, worker_id }
2135 None => Message::Done { result: Err(()), worker_id }
2137 drop(self.coordinator_send.send(Box::new(msg)));
2141 let mut bomb = Bomb {
2142 coordinator_send: cgcx.coordinator_send.clone(),
2144 worker_id: cgcx.worker,
2147 // Execute the work itself, and if it finishes successfully then flag
2148 // ourselves as a success as well.
2150 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
2151 // as a diagnostic was already sent off to the main thread - just
2152 // surface that there was an error in this worker.
2154 let timeline = cgcx.time_graph.as_ref().map(|tg| {
2155 tg.start(time_graph::TimelineId(cgcx.worker),
2156 LLVM_WORK_PACKAGE_KIND,
2159 let mut timeline = timeline.unwrap_or(Timeline::noop());
2160 execute_work_item(&cgcx, work, &mut timeline).ok()
2165 pub fn run_assembler(cgcx: &CodegenContext, handler: &Handler, assembly: &Path, object: &Path) {
2166 let assembler = cgcx.assembler_cmd
2168 .expect("cgcx.assembler_cmd is missing?");
2170 let pname = &assembler.name;
2171 let mut cmd = assembler.cmd.clone();
2172 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
2173 debug!("{:?}", cmd);
2175 match cmd.output() {
2177 if !prog.status.success() {
2178 let mut note = prog.stderr.clone();
2179 note.extend_from_slice(&prog.stdout);
2181 handler.struct_err(&format!("linking with `{}` failed: {}",
2184 .note(&format!("{:?}", &cmd))
2185 .note(str::from_utf8(¬e[..]).unwrap())
2187 handler.abort_if_errors();
2191 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
2192 handler.abort_if_errors();
2197 pub unsafe fn with_llvm_pmb(llmod: &llvm::Module,
2198 config: &ModuleConfig,
2199 opt_level: llvm::CodeGenOptLevel,
2200 prepare_for_thin_lto: bool,
2201 f: &mut dyn FnMut(&llvm::PassManagerBuilder)) {
2204 // Create the PassManagerBuilder for LLVM. We configure it with
2205 // reasonable defaults and prepare it to actually populate the pass
2207 let builder = llvm::LLVMPassManagerBuilderCreate();
2208 let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
2209 let inline_threshold = config.inline_threshold;
2211 let pgo_gen_path = config.pgo_gen.as_ref().map(|s| {
2212 let s = if s.is_empty() { "default_%m.profraw" } else { s };
2213 CString::new(s.as_bytes()).unwrap()
2216 let pgo_use_path = if config.pgo_use.is_empty() {
2219 Some(CString::new(config.pgo_use.as_bytes()).unwrap())
2222 llvm::LLVMRustConfigurePassManagerBuilder(
2225 config.merge_functions,
2226 config.vectorize_slp,
2227 config.vectorize_loop,
2228 prepare_for_thin_lto,
2229 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2230 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2233 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
2235 if opt_size != llvm::CodeGenOptSizeNone {
2236 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
2239 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
2241 // Here we match what clang does (kinda). For O0 we only inline
2242 // always-inline functions (but don't add lifetime intrinsics), at O1 we
2243 // inline with lifetime intrinsics, and O2+ we add an inliner with a
2244 // thresholds copied from clang.
2245 match (opt_level, opt_size, inline_threshold) {
2247 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
2249 (llvm::CodeGenOptLevel::Aggressive, ..) => {
2250 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
2252 (_, llvm::CodeGenOptSizeDefault, _) => {
2253 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
2255 (_, llvm::CodeGenOptSizeAggressive, _) => {
2256 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
2258 (llvm::CodeGenOptLevel::None, ..) => {
2259 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
2261 (llvm::CodeGenOptLevel::Less, ..) => {
2262 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
2264 (llvm::CodeGenOptLevel::Default, ..) => {
2265 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
2267 (llvm::CodeGenOptLevel::Other, ..) => {
2268 bug!("CodeGenOptLevel::Other selected")
2273 llvm::LLVMPassManagerBuilderDispose(builder);
2277 enum SharedEmitterMessage {
2278 Diagnostic(Diagnostic),
2279 InlineAsmError(u32, String),
2285 pub struct SharedEmitter {
2286 sender: Sender<SharedEmitterMessage>,
2289 pub struct SharedEmitterMain {
2290 receiver: Receiver<SharedEmitterMessage>,
2293 impl SharedEmitter {
2294 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
2295 let (sender, receiver) = channel();
2297 (SharedEmitter { sender }, SharedEmitterMain { receiver })
2300 fn inline_asm_error(&self, cookie: u32, msg: String) {
2301 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
2304 fn fatal(&self, msg: &str) {
2305 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2309 impl Emitter for SharedEmitter {
2310 fn emit(&mut self, db: &DiagnosticBuilder) {
2311 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2313 code: db.code.clone(),
2316 for child in &db.children {
2317 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2318 msg: child.message(),
2323 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
2327 impl SharedEmitterMain {
2328 pub fn check(&self, sess: &Session, blocking: bool) {
2330 let message = if blocking {
2331 match self.receiver.recv() {
2332 Ok(message) => Ok(message),
2336 match self.receiver.try_recv() {
2337 Ok(message) => Ok(message),
2343 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2344 let handler = sess.diagnostic();
2347 handler.emit_with_code(&MultiSpan::new(),
2353 handler.emit(&MultiSpan::new(),
2359 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
2360 match Mark::from_u32(cookie).expn_info() {
2361 Some(ei) => sess.span_err(ei.call_site, &msg),
2362 None => sess.err(&msg),
2365 Ok(SharedEmitterMessage::AbortIfErrors) => {
2366 sess.abort_if_errors();
2368 Ok(SharedEmitterMessage::Fatal(msg)) => {
2380 pub struct OngoingCodegen {
2383 metadata: EncodedMetadata,
2384 windows_subsystem: Option<String>,
2385 linker_info: LinkerInfo,
2386 crate_info: CrateInfo,
2387 time_graph: Option<TimeGraph>,
2388 coordinator_send: Sender<Box<dyn Any + Send>>,
2389 codegen_worker_receive: Receiver<Message>,
2390 shared_emitter_main: SharedEmitterMain,
2391 future: thread::JoinHandle<Result<CompiledModules, ()>>,
2392 output_filenames: Arc<OutputFilenames>,
2395 impl OngoingCodegen {
2399 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
2400 self.shared_emitter_main.check(sess, true);
2401 let compiled_modules = match self.future.join() {
2402 Ok(Ok(compiled_modules)) => compiled_modules,
2404 sess.abort_if_errors();
2405 panic!("expected abort due to worker thread errors")
2408 bug!("panic during codegen/LLVM phase");
2412 sess.cgu_reuse_tracker.check_expected_reuse(sess);
2414 sess.abort_if_errors();
2416 if let Some(time_graph) = self.time_graph {
2417 time_graph.dump(&format!("{}-timings", self.crate_name));
2421 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
2423 produce_final_output_artifacts(sess,
2425 &self.output_filenames);
2427 // FIXME: time_llvm_passes support - does this use a global context or
2429 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
2430 unsafe { llvm::LLVMRustPrintPassTimings(); }
2434 crate_name: self.crate_name,
2435 crate_hash: self.crate_hash,
2436 metadata: self.metadata,
2437 windows_subsystem: self.windows_subsystem,
2438 linker_info: self.linker_info,
2439 crate_info: self.crate_info,
2441 modules: compiled_modules.modules,
2442 allocator_module: compiled_modules.allocator_module,
2443 metadata_module: compiled_modules.metadata_module,
2447 pub(crate) fn submit_pre_codegened_module_to_llvm(&self,
2449 module: ModuleCodegen) {
2450 self.wait_for_signal_to_codegen_item();
2451 self.check_for_errors(tcx.sess);
2453 // These are generally cheap and won't through off scheduling.
2455 submit_codegened_module_to_llvm(tcx, module, cost);
2458 pub fn codegen_finished(&self, tcx: TyCtxt) {
2459 self.wait_for_signal_to_codegen_item();
2460 self.check_for_errors(tcx.sess);
2461 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete)));
2464 /// Consume this context indicating that codegen was entirely aborted, and
2465 /// we need to exit as quickly as possible.
2467 /// This method blocks the current thread until all worker threads have
2468 /// finished, and all worker threads should have exited or be real close to
2469 /// exiting at this point.
2470 pub fn codegen_aborted(self) {
2471 // Signal to the coordinator it should spawn no more work and start
2473 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted)));
2474 drop(self.future.join());
2477 pub fn check_for_errors(&self, sess: &Session) {
2478 self.shared_emitter_main.check(sess, false);
2481 pub fn wait_for_signal_to_codegen_item(&self) {
2482 match self.codegen_worker_receive.recv() {
2483 Ok(Message::CodegenItem) => {
2486 Ok(_) => panic!("unexpected message"),
2488 // One of the LLVM threads must have panicked, fall through so
2489 // error handling can be reached.
2495 // impl Drop for OngoingCodegen {
2496 // fn drop(&mut self) {
2500 pub(crate) fn submit_codegened_module_to_llvm(tcx: TyCtxt,
2501 module: ModuleCodegen,
2503 let llvm_work_item = WorkItem::Optimize(module);
2504 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2510 pub(crate) fn submit_post_lto_module_to_llvm(tcx: TyCtxt,
2511 module: CachedModuleCodegen) {
2512 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2513 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2519 pub(crate) fn submit_pre_lto_module_to_llvm(tcx: TyCtxt,
2520 module: CachedModuleCodegen) {
2521 let filename = pre_lto_bitcode_filename(&module.name);
2522 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2523 let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
2524 panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
2528 memmap::Mmap::map(&file).unwrap_or_else(|e| {
2529 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2533 // Schedule the module to be loaded
2534 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::AddImportOnlyModule {
2535 module_data: SerializedModule::FromUncompressedFile(mmap),
2536 work_product: module.source,
2540 pub(super) fn pre_lto_bitcode_filename(module_name: &str) -> String {
2541 format!("{}.{}", module_name, PRE_THIN_LTO_BC_EXT)
2544 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
2545 // This should never be true (because it's not supported). If it is true,
2546 // something is wrong with commandline arg validation.
2547 assert!(!(tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() &&
2548 tcx.sess.target.target.options.is_like_msvc &&
2549 tcx.sess.opts.cg.prefer_dynamic));
2551 tcx.sess.target.target.options.is_like_msvc &&
2552 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
2553 // ThinLTO can't handle this workaround in all cases, so we don't
2554 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2555 // dynamic linking when cross-language LTO is enabled.
2556 !tcx.sess.opts.debugging_opts.cross_lang_lto.enabled()
2559 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2560 // This is required to satisfy `dllimport` references to static data in .rlibs
2561 // when using MSVC linker. We do this only for data, as linker can fix up
2562 // code references on its own.
2563 // See #26591, #27438
2564 fn create_msvc_imps(cgcx: &CodegenContext, llcx: &llvm::Context, llmod: &llvm::Module) {
2565 if !cgcx.msvc_imps_needed {
2568 // The x86 ABI seems to require that leading underscores are added to symbol
2569 // names, so we need an extra underscore on 32-bit. There's also a leading
2570 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2571 // underscores added in front).
2572 let prefix = if cgcx.target_pointer_width == "32" {
2578 let i8p_ty = Type::i8p_llcx::<Value>(llcx);
2579 let globals = base::iter_globals(llmod)
2581 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
2582 llvm::LLVMIsDeclaration(val) == 0
2585 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2586 let mut imp_name = prefix.as_bytes().to_vec();
2587 imp_name.extend(name.to_bytes());
2588 let imp_name = CString::new(imp_name).unwrap();
2591 .collect::<Vec<_>>();
2592 for (imp_name, val) in globals {
2593 let imp = llvm::LLVMAddGlobal(llmod,
2595 imp_name.as_ptr() as *const _);
2596 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
2597 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);